potree.js 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = global || self, factory(global.Potree = {}));
  5. }(this, (function (exports) { 'use strict';
  6. // threejs.org/license
  7. const REVISION = '124';
  8. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  9. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  10. const CullFaceNone = 0;
  11. const CullFaceBack = 1;
  12. const CullFaceFront = 2;
  13. const CullFaceFrontBack = 3;
  14. const BasicShadowMap = 0;
  15. const PCFShadowMap = 1;
  16. const PCFSoftShadowMap = 2;
  17. const VSMShadowMap = 3;
  18. const FrontSide = 0;
  19. const BackSide = 1;
  20. const DoubleSide = 2;
  21. const FlatShading$1 = 1;
  22. const SmoothShading = 2;
  23. const NoBlending = 0;
  24. const NormalBlending = 1;
  25. const AdditiveBlending = 2;
  26. const SubtractiveBlending = 3;
  27. const MultiplyBlending = 4;
  28. const CustomBlending = 5;
  29. const AddEquation = 100;
  30. const SubtractEquation = 101;
  31. const ReverseSubtractEquation = 102;
  32. const MinEquation = 103;
  33. const MaxEquation = 104;
  34. const ZeroFactor = 200;
  35. const OneFactor = 201;
  36. const SrcColorFactor = 202;
  37. const OneMinusSrcColorFactor = 203;
  38. const SrcAlphaFactor = 204;
  39. const OneMinusSrcAlphaFactor = 205;
  40. const DstAlphaFactor = 206;
  41. const OneMinusDstAlphaFactor = 207;
  42. const DstColorFactor = 208;
  43. const OneMinusDstColorFactor = 209;
  44. const SrcAlphaSaturateFactor = 210;
  45. const NeverDepth = 0;
  46. const AlwaysDepth = 1;
  47. const LessDepth = 2;
  48. const LessEqualDepth = 3;
  49. const EqualDepth = 4;
  50. const GreaterEqualDepth = 5;
  51. const GreaterDepth = 6;
  52. const NotEqualDepth = 7;
  53. const MultiplyOperation = 0;
  54. const MixOperation = 1;
  55. const AddOperation = 2;
  56. const NoToneMapping = 0;
  57. const LinearToneMapping = 1;
  58. const ReinhardToneMapping = 2;
  59. const CineonToneMapping = 3;
  60. const ACESFilmicToneMapping = 4;
  61. const CustomToneMapping = 5;
  62. const UVMapping = 300;
  63. const CubeReflectionMapping = 301;
  64. const CubeRefractionMapping = 302;
  65. const EquirectangularReflectionMapping = 303;
  66. const EquirectangularRefractionMapping = 304;
  67. const CubeUVReflectionMapping = 306;
  68. const CubeUVRefractionMapping = 307;
  69. const RepeatWrapping = 1000;
  70. const ClampToEdgeWrapping = 1001;
  71. const MirroredRepeatWrapping = 1002;
  72. const NearestFilter = 1003;
  73. const NearestMipmapNearestFilter = 1004;
  74. const NearestMipMapNearestFilter = 1004;
  75. const NearestMipmapLinearFilter = 1005;
  76. const NearestMipMapLinearFilter = 1005;
  77. const LinearFilter = 1006;
  78. const LinearMipmapNearestFilter = 1007;
  79. const LinearMipMapNearestFilter = 1007;
  80. const LinearMipmapLinearFilter = 1008;
  81. const LinearMipMapLinearFilter = 1008;
  82. const UnsignedByteType = 1009;
  83. const ByteType = 1010;
  84. const ShortType = 1011;
  85. const UnsignedShortType = 1012;
  86. const IntType = 1013;
  87. const UnsignedIntType = 1014;
  88. const FloatType = 1015;
  89. const HalfFloatType = 1016;
  90. const UnsignedShort4444Type = 1017;
  91. const UnsignedShort5551Type = 1018;
  92. const UnsignedShort565Type = 1019;
  93. const UnsignedInt248Type$1 = 1020;
  94. const AlphaFormat = 1021;
  95. const RGBFormat = 1022;
  96. const RGBAFormat = 1023;
  97. const LuminanceFormat = 1024;
  98. const LuminanceAlphaFormat = 1025;
  99. const RGBEFormat = RGBAFormat;
  100. const DepthFormat = 1026;
  101. const DepthStencilFormat = 1027;
  102. const RedFormat = 1028;
  103. const RedIntegerFormat = 1029;
  104. const RGFormat = 1030;
  105. const RGIntegerFormat = 1031;
  106. const RGBIntegerFormat = 1032;
  107. const RGBAIntegerFormat = 1033;
  108. const RGB_S3TC_DXT1_Format = 33776;
  109. const RGBA_S3TC_DXT1_Format$1 = 33777;
  110. const RGBA_S3TC_DXT3_Format = 33778;
  111. const RGBA_S3TC_DXT5_Format$1 = 33779;
  112. const RGB_PVRTC_4BPPV1_Format = 35840;
  113. const RGB_PVRTC_2BPPV1_Format = 35841;
  114. const RGBA_PVRTC_4BPPV1_Format = 35842;
  115. const RGBA_PVRTC_2BPPV1_Format = 35843;
  116. const RGB_ETC1_Format = 36196;
  117. const RGB_ETC2_Format = 37492;
  118. const RGBA_ETC2_EAC_Format = 37496;
  119. const RGBA_ASTC_4x4_Format = 37808;
  120. const RGBA_ASTC_5x4_Format = 37809;
  121. const RGBA_ASTC_5x5_Format = 37810;
  122. const RGBA_ASTC_6x5_Format = 37811;
  123. const RGBA_ASTC_6x6_Format = 37812;
  124. const RGBA_ASTC_8x5_Format = 37813;
  125. const RGBA_ASTC_8x6_Format = 37814;
  126. const RGBA_ASTC_8x8_Format = 37815;
  127. const RGBA_ASTC_10x5_Format = 37816;
  128. const RGBA_ASTC_10x6_Format = 37817;
  129. const RGBA_ASTC_10x8_Format = 37818;
  130. const RGBA_ASTC_10x10_Format = 37819;
  131. const RGBA_ASTC_12x10_Format = 37820;
  132. const RGBA_ASTC_12x12_Format = 37821;
  133. const RGBA_BPTC_Format = 36492;
  134. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  135. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  136. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  137. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  138. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  139. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  140. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  141. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  142. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  143. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  144. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  145. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  146. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  147. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  148. const LoopOnce = 2200;
  149. const LoopRepeat = 2201;
  150. const LoopPingPong = 2202;
  151. const InterpolateDiscrete = 2300;
  152. const InterpolateLinear = 2301;
  153. const InterpolateSmooth = 2302;
  154. const ZeroCurvatureEnding = 2400;
  155. const ZeroSlopeEnding = 2401;
  156. const WrapAroundEnding = 2402;
  157. const NormalAnimationBlendMode = 2500;
  158. const AdditiveAnimationBlendMode = 2501;
  159. const TrianglesDrawMode = 0;
  160. const TriangleStripDrawMode = 1;
  161. const TriangleFanDrawMode = 2;
  162. const LinearEncoding = 3000;
  163. const sRGBEncoding = 3001;
  164. const GammaEncoding = 3007;
  165. const RGBEEncoding = 3002;
  166. const LogLuvEncoding = 3003;
  167. const RGBM7Encoding = 3004;
  168. const RGBM16Encoding = 3005;
  169. const RGBDEncoding = 3006;
  170. const BasicDepthPacking = 3200;
  171. const RGBADepthPacking = 3201;
  172. const TangentSpaceNormalMap = 0;
  173. const ObjectSpaceNormalMap = 1;
  174. const ZeroStencilOp = 0;
  175. const KeepStencilOp = 7680;
  176. const ReplaceStencilOp = 7681;
  177. const IncrementStencilOp = 7682;
  178. const DecrementStencilOp = 7683;
  179. const IncrementWrapStencilOp = 34055;
  180. const DecrementWrapStencilOp = 34056;
  181. const InvertStencilOp = 5386;
  182. const NeverStencilFunc = 512;
  183. const LessStencilFunc = 513;
  184. const EqualStencilFunc = 514;
  185. const LessEqualStencilFunc = 515;
  186. const GreaterStencilFunc = 516;
  187. const NotEqualStencilFunc = 517;
  188. const GreaterEqualStencilFunc = 518;
  189. const AlwaysStencilFunc = 519;
  190. const StaticDrawUsage = 35044;
  191. const DynamicDrawUsage = 35048;
  192. const StreamDrawUsage = 35040;
  193. const StaticReadUsage = 35045;
  194. const DynamicReadUsage = 35049;
  195. const StreamReadUsage = 35041;
  196. const StaticCopyUsage = 35046;
  197. const DynamicCopyUsage = 35050;
  198. const StreamCopyUsage = 35042;
  199. const GLSL1 = '100';
  200. const GLSL3 = '300 es';
  201. /**
  202. * https://github.com/mrdoob/eventdispatcher.js/
  203. */
  204. function EventDispatcher() {}
  205. Object.assign( EventDispatcher.prototype, {
  206. addEventListener: function ( type, listener ) {
  207. if ( this._listeners === undefined ) this._listeners = {};
  208. const listeners = this._listeners;
  209. if ( listeners[ type ] === undefined ) {
  210. listeners[ type ] = [];
  211. }
  212. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  213. listeners[ type ].push( listener );
  214. }
  215. },
  216. hasEventListener: function ( type, listener ) {
  217. if ( this._listeners === undefined ) return false;
  218. const listeners = this._listeners;
  219. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  220. },
  221. dispatchEvent: function ( event ) {
  222. if ( this._listeners === undefined ) return;
  223. const listeners = this._listeners;
  224. const listenerArray = listeners[ event.type ];
  225. if ( listenerArray !== undefined ) {
  226. event.target = this;
  227. // Make a copy, in case listeners are removed while iterating.
  228. const array = listenerArray.slice( 0 );
  229. for ( let i = 0, l = array.length; i < l; i ++ ) {
  230. array[ i ].call( this, event );
  231. }
  232. }
  233. }
  234. } );
  235. const _lut = [];
  236. for ( let i = 0; i < 256; i ++ ) {
  237. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  238. }
  239. let _seed = 1234567;
  240. const MathUtils = {
  241. DEG2RAD: Math.PI / 180,
  242. RAD2DEG: 180 / Math.PI,
  243. generateUUID: function () {
  244. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  245. const d0 = Math.random() * 0xffffffff | 0;
  246. const d1 = Math.random() * 0xffffffff | 0;
  247. const d2 = Math.random() * 0xffffffff | 0;
  248. const d3 = Math.random() * 0xffffffff | 0;
  249. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  250. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  251. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  252. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  253. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  254. return uuid.toUpperCase();
  255. },
  256. clamp: function ( value, min, max ) {
  257. return Math.max( min, Math.min( max, value ) );
  258. },
  259. // compute euclidian modulo of m % n
  260. // https://en.wikipedia.org/wiki/Modulo_operation
  261. euclideanModulo: function ( n, m ) {
  262. return ( ( n % m ) + m ) % m;
  263. },
  264. // Linear mapping from range <a1, a2> to range <b1, b2>
  265. mapLinear: function ( x, a1, a2, b1, b2 ) {
  266. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  267. },
  268. // https://en.wikipedia.org/wiki/Linear_interpolation
  269. lerp: function ( x, y, t ) {
  270. return ( 1 - t ) * x + t * y;
  271. },
  272. // http://en.wikipedia.org/wiki/Smoothstep
  273. smoothstep: function ( x, min, max ) {
  274. if ( x <= min ) return 0;
  275. if ( x >= max ) return 1;
  276. x = ( x - min ) / ( max - min );
  277. return x * x * ( 3 - 2 * x );
  278. },
  279. smootherstep: function ( x, min, max ) {
  280. if ( x <= min ) return 0;
  281. if ( x >= max ) return 1;
  282. x = ( x - min ) / ( max - min );
  283. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  284. },
  285. // Random integer from <low, high> interval
  286. randInt: function ( low, high ) {
  287. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  288. },
  289. // Random float from <low, high> interval
  290. randFloat: function ( low, high ) {
  291. return low + Math.random() * ( high - low );
  292. },
  293. // Random float from <-range/2, range/2> interval
  294. randFloatSpread: function ( range ) {
  295. return range * ( 0.5 - Math.random() );
  296. },
  297. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  298. seededRandom: function ( s ) {
  299. if ( s !== undefined ) _seed = s % 2147483647;
  300. // Park-Miller algorithm
  301. _seed = _seed * 16807 % 2147483647;
  302. return ( _seed - 1 ) / 2147483646;
  303. },
  304. degToRad: function ( degrees ) {
  305. return degrees * MathUtils.DEG2RAD;
  306. },
  307. radToDeg: function ( radians ) {
  308. return radians * MathUtils.RAD2DEG;
  309. },
  310. isPowerOfTwo: function ( value ) {
  311. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  312. },
  313. ceilPowerOfTwo: function ( value ) {
  314. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  315. },
  316. floorPowerOfTwo: function ( value ) {
  317. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  318. },
  319. setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
  320. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  321. // rotations are applied to the axes in the order specified by 'order'
  322. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  323. // angles are in radians
  324. const cos = Math.cos;
  325. const sin = Math.sin;
  326. const c2 = cos( b / 2 );
  327. const s2 = sin( b / 2 );
  328. const c13 = cos( ( a + c ) / 2 );
  329. const s13 = sin( ( a + c ) / 2 );
  330. const c1_3 = cos( ( a - c ) / 2 );
  331. const s1_3 = sin( ( a - c ) / 2 );
  332. const c3_1 = cos( ( c - a ) / 2 );
  333. const s3_1 = sin( ( c - a ) / 2 );
  334. switch ( order ) {
  335. case 'XYX':
  336. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  337. break;
  338. case 'YZY':
  339. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  340. break;
  341. case 'ZXZ':
  342. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  343. break;
  344. case 'XZX':
  345. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  346. break;
  347. case 'YXY':
  348. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  349. break;
  350. case 'ZYZ':
  351. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  352. break;
  353. default:
  354. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  355. }
  356. }
  357. };
  358. class Vector2 {
  359. constructor( x = 0, y = 0 ) {
  360. Object.defineProperty( this, 'isVector2', { value: true } );
  361. this.x = x;
  362. this.y = y;
  363. }
  364. get width() {
  365. return this.x;
  366. }
  367. set width( value ) {
  368. this.x = value;
  369. }
  370. get height() {
  371. return this.y;
  372. }
  373. set height( value ) {
  374. this.y = value;
  375. }
  376. set( x, y ) {
  377. this.x = x;
  378. this.y = y;
  379. return this;
  380. }
  381. setScalar( scalar ) {
  382. this.x = scalar;
  383. this.y = scalar;
  384. return this;
  385. }
  386. setX( x ) {
  387. this.x = x;
  388. return this;
  389. }
  390. setY( y ) {
  391. this.y = y;
  392. return this;
  393. }
  394. setComponent( index, value ) {
  395. switch ( index ) {
  396. case 0: this.x = value; break;
  397. case 1: this.y = value; break;
  398. default: throw new Error( 'index is out of range: ' + index );
  399. }
  400. return this;
  401. }
  402. getComponent( index ) {
  403. switch ( index ) {
  404. case 0: return this.x;
  405. case 1: return this.y;
  406. default: throw new Error( 'index is out of range: ' + index );
  407. }
  408. }
  409. clone() {
  410. return new this.constructor( this.x, this.y );
  411. }
  412. copy( v ) {
  413. this.x = v.x;
  414. this.y = v.y;
  415. return this;
  416. }
  417. add( v, w ) {
  418. if ( w !== undefined ) {
  419. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  420. return this.addVectors( v, w );
  421. }
  422. this.x += v.x;
  423. this.y += v.y;
  424. return this;
  425. }
  426. addScalar( s ) {
  427. this.x += s;
  428. this.y += s;
  429. return this;
  430. }
  431. addVectors( a, b ) {
  432. this.x = a.x + b.x;
  433. this.y = a.y + b.y;
  434. return this;
  435. }
  436. addScaledVector( v, s ) {
  437. this.x += v.x * s;
  438. this.y += v.y * s;
  439. return this;
  440. }
  441. sub( v, w ) {
  442. if ( w !== undefined ) {
  443. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  444. return this.subVectors( v, w );
  445. }
  446. this.x -= v.x;
  447. this.y -= v.y;
  448. return this;
  449. }
  450. subScalar( s ) {
  451. this.x -= s;
  452. this.y -= s;
  453. return this;
  454. }
  455. subVectors( a, b ) {
  456. this.x = a.x - b.x;
  457. this.y = a.y - b.y;
  458. return this;
  459. }
  460. multiply( v ) {
  461. this.x *= v.x;
  462. this.y *= v.y;
  463. return this;
  464. }
  465. multiplyScalar( scalar ) {
  466. this.x *= scalar;
  467. this.y *= scalar;
  468. return this;
  469. }
  470. divide( v ) {
  471. this.x /= v.x;
  472. this.y /= v.y;
  473. return this;
  474. }
  475. divideScalar( scalar ) {
  476. return this.multiplyScalar( 1 / scalar );
  477. }
  478. applyMatrix3( m ) {
  479. const x = this.x, y = this.y;
  480. const e = m.elements;
  481. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  482. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  483. return this;
  484. }
  485. min( v ) {
  486. this.x = Math.min( this.x, v.x );
  487. this.y = Math.min( this.y, v.y );
  488. return this;
  489. }
  490. max( v ) {
  491. this.x = Math.max( this.x, v.x );
  492. this.y = Math.max( this.y, v.y );
  493. return this;
  494. }
  495. clamp( min, max ) {
  496. // assumes min < max, componentwise
  497. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  498. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  499. return this;
  500. }
  501. clampScalar( minVal, maxVal ) {
  502. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  503. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  504. return this;
  505. }
  506. clampLength( min, max ) {
  507. const length = this.length();
  508. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  509. }
  510. floor() {
  511. this.x = Math.floor( this.x );
  512. this.y = Math.floor( this.y );
  513. return this;
  514. }
  515. ceil() {
  516. this.x = Math.ceil( this.x );
  517. this.y = Math.ceil( this.y );
  518. return this;
  519. }
  520. round() {
  521. this.x = Math.round( this.x );
  522. this.y = Math.round( this.y );
  523. return this;
  524. }
  525. roundToZero() {
  526. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  527. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  528. return this;
  529. }
  530. negate() {
  531. this.x = - this.x;
  532. this.y = - this.y;
  533. return this;
  534. }
  535. dot( v ) {
  536. return this.x * v.x + this.y * v.y;
  537. }
  538. cross( v ) {
  539. return this.x * v.y - this.y * v.x;
  540. }
  541. lengthSq() {
  542. return this.x * this.x + this.y * this.y;
  543. }
  544. length() {
  545. return Math.sqrt( this.x * this.x + this.y * this.y );
  546. }
  547. manhattanLength() {
  548. return Math.abs( this.x ) + Math.abs( this.y );
  549. }
  550. normalize() {
  551. return this.divideScalar( this.length() || 1 );
  552. }
  553. angle() {
  554. // computes the angle in radians with respect to the positive x-axis
  555. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  556. return angle;
  557. }
  558. distanceTo( v ) {
  559. return Math.sqrt( this.distanceToSquared( v ) );
  560. }
  561. distanceToSquared( v ) {
  562. const dx = this.x - v.x, dy = this.y - v.y;
  563. return dx * dx + dy * dy;
  564. }
  565. manhattanDistanceTo( v ) {
  566. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  567. }
  568. setLength( length ) {
  569. return this.normalize().multiplyScalar( length );
  570. }
  571. lerp( v, alpha ) {
  572. this.x += ( v.x - this.x ) * alpha;
  573. this.y += ( v.y - this.y ) * alpha;
  574. return this;
  575. }
  576. lerpVectors( v1, v2, alpha ) {
  577. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  578. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  579. return this;
  580. }
  581. equals( v ) {
  582. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  583. }
  584. fromArray( array, offset = 0 ) {
  585. this.x = array[ offset ];
  586. this.y = array[ offset + 1 ];
  587. return this;
  588. }
  589. toArray( array = [], offset = 0 ) {
  590. array[ offset ] = this.x;
  591. array[ offset + 1 ] = this.y;
  592. return array;
  593. }
  594. fromBufferAttribute( attribute, index, offset ) {
  595. if ( offset !== undefined ) {
  596. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  597. }
  598. this.x = attribute.getX( index );
  599. this.y = attribute.getY( index );
  600. return this;
  601. }
  602. rotateAround( center, angle ) {
  603. const c = Math.cos( angle ), s = Math.sin( angle );
  604. const x = this.x - center.x;
  605. const y = this.y - center.y;
  606. this.x = x * c - y * s + center.x;
  607. this.y = x * s + y * c + center.y;
  608. return this;
  609. }
  610. random() {
  611. this.x = Math.random();
  612. this.y = Math.random();
  613. return this;
  614. }
  615. }
  616. class Matrix3 {
  617. constructor() {
  618. Object.defineProperty( this, 'isMatrix3', { value: true } );
  619. this.elements = [
  620. 1, 0, 0,
  621. 0, 1, 0,
  622. 0, 0, 1
  623. ];
  624. if ( arguments.length > 0 ) {
  625. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  626. }
  627. }
  628. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  629. const te = this.elements;
  630. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  631. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  632. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  633. return this;
  634. }
  635. identity() {
  636. this.set(
  637. 1, 0, 0,
  638. 0, 1, 0,
  639. 0, 0, 1
  640. );
  641. return this;
  642. }
  643. clone() {
  644. return new this.constructor().fromArray( this.elements );
  645. }
  646. copy( m ) {
  647. const te = this.elements;
  648. const me = m.elements;
  649. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  650. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  651. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  652. return this;
  653. }
  654. extractBasis( xAxis, yAxis, zAxis ) {
  655. xAxis.setFromMatrix3Column( this, 0 );
  656. yAxis.setFromMatrix3Column( this, 1 );
  657. zAxis.setFromMatrix3Column( this, 2 );
  658. return this;
  659. }
  660. setFromMatrix4( m ) {
  661. const me = m.elements;
  662. this.set(
  663. me[ 0 ], me[ 4 ], me[ 8 ],
  664. me[ 1 ], me[ 5 ], me[ 9 ],
  665. me[ 2 ], me[ 6 ], me[ 10 ]
  666. );
  667. return this;
  668. }
  669. multiply( m ) {
  670. return this.multiplyMatrices( this, m );
  671. }
  672. premultiply( m ) {
  673. return this.multiplyMatrices( m, this );
  674. }
  675. multiplyMatrices( a, b ) {
  676. const ae = a.elements;
  677. const be = b.elements;
  678. const te = this.elements;
  679. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  680. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  681. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  682. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  683. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  684. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  685. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  686. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  687. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  688. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  689. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  690. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  691. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  692. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  693. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  694. return this;
  695. }
  696. multiplyScalar( s ) {
  697. const te = this.elements;
  698. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  699. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  700. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  701. return this;
  702. }
  703. determinant() {
  704. const te = this.elements;
  705. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  706. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  707. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  708. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  709. }
  710. invert() {
  711. const te = this.elements,
  712. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  713. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  714. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  715. t11 = n33 * n22 - n32 * n23,
  716. t12 = n32 * n13 - n33 * n12,
  717. t13 = n23 * n12 - n22 * n13,
  718. det = n11 * t11 + n21 * t12 + n31 * t13;
  719. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  720. const detInv = 1 / det;
  721. te[ 0 ] = t11 * detInv;
  722. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  723. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  724. te[ 3 ] = t12 * detInv;
  725. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  726. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  727. te[ 6 ] = t13 * detInv;
  728. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  729. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  730. return this;
  731. }
  732. transpose() {
  733. let tmp;
  734. const m = this.elements;
  735. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  736. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  737. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  738. return this;
  739. }
  740. getNormalMatrix( matrix4 ) {
  741. return this.setFromMatrix4( matrix4 ).copy( this ).invert().transpose();
  742. }
  743. transposeIntoArray( r ) {
  744. const m = this.elements;
  745. r[ 0 ] = m[ 0 ];
  746. r[ 1 ] = m[ 3 ];
  747. r[ 2 ] = m[ 6 ];
  748. r[ 3 ] = m[ 1 ];
  749. r[ 4 ] = m[ 4 ];
  750. r[ 5 ] = m[ 7 ];
  751. r[ 6 ] = m[ 2 ];
  752. r[ 7 ] = m[ 5 ];
  753. r[ 8 ] = m[ 8 ];
  754. return this;
  755. }
  756. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  757. const c = Math.cos( rotation );
  758. const s = Math.sin( rotation );
  759. this.set(
  760. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  761. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  762. 0, 0, 1
  763. );
  764. return this;
  765. }
  766. scale( sx, sy ) {
  767. const te = this.elements;
  768. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  769. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  770. return this;
  771. }
  772. rotate( theta ) {
  773. const c = Math.cos( theta );
  774. const s = Math.sin( theta );
  775. const te = this.elements;
  776. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  777. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  778. te[ 0 ] = c * a11 + s * a21;
  779. te[ 3 ] = c * a12 + s * a22;
  780. te[ 6 ] = c * a13 + s * a23;
  781. te[ 1 ] = - s * a11 + c * a21;
  782. te[ 4 ] = - s * a12 + c * a22;
  783. te[ 7 ] = - s * a13 + c * a23;
  784. return this;
  785. }
  786. translate( tx, ty ) {
  787. const te = this.elements;
  788. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  789. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  790. return this;
  791. }
  792. equals( matrix ) {
  793. const te = this.elements;
  794. const me = matrix.elements;
  795. for ( let i = 0; i < 9; i ++ ) {
  796. if ( te[ i ] !== me[ i ] ) return false;
  797. }
  798. return true;
  799. }
  800. fromArray( array, offset = 0 ) {
  801. for ( let i = 0; i < 9; i ++ ) {
  802. this.elements[ i ] = array[ i + offset ];
  803. }
  804. return this;
  805. }
  806. toArray( array = [], offset = 0 ) {
  807. const te = this.elements;
  808. array[ offset ] = te[ 0 ];
  809. array[ offset + 1 ] = te[ 1 ];
  810. array[ offset + 2 ] = te[ 2 ];
  811. array[ offset + 3 ] = te[ 3 ];
  812. array[ offset + 4 ] = te[ 4 ];
  813. array[ offset + 5 ] = te[ 5 ];
  814. array[ offset + 6 ] = te[ 6 ];
  815. array[ offset + 7 ] = te[ 7 ];
  816. array[ offset + 8 ] = te[ 8 ];
  817. return array;
  818. }
  819. }
  820. let _canvas;
  821. const ImageUtils = {
  822. getDataURL: function ( image ) {
  823. if ( /^data:/i.test( image.src ) ) {
  824. return image.src;
  825. }
  826. if ( typeof HTMLCanvasElement == 'undefined' ) {
  827. return image.src;
  828. }
  829. let canvas;
  830. if ( image instanceof HTMLCanvasElement ) {
  831. canvas = image;
  832. } else {
  833. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  834. _canvas.width = image.width;
  835. _canvas.height = image.height;
  836. const context = _canvas.getContext( '2d' );
  837. if ( image instanceof ImageData ) {
  838. context.putImageData( image, 0, 0 );
  839. } else {
  840. context.drawImage( image, 0, 0, image.width, image.height );
  841. }
  842. canvas = _canvas;
  843. }
  844. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  845. return canvas.toDataURL( 'image/jpeg', 0.6 );
  846. } else {
  847. return canvas.toDataURL( 'image/png' );
  848. }
  849. }
  850. };
  851. let textureId = 0;
  852. function Texture( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) {
  853. Object.defineProperty( this, 'id', { value: textureId ++ } );
  854. this.uuid = MathUtils.generateUUID();
  855. this.name = '';
  856. this.image = image;
  857. this.mipmaps = [];
  858. this.mapping = mapping;
  859. this.wrapS = wrapS;
  860. this.wrapT = wrapT;
  861. this.magFilter = magFilter;
  862. this.minFilter = minFilter;
  863. this.anisotropy = anisotropy;
  864. this.format = format;
  865. this.internalFormat = null;
  866. this.type = type;
  867. this.offset = new Vector2( 0, 0 );
  868. this.repeat = new Vector2( 1, 1 );
  869. this.center = new Vector2( 0, 0 );
  870. this.rotation = 0;
  871. this.matrixAutoUpdate = true;
  872. this.matrix = new Matrix3();
  873. this.generateMipmaps = true;
  874. this.premultiplyAlpha = false;
  875. this.flipY = true;
  876. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  877. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  878. //
  879. // Also changing the encoding after already used by a Material will not automatically make the Material
  880. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  881. this.encoding = encoding;
  882. this.version = 0;
  883. this.onUpdate = null;
  884. }
  885. Texture.DEFAULT_IMAGE = undefined;
  886. Texture.DEFAULT_MAPPING = UVMapping;
  887. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  888. constructor: Texture,
  889. isTexture: true,
  890. updateMatrix: function () {
  891. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  892. },
  893. clone: function () {
  894. return new this.constructor().copy( this );
  895. },
  896. copy: function ( source ) {
  897. this.name = source.name;
  898. this.image = source.image;
  899. this.mipmaps = source.mipmaps.slice( 0 );
  900. this.mapping = source.mapping;
  901. this.wrapS = source.wrapS;
  902. this.wrapT = source.wrapT;
  903. this.magFilter = source.magFilter;
  904. this.minFilter = source.minFilter;
  905. this.anisotropy = source.anisotropy;
  906. this.format = source.format;
  907. this.internalFormat = source.internalFormat;
  908. this.type = source.type;
  909. this.offset.copy( source.offset );
  910. this.repeat.copy( source.repeat );
  911. this.center.copy( source.center );
  912. this.rotation = source.rotation;
  913. this.matrixAutoUpdate = source.matrixAutoUpdate;
  914. this.matrix.copy( source.matrix );
  915. this.generateMipmaps = source.generateMipmaps;
  916. this.premultiplyAlpha = source.premultiplyAlpha;
  917. this.flipY = source.flipY;
  918. this.unpackAlignment = source.unpackAlignment;
  919. this.encoding = source.encoding;
  920. return this;
  921. },
  922. toJSON: function ( meta ) {
  923. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  924. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  925. return meta.textures[ this.uuid ];
  926. }
  927. const output = {
  928. metadata: {
  929. version: 4.5,
  930. type: 'Texture',
  931. generator: 'Texture.toJSON'
  932. },
  933. uuid: this.uuid,
  934. name: this.name,
  935. mapping: this.mapping,
  936. repeat: [ this.repeat.x, this.repeat.y ],
  937. offset: [ this.offset.x, this.offset.y ],
  938. center: [ this.center.x, this.center.y ],
  939. rotation: this.rotation,
  940. wrap: [ this.wrapS, this.wrapT ],
  941. format: this.format,
  942. type: this.type,
  943. encoding: this.encoding,
  944. minFilter: this.minFilter,
  945. magFilter: this.magFilter,
  946. anisotropy: this.anisotropy,
  947. flipY: this.flipY,
  948. premultiplyAlpha: this.premultiplyAlpha,
  949. unpackAlignment: this.unpackAlignment
  950. };
  951. if ( this.image !== undefined ) {
  952. // TODO: Move to THREE.Image
  953. const image = this.image;
  954. if ( image.uuid === undefined ) {
  955. image.uuid = MathUtils.generateUUID(); // UGH
  956. }
  957. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  958. let url;
  959. if ( Array.isArray( image ) ) {
  960. // process array of images e.g. CubeTexture
  961. url = [];
  962. for ( let i = 0, l = image.length; i < l; i ++ ) {
  963. // check cube texture with data textures
  964. if ( image[ i ].isDataTexture ) {
  965. url.push( serializeImage( image[ i ].image ) );
  966. } else {
  967. url.push( serializeImage( image[ i ] ) );
  968. }
  969. }
  970. } else {
  971. // process single image
  972. url = serializeImage( image );
  973. }
  974. meta.images[ image.uuid ] = {
  975. uuid: image.uuid,
  976. url: url
  977. };
  978. }
  979. output.image = image.uuid;
  980. }
  981. if ( ! isRootObject ) {
  982. meta.textures[ this.uuid ] = output;
  983. }
  984. return output;
  985. },
  986. dispose: function () {
  987. this.dispatchEvent( { type: 'dispose' } );
  988. },
  989. transformUv: function ( uv ) {
  990. if ( this.mapping !== UVMapping ) return uv;
  991. uv.applyMatrix3( this.matrix );
  992. if ( uv.x < 0 || uv.x > 1 ) {
  993. switch ( this.wrapS ) {
  994. case RepeatWrapping:
  995. uv.x = uv.x - Math.floor( uv.x );
  996. break;
  997. case ClampToEdgeWrapping:
  998. uv.x = uv.x < 0 ? 0 : 1;
  999. break;
  1000. case MirroredRepeatWrapping:
  1001. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1002. uv.x = Math.ceil( uv.x ) - uv.x;
  1003. } else {
  1004. uv.x = uv.x - Math.floor( uv.x );
  1005. }
  1006. break;
  1007. }
  1008. }
  1009. if ( uv.y < 0 || uv.y > 1 ) {
  1010. switch ( this.wrapT ) {
  1011. case RepeatWrapping:
  1012. uv.y = uv.y - Math.floor( uv.y );
  1013. break;
  1014. case ClampToEdgeWrapping:
  1015. uv.y = uv.y < 0 ? 0 : 1;
  1016. break;
  1017. case MirroredRepeatWrapping:
  1018. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1019. uv.y = Math.ceil( uv.y ) - uv.y;
  1020. } else {
  1021. uv.y = uv.y - Math.floor( uv.y );
  1022. }
  1023. break;
  1024. }
  1025. }
  1026. if ( this.flipY ) {
  1027. uv.y = 1 - uv.y;
  1028. }
  1029. return uv;
  1030. }
  1031. } );
  1032. Object.defineProperty( Texture.prototype, 'needsUpdate', {
  1033. set: function ( value ) {
  1034. if ( value === true ) this.version ++;
  1035. }
  1036. } );
  1037. function serializeImage( image ) {
  1038. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1039. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1040. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1041. // default images
  1042. return ImageUtils.getDataURL( image );
  1043. } else {
  1044. if ( image.data ) {
  1045. // images of DataTexture
  1046. return {
  1047. data: Array.prototype.slice.call( image.data ),
  1048. width: image.width,
  1049. height: image.height,
  1050. type: image.data.constructor.name
  1051. };
  1052. } else {
  1053. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1054. return {};
  1055. }
  1056. }
  1057. }
  1058. class Vector4 {
  1059. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1060. Object.defineProperty( this, 'isVector4', { value: true } );
  1061. this.x = x;
  1062. this.y = y;
  1063. this.z = z;
  1064. this.w = w;
  1065. }
  1066. get width() {
  1067. return this.z;
  1068. }
  1069. set width( value ) {
  1070. this.z = value;
  1071. }
  1072. get height() {
  1073. return this.w;
  1074. }
  1075. set height( value ) {
  1076. this.w = value;
  1077. }
  1078. set( x, y, z, w ) {
  1079. this.x = x;
  1080. this.y = y;
  1081. this.z = z;
  1082. this.w = w;
  1083. return this;
  1084. }
  1085. setScalar( scalar ) {
  1086. this.x = scalar;
  1087. this.y = scalar;
  1088. this.z = scalar;
  1089. this.w = scalar;
  1090. return this;
  1091. }
  1092. setX( x ) {
  1093. this.x = x;
  1094. return this;
  1095. }
  1096. setY( y ) {
  1097. this.y = y;
  1098. return this;
  1099. }
  1100. setZ( z ) {
  1101. this.z = z;
  1102. return this;
  1103. }
  1104. setW( w ) {
  1105. this.w = w;
  1106. return this;
  1107. }
  1108. setComponent( index, value ) {
  1109. switch ( index ) {
  1110. case 0: this.x = value; break;
  1111. case 1: this.y = value; break;
  1112. case 2: this.z = value; break;
  1113. case 3: this.w = value; break;
  1114. default: throw new Error( 'index is out of range: ' + index );
  1115. }
  1116. return this;
  1117. }
  1118. getComponent( index ) {
  1119. switch ( index ) {
  1120. case 0: return this.x;
  1121. case 1: return this.y;
  1122. case 2: return this.z;
  1123. case 3: return this.w;
  1124. default: throw new Error( 'index is out of range: ' + index );
  1125. }
  1126. }
  1127. clone() {
  1128. return new this.constructor( this.x, this.y, this.z, this.w );
  1129. }
  1130. copy( v ) {
  1131. this.x = v.x;
  1132. this.y = v.y;
  1133. this.z = v.z;
  1134. this.w = ( v.w !== undefined ) ? v.w : 1;
  1135. return this;
  1136. }
  1137. add( v, w ) {
  1138. if ( w !== undefined ) {
  1139. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1140. return this.addVectors( v, w );
  1141. }
  1142. this.x += v.x;
  1143. this.y += v.y;
  1144. this.z += v.z;
  1145. this.w += v.w;
  1146. return this;
  1147. }
  1148. addScalar( s ) {
  1149. this.x += s;
  1150. this.y += s;
  1151. this.z += s;
  1152. this.w += s;
  1153. return this;
  1154. }
  1155. addVectors( a, b ) {
  1156. this.x = a.x + b.x;
  1157. this.y = a.y + b.y;
  1158. this.z = a.z + b.z;
  1159. this.w = a.w + b.w;
  1160. return this;
  1161. }
  1162. addScaledVector( v, s ) {
  1163. this.x += v.x * s;
  1164. this.y += v.y * s;
  1165. this.z += v.z * s;
  1166. this.w += v.w * s;
  1167. return this;
  1168. }
  1169. sub( v, w ) {
  1170. if ( w !== undefined ) {
  1171. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1172. return this.subVectors( v, w );
  1173. }
  1174. this.x -= v.x;
  1175. this.y -= v.y;
  1176. this.z -= v.z;
  1177. this.w -= v.w;
  1178. return this;
  1179. }
  1180. subScalar( s ) {
  1181. this.x -= s;
  1182. this.y -= s;
  1183. this.z -= s;
  1184. this.w -= s;
  1185. return this;
  1186. }
  1187. subVectors( a, b ) {
  1188. this.x = a.x - b.x;
  1189. this.y = a.y - b.y;
  1190. this.z = a.z - b.z;
  1191. this.w = a.w - b.w;
  1192. return this;
  1193. }
  1194. multiplyScalar( scalar ) {
  1195. this.x *= scalar;
  1196. this.y *= scalar;
  1197. this.z *= scalar;
  1198. this.w *= scalar;
  1199. return this;
  1200. }
  1201. applyMatrix4( m ) {
  1202. const x = this.x, y = this.y, z = this.z, w = this.w;
  1203. const e = m.elements;
  1204. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1205. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1206. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1207. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1208. return this;
  1209. }
  1210. divideScalar( scalar ) {
  1211. return this.multiplyScalar( 1 / scalar );
  1212. }
  1213. setAxisAngleFromQuaternion( q ) {
  1214. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1215. // q is assumed to be normalized
  1216. this.w = 2 * Math.acos( q.w );
  1217. const s = Math.sqrt( 1 - q.w * q.w );
  1218. if ( s < 0.0001 ) {
  1219. this.x = 1;
  1220. this.y = 0;
  1221. this.z = 0;
  1222. } else {
  1223. this.x = q.x / s;
  1224. this.y = q.y / s;
  1225. this.z = q.z / s;
  1226. }
  1227. return this;
  1228. }
  1229. setAxisAngleFromRotationMatrix( m ) {
  1230. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1231. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1232. let angle, x, y, z; // variables for result
  1233. const epsilon = 0.01, // margin to allow for rounding errors
  1234. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1235. te = m.elements,
  1236. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1237. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1238. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1239. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1240. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1241. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1242. // singularity found
  1243. // first check for identity matrix which must have +1 for all terms
  1244. // in leading diagonal and zero in other terms
  1245. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1246. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1247. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1248. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1249. // this singularity is identity matrix so angle = 0
  1250. this.set( 1, 0, 0, 0 );
  1251. return this; // zero angle, arbitrary axis
  1252. }
  1253. // otherwise this singularity is angle = 180
  1254. angle = Math.PI;
  1255. const xx = ( m11 + 1 ) / 2;
  1256. const yy = ( m22 + 1 ) / 2;
  1257. const zz = ( m33 + 1 ) / 2;
  1258. const xy = ( m12 + m21 ) / 4;
  1259. const xz = ( m13 + m31 ) / 4;
  1260. const yz = ( m23 + m32 ) / 4;
  1261. if ( ( xx > yy ) && ( xx > zz ) ) {
  1262. // m11 is the largest diagonal term
  1263. if ( xx < epsilon ) {
  1264. x = 0;
  1265. y = 0.707106781;
  1266. z = 0.707106781;
  1267. } else {
  1268. x = Math.sqrt( xx );
  1269. y = xy / x;
  1270. z = xz / x;
  1271. }
  1272. } else if ( yy > zz ) {
  1273. // m22 is the largest diagonal term
  1274. if ( yy < epsilon ) {
  1275. x = 0.707106781;
  1276. y = 0;
  1277. z = 0.707106781;
  1278. } else {
  1279. y = Math.sqrt( yy );
  1280. x = xy / y;
  1281. z = yz / y;
  1282. }
  1283. } else {
  1284. // m33 is the largest diagonal term so base result on this
  1285. if ( zz < epsilon ) {
  1286. x = 0.707106781;
  1287. y = 0.707106781;
  1288. z = 0;
  1289. } else {
  1290. z = Math.sqrt( zz );
  1291. x = xz / z;
  1292. y = yz / z;
  1293. }
  1294. }
  1295. this.set( x, y, z, angle );
  1296. return this; // return 180 deg rotation
  1297. }
  1298. // as we have reached here there are no singularities so we can handle normally
  1299. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1300. ( m13 - m31 ) * ( m13 - m31 ) +
  1301. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1302. if ( Math.abs( s ) < 0.001 ) s = 1;
  1303. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1304. // caught by singularity test above, but I've left it in just in case
  1305. this.x = ( m32 - m23 ) / s;
  1306. this.y = ( m13 - m31 ) / s;
  1307. this.z = ( m21 - m12 ) / s;
  1308. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1309. return this;
  1310. }
  1311. min( v ) {
  1312. this.x = Math.min( this.x, v.x );
  1313. this.y = Math.min( this.y, v.y );
  1314. this.z = Math.min( this.z, v.z );
  1315. this.w = Math.min( this.w, v.w );
  1316. return this;
  1317. }
  1318. max( v ) {
  1319. this.x = Math.max( this.x, v.x );
  1320. this.y = Math.max( this.y, v.y );
  1321. this.z = Math.max( this.z, v.z );
  1322. this.w = Math.max( this.w, v.w );
  1323. return this;
  1324. }
  1325. clamp( min, max ) {
  1326. // assumes min < max, componentwise
  1327. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1328. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1329. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1330. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1331. return this;
  1332. }
  1333. clampScalar( minVal, maxVal ) {
  1334. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1335. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1336. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1337. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1338. return this;
  1339. }
  1340. clampLength( min, max ) {
  1341. const length = this.length();
  1342. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1343. }
  1344. floor() {
  1345. this.x = Math.floor( this.x );
  1346. this.y = Math.floor( this.y );
  1347. this.z = Math.floor( this.z );
  1348. this.w = Math.floor( this.w );
  1349. return this;
  1350. }
  1351. ceil() {
  1352. this.x = Math.ceil( this.x );
  1353. this.y = Math.ceil( this.y );
  1354. this.z = Math.ceil( this.z );
  1355. this.w = Math.ceil( this.w );
  1356. return this;
  1357. }
  1358. round() {
  1359. this.x = Math.round( this.x );
  1360. this.y = Math.round( this.y );
  1361. this.z = Math.round( this.z );
  1362. this.w = Math.round( this.w );
  1363. return this;
  1364. }
  1365. roundToZero() {
  1366. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1367. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1368. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1369. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1370. return this;
  1371. }
  1372. negate() {
  1373. this.x = - this.x;
  1374. this.y = - this.y;
  1375. this.z = - this.z;
  1376. this.w = - this.w;
  1377. return this;
  1378. }
  1379. dot( v ) {
  1380. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1381. }
  1382. lengthSq() {
  1383. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1384. }
  1385. length() {
  1386. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1387. }
  1388. manhattanLength() {
  1389. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1390. }
  1391. normalize() {
  1392. return this.divideScalar( this.length() || 1 );
  1393. }
  1394. setLength( length ) {
  1395. return this.normalize().multiplyScalar( length );
  1396. }
  1397. lerp( v, alpha ) {
  1398. this.x += ( v.x - this.x ) * alpha;
  1399. this.y += ( v.y - this.y ) * alpha;
  1400. this.z += ( v.z - this.z ) * alpha;
  1401. this.w += ( v.w - this.w ) * alpha;
  1402. return this;
  1403. }
  1404. lerpVectors( v1, v2, alpha ) {
  1405. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1406. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1407. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1408. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1409. return this;
  1410. }
  1411. equals( v ) {
  1412. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1413. }
  1414. fromArray( array, offset = 0 ) {
  1415. this.x = array[ offset ];
  1416. this.y = array[ offset + 1 ];
  1417. this.z = array[ offset + 2 ];
  1418. this.w = array[ offset + 3 ];
  1419. return this;
  1420. }
  1421. toArray( array = [], offset = 0 ) {
  1422. array[ offset ] = this.x;
  1423. array[ offset + 1 ] = this.y;
  1424. array[ offset + 2 ] = this.z;
  1425. array[ offset + 3 ] = this.w;
  1426. return array;
  1427. }
  1428. fromBufferAttribute( attribute, index, offset ) {
  1429. if ( offset !== undefined ) {
  1430. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  1431. }
  1432. this.x = attribute.getX( index );
  1433. this.y = attribute.getY( index );
  1434. this.z = attribute.getZ( index );
  1435. this.w = attribute.getW( index );
  1436. return this;
  1437. }
  1438. random() {
  1439. this.x = Math.random();
  1440. this.y = Math.random();
  1441. this.z = Math.random();
  1442. this.w = Math.random();
  1443. return this;
  1444. }
  1445. }
  1446. /*
  1447. In options, we can specify:
  1448. * Texture parameters for an auto-generated target texture
  1449. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1450. */
  1451. function WebGLRenderTarget( width, height, options ) {
  1452. this.width = width;
  1453. this.height = height;
  1454. this.scissor = new Vector4( 0, 0, width, height );
  1455. this.scissorTest = false;
  1456. this.viewport = new Vector4( 0, 0, width, height );
  1457. options = options || {};
  1458. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  1459. this.texture.image = {};
  1460. this.texture.image.width = width;
  1461. this.texture.image.height = height;
  1462. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1463. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1464. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1465. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1466. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1467. }
  1468. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  1469. constructor: WebGLRenderTarget,
  1470. isWebGLRenderTarget: true,
  1471. setSize: function ( width, height ) {
  1472. if ( this.width !== width || this.height !== height ) {
  1473. this.width = width;
  1474. this.height = height;
  1475. this.texture.image.width = width;
  1476. this.texture.image.height = height;
  1477. this.dispose();
  1478. }
  1479. this.viewport.set( 0, 0, width, height );
  1480. this.scissor.set( 0, 0, width, height );
  1481. },
  1482. clone: function () {
  1483. return new this.constructor().copy( this );
  1484. },
  1485. copy: function ( source ) {
  1486. this.width = source.width;
  1487. this.height = source.height;
  1488. this.viewport.copy( source.viewport );
  1489. this.texture = source.texture.clone();
  1490. this.depthBuffer = source.depthBuffer;
  1491. this.stencilBuffer = source.stencilBuffer;
  1492. this.depthTexture = source.depthTexture;
  1493. return this;
  1494. },
  1495. dispose: function () {
  1496. this.dispatchEvent( { type: 'dispose' } );
  1497. }
  1498. } );
  1499. function WebGLMultisampleRenderTarget( width, height, options ) {
  1500. WebGLRenderTarget.call( this, width, height, options );
  1501. this.samples = 4;
  1502. }
  1503. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  1504. constructor: WebGLMultisampleRenderTarget,
  1505. isWebGLMultisampleRenderTarget: true,
  1506. copy: function ( source ) {
  1507. WebGLRenderTarget.prototype.copy.call( this, source );
  1508. this.samples = source.samples;
  1509. return this;
  1510. }
  1511. } );
  1512. class Quaternion {
  1513. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1514. Object.defineProperty( this, 'isQuaternion', { value: true } );
  1515. this._x = x;
  1516. this._y = y;
  1517. this._z = z;
  1518. this._w = w;
  1519. }
  1520. static slerp( qa, qb, qm, t ) {
  1521. return qm.copy( qa ).slerp( qb, t );
  1522. }
  1523. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1524. // fuzz-free, array-based Quaternion SLERP operation
  1525. let x0 = src0[ srcOffset0 + 0 ],
  1526. y0 = src0[ srcOffset0 + 1 ],
  1527. z0 = src0[ srcOffset0 + 2 ],
  1528. w0 = src0[ srcOffset0 + 3 ];
  1529. const x1 = src1[ srcOffset1 + 0 ],
  1530. y1 = src1[ srcOffset1 + 1 ],
  1531. z1 = src1[ srcOffset1 + 2 ],
  1532. w1 = src1[ srcOffset1 + 3 ];
  1533. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1534. let s = 1 - t;
  1535. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1536. dir = ( cos >= 0 ? 1 : - 1 ),
  1537. sqrSin = 1 - cos * cos;
  1538. // Skip the Slerp for tiny steps to avoid numeric problems:
  1539. if ( sqrSin > Number.EPSILON ) {
  1540. const sin = Math.sqrt( sqrSin ),
  1541. len = Math.atan2( sin, cos * dir );
  1542. s = Math.sin( s * len ) / sin;
  1543. t = Math.sin( t * len ) / sin;
  1544. }
  1545. const tDir = t * dir;
  1546. x0 = x0 * s + x1 * tDir;
  1547. y0 = y0 * s + y1 * tDir;
  1548. z0 = z0 * s + z1 * tDir;
  1549. w0 = w0 * s + w1 * tDir;
  1550. // Normalize in case we just did a lerp:
  1551. if ( s === 1 - t ) {
  1552. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1553. x0 *= f;
  1554. y0 *= f;
  1555. z0 *= f;
  1556. w0 *= f;
  1557. }
  1558. }
  1559. dst[ dstOffset ] = x0;
  1560. dst[ dstOffset + 1 ] = y0;
  1561. dst[ dstOffset + 2 ] = z0;
  1562. dst[ dstOffset + 3 ] = w0;
  1563. }
  1564. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1565. const x0 = src0[ srcOffset0 ];
  1566. const y0 = src0[ srcOffset0 + 1 ];
  1567. const z0 = src0[ srcOffset0 + 2 ];
  1568. const w0 = src0[ srcOffset0 + 3 ];
  1569. const x1 = src1[ srcOffset1 ];
  1570. const y1 = src1[ srcOffset1 + 1 ];
  1571. const z1 = src1[ srcOffset1 + 2 ];
  1572. const w1 = src1[ srcOffset1 + 3 ];
  1573. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1574. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1575. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1576. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1577. return dst;
  1578. }
  1579. get x() {
  1580. return this._x;
  1581. }
  1582. set x( value ) {
  1583. this._x = value;
  1584. this._onChangeCallback();
  1585. }
  1586. get y() {
  1587. return this._y;
  1588. }
  1589. set y( value ) {
  1590. this._y = value;
  1591. this._onChangeCallback();
  1592. }
  1593. get z() {
  1594. return this._z;
  1595. }
  1596. set z( value ) {
  1597. this._z = value;
  1598. this._onChangeCallback();
  1599. }
  1600. get w() {
  1601. return this._w;
  1602. }
  1603. set w( value ) {
  1604. this._w = value;
  1605. this._onChangeCallback();
  1606. }
  1607. set( x, y, z, w ) {
  1608. this._x = x;
  1609. this._y = y;
  1610. this._z = z;
  1611. this._w = w;
  1612. this._onChangeCallback();
  1613. return this;
  1614. }
  1615. clone() {
  1616. return new this.constructor( this._x, this._y, this._z, this._w );
  1617. }
  1618. copy( quaternion ) {
  1619. this._x = quaternion.x;
  1620. this._y = quaternion.y;
  1621. this._z = quaternion.z;
  1622. this._w = quaternion.w;
  1623. this._onChangeCallback();
  1624. return this;
  1625. }
  1626. setFromEuler( euler, update ) {
  1627. if ( ! ( euler && euler.isEuler ) ) {
  1628. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1629. }
  1630. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1631. // http://www.mathworks.com/matlabcentral/fileexchange/
  1632. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1633. // content/SpinCalc.m
  1634. const cos = Math.cos;
  1635. const sin = Math.sin;
  1636. const c1 = cos( x / 2 );
  1637. const c2 = cos( y / 2 );
  1638. const c3 = cos( z / 2 );
  1639. const s1 = sin( x / 2 );
  1640. const s2 = sin( y / 2 );
  1641. const s3 = sin( z / 2 );
  1642. switch ( order ) {
  1643. case 'XYZ':
  1644. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1645. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1646. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1647. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1648. break;
  1649. case 'YXZ':
  1650. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1651. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1652. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1653. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1654. break;
  1655. case 'ZXY':
  1656. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1657. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1658. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1659. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1660. break;
  1661. case 'ZYX':
  1662. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1663. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1664. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1665. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1666. break;
  1667. case 'YZX':
  1668. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1669. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1670. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1671. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1672. break;
  1673. case 'XZY':
  1674. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1675. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1676. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1677. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1678. break;
  1679. default:
  1680. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1681. }
  1682. if ( update !== false ) this._onChangeCallback();
  1683. return this;
  1684. }
  1685. setFromAxisAngle( axis, angle ) {
  1686. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1687. // assumes axis is normalized
  1688. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1689. this._x = axis.x * s;
  1690. this._y = axis.y * s;
  1691. this._z = axis.z * s;
  1692. this._w = Math.cos( halfAngle );
  1693. this._onChangeCallback();
  1694. return this;
  1695. }
  1696. setFromRotationMatrix( m ) {
  1697. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1698. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1699. const te = m.elements,
  1700. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1701. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1702. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1703. trace = m11 + m22 + m33;
  1704. if ( trace > 0 ) {
  1705. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1706. this._w = 0.25 / s;
  1707. this._x = ( m32 - m23 ) * s;
  1708. this._y = ( m13 - m31 ) * s;
  1709. this._z = ( m21 - m12 ) * s;
  1710. } else if ( m11 > m22 && m11 > m33 ) {
  1711. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1712. this._w = ( m32 - m23 ) / s;
  1713. this._x = 0.25 * s;
  1714. this._y = ( m12 + m21 ) / s;
  1715. this._z = ( m13 + m31 ) / s;
  1716. } else if ( m22 > m33 ) {
  1717. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1718. this._w = ( m13 - m31 ) / s;
  1719. this._x = ( m12 + m21 ) / s;
  1720. this._y = 0.25 * s;
  1721. this._z = ( m23 + m32 ) / s;
  1722. } else {
  1723. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1724. this._w = ( m21 - m12 ) / s;
  1725. this._x = ( m13 + m31 ) / s;
  1726. this._y = ( m23 + m32 ) / s;
  1727. this._z = 0.25 * s;
  1728. }
  1729. this._onChangeCallback();
  1730. return this;
  1731. }
  1732. setFromUnitVectors( vFrom, vTo ) {
  1733. // assumes direction vectors vFrom and vTo are normalized
  1734. const EPS = 0.000001;
  1735. let r = vFrom.dot( vTo ) + 1;
  1736. if ( r < EPS ) {
  1737. r = 0;
  1738. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1739. this._x = - vFrom.y;
  1740. this._y = vFrom.x;
  1741. this._z = 0;
  1742. this._w = r;
  1743. } else {
  1744. this._x = 0;
  1745. this._y = - vFrom.z;
  1746. this._z = vFrom.y;
  1747. this._w = r;
  1748. }
  1749. } else {
  1750. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1751. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1752. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1753. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1754. this._w = r;
  1755. }
  1756. return this.normalize();
  1757. }
  1758. angleTo( q ) {
  1759. return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
  1760. }
  1761. rotateTowards( q, step ) {
  1762. const angle = this.angleTo( q );
  1763. if ( angle === 0 ) return this;
  1764. const t = Math.min( 1, step / angle );
  1765. this.slerp( q, t );
  1766. return this;
  1767. }
  1768. identity() {
  1769. return this.set( 0, 0, 0, 1 );
  1770. }
  1771. invert() {
  1772. // quaternion is assumed to have unit length
  1773. return this.conjugate();
  1774. }
  1775. conjugate() {
  1776. this._x *= - 1;
  1777. this._y *= - 1;
  1778. this._z *= - 1;
  1779. this._onChangeCallback();
  1780. return this;
  1781. }
  1782. dot( v ) {
  1783. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1784. }
  1785. lengthSq() {
  1786. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1787. }
  1788. length() {
  1789. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1790. }
  1791. normalize() {
  1792. let l = this.length();
  1793. if ( l === 0 ) {
  1794. this._x = 0;
  1795. this._y = 0;
  1796. this._z = 0;
  1797. this._w = 1;
  1798. } else {
  1799. l = 1 / l;
  1800. this._x = this._x * l;
  1801. this._y = this._y * l;
  1802. this._z = this._z * l;
  1803. this._w = this._w * l;
  1804. }
  1805. this._onChangeCallback();
  1806. return this;
  1807. }
  1808. multiply( q, p ) {
  1809. if ( p !== undefined ) {
  1810. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1811. return this.multiplyQuaternions( q, p );
  1812. }
  1813. return this.multiplyQuaternions( this, q );
  1814. }
  1815. premultiply( q ) {
  1816. return this.multiplyQuaternions( q, this );
  1817. }
  1818. multiplyQuaternions( a, b ) {
  1819. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1820. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1821. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1822. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1823. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1824. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1825. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1826. this._onChangeCallback();
  1827. return this;
  1828. }
  1829. slerp( qb, t ) {
  1830. if ( t === 0 ) return this;
  1831. if ( t === 1 ) return this.copy( qb );
  1832. const x = this._x, y = this._y, z = this._z, w = this._w;
  1833. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1834. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1835. if ( cosHalfTheta < 0 ) {
  1836. this._w = - qb._w;
  1837. this._x = - qb._x;
  1838. this._y = - qb._y;
  1839. this._z = - qb._z;
  1840. cosHalfTheta = - cosHalfTheta;
  1841. } else {
  1842. this.copy( qb );
  1843. }
  1844. if ( cosHalfTheta >= 1.0 ) {
  1845. this._w = w;
  1846. this._x = x;
  1847. this._y = y;
  1848. this._z = z;
  1849. return this;
  1850. }
  1851. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1852. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1853. const s = 1 - t;
  1854. this._w = s * w + t * this._w;
  1855. this._x = s * x + t * this._x;
  1856. this._y = s * y + t * this._y;
  1857. this._z = s * z + t * this._z;
  1858. this.normalize();
  1859. this._onChangeCallback();
  1860. return this;
  1861. }
  1862. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1863. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1864. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1865. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1866. this._w = ( w * ratioA + this._w * ratioB );
  1867. this._x = ( x * ratioA + this._x * ratioB );
  1868. this._y = ( y * ratioA + this._y * ratioB );
  1869. this._z = ( z * ratioA + this._z * ratioB );
  1870. this._onChangeCallback();
  1871. return this;
  1872. }
  1873. equals( quaternion ) {
  1874. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1875. }
  1876. fromArray( array, offset = 0 ) {
  1877. this._x = array[ offset ];
  1878. this._y = array[ offset + 1 ];
  1879. this._z = array[ offset + 2 ];
  1880. this._w = array[ offset + 3 ];
  1881. this._onChangeCallback();
  1882. return this;
  1883. }
  1884. toArray( array = [], offset = 0 ) {
  1885. array[ offset ] = this._x;
  1886. array[ offset + 1 ] = this._y;
  1887. array[ offset + 2 ] = this._z;
  1888. array[ offset + 3 ] = this._w;
  1889. return array;
  1890. }
  1891. fromBufferAttribute( attribute, index ) {
  1892. this._x = attribute.getX( index );
  1893. this._y = attribute.getY( index );
  1894. this._z = attribute.getZ( index );
  1895. this._w = attribute.getW( index );
  1896. return this;
  1897. }
  1898. _onChange( callback ) {
  1899. this._onChangeCallback = callback;
  1900. return this;
  1901. }
  1902. _onChangeCallback() {}
  1903. }
  1904. class Vector3 {
  1905. constructor( x = 0, y = 0, z = 0 ) {
  1906. Object.defineProperty( this, 'isVector3', { value: true } );
  1907. this.x = x;
  1908. this.y = y;
  1909. this.z = z;
  1910. }
  1911. set( x, y, z ) {
  1912. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  1913. this.x = x;
  1914. this.y = y;
  1915. this.z = z;
  1916. return this;
  1917. }
  1918. setScalar( scalar ) {
  1919. this.x = scalar;
  1920. this.y = scalar;
  1921. this.z = scalar;
  1922. return this;
  1923. }
  1924. setX( x ) {
  1925. this.x = x;
  1926. return this;
  1927. }
  1928. setY( y ) {
  1929. this.y = y;
  1930. return this;
  1931. }
  1932. setZ( z ) {
  1933. this.z = z;
  1934. return this;
  1935. }
  1936. setComponent( index, value ) {
  1937. switch ( index ) {
  1938. case 0: this.x = value; break;
  1939. case 1: this.y = value; break;
  1940. case 2: this.z = value; break;
  1941. default: throw new Error( 'index is out of range: ' + index );
  1942. }
  1943. return this;
  1944. }
  1945. getComponent( index ) {
  1946. switch ( index ) {
  1947. case 0: return this.x;
  1948. case 1: return this.y;
  1949. case 2: return this.z;
  1950. default: throw new Error( 'index is out of range: ' + index );
  1951. }
  1952. }
  1953. clone() {
  1954. return new this.constructor( this.x, this.y, this.z );
  1955. }
  1956. copy( v ) {
  1957. this.x = v.x;
  1958. this.y = v.y;
  1959. this.z = v.z;
  1960. return this;
  1961. }
  1962. add( v, w ) {
  1963. if ( w !== undefined ) {
  1964. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1965. return this.addVectors( v, w );
  1966. }
  1967. this.x += v.x;
  1968. this.y += v.y;
  1969. this.z += v.z;
  1970. return this;
  1971. }
  1972. addScalar( s ) {
  1973. this.x += s;
  1974. this.y += s;
  1975. this.z += s;
  1976. return this;
  1977. }
  1978. addVectors( a, b ) {
  1979. this.x = a.x + b.x;
  1980. this.y = a.y + b.y;
  1981. this.z = a.z + b.z;
  1982. return this;
  1983. }
  1984. addScaledVector( v, s ) {
  1985. this.x += v.x * s;
  1986. this.y += v.y * s;
  1987. this.z += v.z * s;
  1988. return this;
  1989. }
  1990. sub( v, w ) {
  1991. if ( w !== undefined ) {
  1992. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1993. return this.subVectors( v, w );
  1994. }
  1995. this.x -= v.x;
  1996. this.y -= v.y;
  1997. this.z -= v.z;
  1998. return this;
  1999. }
  2000. subScalar( s ) {
  2001. this.x -= s;
  2002. this.y -= s;
  2003. this.z -= s;
  2004. return this;
  2005. }
  2006. subVectors( a, b ) {
  2007. this.x = a.x - b.x;
  2008. this.y = a.y - b.y;
  2009. this.z = a.z - b.z;
  2010. return this;
  2011. }
  2012. multiply( v, w ) {
  2013. if ( w !== undefined ) {
  2014. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2015. return this.multiplyVectors( v, w );
  2016. }
  2017. this.x *= v.x;
  2018. this.y *= v.y;
  2019. this.z *= v.z;
  2020. return this;
  2021. }
  2022. multiplyScalar( scalar ) {
  2023. this.x *= scalar;
  2024. this.y *= scalar;
  2025. this.z *= scalar;
  2026. return this;
  2027. }
  2028. multiplyVectors( a, b ) {
  2029. this.x = a.x * b.x;
  2030. this.y = a.y * b.y;
  2031. this.z = a.z * b.z;
  2032. return this;
  2033. }
  2034. applyEuler( euler ) {
  2035. if ( ! ( euler && euler.isEuler ) ) {
  2036. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2037. }
  2038. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  2039. }
  2040. applyAxisAngle( axis, angle ) {
  2041. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  2042. }
  2043. applyMatrix3( m ) {
  2044. const x = this.x, y = this.y, z = this.z;
  2045. const e = m.elements;
  2046. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2047. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2048. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2049. return this;
  2050. }
  2051. applyNormalMatrix( m ) {
  2052. return this.applyMatrix3( m ).normalize();
  2053. }
  2054. applyMatrix4( m ) {
  2055. const x = this.x, y = this.y, z = this.z;
  2056. const e = m.elements;
  2057. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2058. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2059. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2060. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2061. return this;
  2062. }
  2063. applyQuaternion( q ) {
  2064. const x = this.x, y = this.y, z = this.z;
  2065. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2066. // calculate quat * vector
  2067. const ix = qw * x + qy * z - qz * y;
  2068. const iy = qw * y + qz * x - qx * z;
  2069. const iz = qw * z + qx * y - qy * x;
  2070. const iw = - qx * x - qy * y - qz * z;
  2071. // calculate result * inverse quat
  2072. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2073. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2074. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2075. return this;
  2076. }
  2077. project( camera ) {
  2078. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2079. }
  2080. unproject( camera ) {
  2081. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2082. }
  2083. transformDirection( m ) {
  2084. // input: THREE.Matrix4 affine matrix
  2085. // vector interpreted as a direction
  2086. const x = this.x, y = this.y, z = this.z;
  2087. const e = m.elements;
  2088. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2089. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2090. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2091. return this.normalize();
  2092. }
  2093. divide( v ) {
  2094. this.x /= v.x;
  2095. this.y /= v.y;
  2096. this.z /= v.z;
  2097. return this;
  2098. }
  2099. divideScalar( scalar ) {
  2100. return this.multiplyScalar( 1 / scalar );
  2101. }
  2102. min( v ) {
  2103. this.x = Math.min( this.x, v.x );
  2104. this.y = Math.min( this.y, v.y );
  2105. this.z = Math.min( this.z, v.z );
  2106. return this;
  2107. }
  2108. max( v ) {
  2109. this.x = Math.max( this.x, v.x );
  2110. this.y = Math.max( this.y, v.y );
  2111. this.z = Math.max( this.z, v.z );
  2112. return this;
  2113. }
  2114. clamp( min, max ) {
  2115. // assumes min < max, componentwise
  2116. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2117. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2118. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2119. return this;
  2120. }
  2121. clampScalar( minVal, maxVal ) {
  2122. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2123. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2124. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2125. return this;
  2126. }
  2127. clampLength( min, max ) {
  2128. const length = this.length();
  2129. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2130. }
  2131. floor() {
  2132. this.x = Math.floor( this.x );
  2133. this.y = Math.floor( this.y );
  2134. this.z = Math.floor( this.z );
  2135. return this;
  2136. }
  2137. ceil() {
  2138. this.x = Math.ceil( this.x );
  2139. this.y = Math.ceil( this.y );
  2140. this.z = Math.ceil( this.z );
  2141. return this;
  2142. }
  2143. round() {
  2144. this.x = Math.round( this.x );
  2145. this.y = Math.round( this.y );
  2146. this.z = Math.round( this.z );
  2147. return this;
  2148. }
  2149. roundToZero() {
  2150. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2151. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2152. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2153. return this;
  2154. }
  2155. negate() {
  2156. this.x = - this.x;
  2157. this.y = - this.y;
  2158. this.z = - this.z;
  2159. return this;
  2160. }
  2161. dot( v ) {
  2162. return this.x * v.x + this.y * v.y + this.z * v.z;
  2163. }
  2164. // TODO lengthSquared?
  2165. lengthSq() {
  2166. return this.x * this.x + this.y * this.y + this.z * this.z;
  2167. }
  2168. length() {
  2169. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2170. }
  2171. manhattanLength() {
  2172. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2173. }
  2174. normalize() {
  2175. return this.divideScalar( this.length() || 1 );
  2176. }
  2177. setLength( length ) {
  2178. return this.normalize().multiplyScalar( length );
  2179. }
  2180. lerp( v, alpha ) {
  2181. this.x += ( v.x - this.x ) * alpha;
  2182. this.y += ( v.y - this.y ) * alpha;
  2183. this.z += ( v.z - this.z ) * alpha;
  2184. return this;
  2185. }
  2186. lerpVectors( v1, v2, alpha ) {
  2187. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2188. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2189. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2190. return this;
  2191. }
  2192. cross( v, w ) {
  2193. if ( w !== undefined ) {
  2194. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2195. return this.crossVectors( v, w );
  2196. }
  2197. return this.crossVectors( this, v );
  2198. }
  2199. crossVectors( a, b ) {
  2200. const ax = a.x, ay = a.y, az = a.z;
  2201. const bx = b.x, by = b.y, bz = b.z;
  2202. this.x = ay * bz - az * by;
  2203. this.y = az * bx - ax * bz;
  2204. this.z = ax * by - ay * bx;
  2205. return this;
  2206. }
  2207. projectOnVector( v ) {
  2208. const denominator = v.lengthSq();
  2209. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2210. const scalar = v.dot( this ) / denominator;
  2211. return this.copy( v ).multiplyScalar( scalar );
  2212. }
  2213. projectOnPlane( planeNormal ) {
  2214. _vector.copy( this ).projectOnVector( planeNormal );
  2215. return this.sub( _vector );
  2216. }
  2217. reflect( normal ) {
  2218. // reflect incident vector off plane orthogonal to normal
  2219. // normal is assumed to have unit length
  2220. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2221. }
  2222. angleTo( v ) {
  2223. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2224. if ( denominator === 0 ) return Math.PI / 2;
  2225. const theta = this.dot( v ) / denominator;
  2226. // clamp, to handle numerical problems
  2227. return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
  2228. }
  2229. distanceTo( v ) {
  2230. return Math.sqrt( this.distanceToSquared( v ) );
  2231. }
  2232. distanceToSquared( v ) {
  2233. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2234. return dx * dx + dy * dy + dz * dz;
  2235. }
  2236. manhattanDistanceTo( v ) {
  2237. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2238. }
  2239. setFromSpherical( s ) {
  2240. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2241. }
  2242. setFromSphericalCoords( radius, phi, theta ) {
  2243. const sinPhiRadius = Math.sin( phi ) * radius;
  2244. this.x = sinPhiRadius * Math.sin( theta );
  2245. this.y = Math.cos( phi ) * radius;
  2246. this.z = sinPhiRadius * Math.cos( theta );
  2247. return this;
  2248. }
  2249. setFromCylindrical( c ) {
  2250. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2251. }
  2252. setFromCylindricalCoords( radius, theta, y ) {
  2253. this.x = radius * Math.sin( theta );
  2254. this.y = y;
  2255. this.z = radius * Math.cos( theta );
  2256. return this;
  2257. }
  2258. setFromMatrixPosition( m ) {
  2259. const e = m.elements;
  2260. this.x = e[ 12 ];
  2261. this.y = e[ 13 ];
  2262. this.z = e[ 14 ];
  2263. return this;
  2264. }
  2265. setFromMatrixScale( m ) {
  2266. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2267. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2268. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2269. this.x = sx;
  2270. this.y = sy;
  2271. this.z = sz;
  2272. return this;
  2273. }
  2274. setFromMatrixColumn( m, index ) {
  2275. return this.fromArray( m.elements, index * 4 );
  2276. }
  2277. setFromMatrix3Column( m, index ) {
  2278. return this.fromArray( m.elements, index * 3 );
  2279. }
  2280. equals( v ) {
  2281. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2282. }
  2283. fromArray( array, offset = 0 ) {
  2284. this.x = array[ offset ];
  2285. this.y = array[ offset + 1 ];
  2286. this.z = array[ offset + 2 ];
  2287. return this;
  2288. }
  2289. toArray( array = [], offset = 0 ) {
  2290. array[ offset ] = this.x;
  2291. array[ offset + 1 ] = this.y;
  2292. array[ offset + 2 ] = this.z;
  2293. return array;
  2294. }
  2295. fromBufferAttribute( attribute, index, offset ) {
  2296. if ( offset !== undefined ) {
  2297. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  2298. }
  2299. this.x = attribute.getX( index );
  2300. this.y = attribute.getY( index );
  2301. this.z = attribute.getZ( index );
  2302. return this;
  2303. }
  2304. random() {
  2305. this.x = Math.random();
  2306. this.y = Math.random();
  2307. this.z = Math.random();
  2308. return this;
  2309. }
  2310. }
  2311. const _vector = /*@__PURE__*/ new Vector3();
  2312. const _quaternion = /*@__PURE__*/ new Quaternion();
  2313. class Box3 {
  2314. constructor( min, max ) {
  2315. Object.defineProperty( this, 'isBox3', { value: true } );
  2316. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  2317. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  2318. }
  2319. set( min, max ) {
  2320. this.min.copy( min );
  2321. this.max.copy( max );
  2322. return this;
  2323. }
  2324. setFromArray( array ) {
  2325. let minX = + Infinity;
  2326. let minY = + Infinity;
  2327. let minZ = + Infinity;
  2328. let maxX = - Infinity;
  2329. let maxY = - Infinity;
  2330. let maxZ = - Infinity;
  2331. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2332. const x = array[ i ];
  2333. const y = array[ i + 1 ];
  2334. const z = array[ i + 2 ];
  2335. if ( x < minX ) minX = x;
  2336. if ( y < minY ) minY = y;
  2337. if ( z < minZ ) minZ = z;
  2338. if ( x > maxX ) maxX = x;
  2339. if ( y > maxY ) maxY = y;
  2340. if ( z > maxZ ) maxZ = z;
  2341. }
  2342. this.min.set( minX, minY, minZ );
  2343. this.max.set( maxX, maxY, maxZ );
  2344. return this;
  2345. }
  2346. setFromBufferAttribute( attribute ) {
  2347. let minX = + Infinity;
  2348. let minY = + Infinity;
  2349. let minZ = + Infinity;
  2350. let maxX = - Infinity;
  2351. let maxY = - Infinity;
  2352. let maxZ = - Infinity;
  2353. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2354. const x = attribute.getX( i );
  2355. const y = attribute.getY( i );
  2356. const z = attribute.getZ( i );
  2357. if ( x < minX ) minX = x;
  2358. if ( y < minY ) minY = y;
  2359. if ( z < minZ ) minZ = z;
  2360. if ( x > maxX ) maxX = x;
  2361. if ( y > maxY ) maxY = y;
  2362. if ( z > maxZ ) maxZ = z;
  2363. }
  2364. this.min.set( minX, minY, minZ );
  2365. this.max.set( maxX, maxY, maxZ );
  2366. return this;
  2367. }
  2368. setFromPoints( points ) {
  2369. this.makeEmpty();
  2370. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2371. this.expandByPoint( points[ i ] );
  2372. }
  2373. return this;
  2374. }
  2375. setFromCenterAndSize( center, size ) {
  2376. const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
  2377. this.min.copy( center ).sub( halfSize );
  2378. this.max.copy( center ).add( halfSize );
  2379. return this;
  2380. }
  2381. setFromObject( object ) {
  2382. this.makeEmpty();
  2383. return this.expandByObject( object );
  2384. }
  2385. clone() {
  2386. return new this.constructor().copy( this );
  2387. }
  2388. copy( box ) {
  2389. this.min.copy( box.min );
  2390. this.max.copy( box.max );
  2391. return this;
  2392. }
  2393. makeEmpty() {
  2394. this.min.x = this.min.y = this.min.z = + Infinity;
  2395. this.max.x = this.max.y = this.max.z = - Infinity;
  2396. return this;
  2397. }
  2398. isEmpty() {
  2399. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2400. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2401. }
  2402. getCenter( target ) {
  2403. if ( target === undefined ) {
  2404. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  2405. target = new Vector3();
  2406. }
  2407. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2408. }
  2409. getSize( target ) {
  2410. if ( target === undefined ) {
  2411. console.warn( 'THREE.Box3: .getSize() target is now required' );
  2412. target = new Vector3();
  2413. }
  2414. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2415. }
  2416. expandByPoint( point ) {
  2417. this.min.min( point );
  2418. this.max.max( point );
  2419. return this;
  2420. }
  2421. expandByVector( vector ) {
  2422. this.min.sub( vector );
  2423. this.max.add( vector );
  2424. return this;
  2425. }
  2426. expandByScalar( scalar ) {
  2427. this.min.addScalar( - scalar );
  2428. this.max.addScalar( scalar );
  2429. return this;
  2430. }
  2431. expandByObject( object ) {
  2432. // Computes the world-axis-aligned bounding box of an object (including its children),
  2433. // accounting for both the object's, and children's, world transforms
  2434. object.updateWorldMatrix( false, false );
  2435. const geometry = object.geometry;
  2436. if ( geometry !== undefined ) {
  2437. if ( geometry.boundingBox === null ) {
  2438. geometry.computeBoundingBox();
  2439. }
  2440. _box.copy( geometry.boundingBox );
  2441. _box.applyMatrix4( object.matrixWorld );
  2442. this.union( _box );
  2443. }
  2444. const children = object.children;
  2445. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2446. this.expandByObject( children[ i ] );
  2447. }
  2448. return this;
  2449. }
  2450. containsPoint( point ) {
  2451. return point.x < this.min.x || point.x > this.max.x ||
  2452. point.y < this.min.y || point.y > this.max.y ||
  2453. point.z < this.min.z || point.z > this.max.z ? false : true;
  2454. }
  2455. containsBox( box ) {
  2456. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2457. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2458. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2459. }
  2460. getParameter( point, target ) {
  2461. // This can potentially have a divide by zero if the box
  2462. // has a size dimension of 0.
  2463. if ( target === undefined ) {
  2464. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  2465. target = new Vector3();
  2466. }
  2467. return target.set(
  2468. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2469. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2470. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2471. );
  2472. }
  2473. intersectsBox( box ) {
  2474. // using 6 splitting planes to rule out intersections.
  2475. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2476. box.max.y < this.min.y || box.min.y > this.max.y ||
  2477. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2478. }
  2479. intersectsSphere( sphere ) {
  2480. // Find the point on the AABB closest to the sphere center.
  2481. this.clampPoint( sphere.center, _vector$1 );
  2482. // If that point is inside the sphere, the AABB and sphere intersect.
  2483. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2484. }
  2485. intersectsPlane( plane ) {
  2486. // We compute the minimum and maximum dot product values. If those values
  2487. // are on the same side (back or front) of the plane, then there is no intersection.
  2488. let min, max;
  2489. if ( plane.normal.x > 0 ) {
  2490. min = plane.normal.x * this.min.x;
  2491. max = plane.normal.x * this.max.x;
  2492. } else {
  2493. min = plane.normal.x * this.max.x;
  2494. max = plane.normal.x * this.min.x;
  2495. }
  2496. if ( plane.normal.y > 0 ) {
  2497. min += plane.normal.y * this.min.y;
  2498. max += plane.normal.y * this.max.y;
  2499. } else {
  2500. min += plane.normal.y * this.max.y;
  2501. max += plane.normal.y * this.min.y;
  2502. }
  2503. if ( plane.normal.z > 0 ) {
  2504. min += plane.normal.z * this.min.z;
  2505. max += plane.normal.z * this.max.z;
  2506. } else {
  2507. min += plane.normal.z * this.max.z;
  2508. max += plane.normal.z * this.min.z;
  2509. }
  2510. return ( min <= - plane.constant && max >= - plane.constant );
  2511. }
  2512. intersectsTriangle( triangle ) {
  2513. if ( this.isEmpty() ) {
  2514. return false;
  2515. }
  2516. // compute box center and extents
  2517. this.getCenter( _center );
  2518. _extents.subVectors( this.max, _center );
  2519. // translate triangle to aabb origin
  2520. _v0.subVectors( triangle.a, _center );
  2521. _v1.subVectors( triangle.b, _center );
  2522. _v2.subVectors( triangle.c, _center );
  2523. // compute edge vectors for triangle
  2524. _f0.subVectors( _v1, _v0 );
  2525. _f1.subVectors( _v2, _v1 );
  2526. _f2.subVectors( _v0, _v2 );
  2527. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2528. // 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
  2529. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2530. let axes = [
  2531. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2532. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2533. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2534. ];
  2535. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  2536. return false;
  2537. }
  2538. // test 3 face normals from the aabb
  2539. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2540. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  2541. return false;
  2542. }
  2543. // finally testing the face normal of the triangle
  2544. // use already existing triangle edge vectors here
  2545. _triangleNormal.crossVectors( _f0, _f1 );
  2546. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2547. return satForAxes( axes, _v0, _v1, _v2, _extents );
  2548. }
  2549. clampPoint( point, target ) {
  2550. if ( target === undefined ) {
  2551. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  2552. target = new Vector3();
  2553. }
  2554. return target.copy( point ).clamp( this.min, this.max );
  2555. }
  2556. distanceToPoint( point ) {
  2557. const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
  2558. return clampedPoint.sub( point ).length();
  2559. }
  2560. getBoundingSphere( target ) {
  2561. if ( target === undefined ) {
  2562. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  2563. //target = new Sphere(); // removed to avoid cyclic dependency
  2564. }
  2565. this.getCenter( target.center );
  2566. target.radius = this.getSize( _vector$1 ).length() * 0.5;
  2567. return target;
  2568. }
  2569. intersect( box ) {
  2570. this.min.max( box.min );
  2571. this.max.min( box.max );
  2572. // 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.
  2573. if ( this.isEmpty() ) this.makeEmpty();
  2574. return this;
  2575. }
  2576. union( box ) {
  2577. this.min.min( box.min );
  2578. this.max.max( box.max );
  2579. return this;
  2580. }
  2581. applyMatrix4( matrix ) {
  2582. // transform of empty box is an empty box.
  2583. if ( this.isEmpty() ) return this;
  2584. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2585. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2586. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2587. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2588. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2589. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2590. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2591. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2592. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2593. this.setFromPoints( _points );
  2594. return this;
  2595. }
  2596. translate( offset ) {
  2597. this.min.add( offset );
  2598. this.max.add( offset );
  2599. return this;
  2600. }
  2601. equals( box ) {
  2602. return box.min.equals( this.min ) && box.max.equals( this.max );
  2603. }
  2604. }
  2605. function satForAxes( axes, v0, v1, v2, extents ) {
  2606. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2607. _testAxis.fromArray( axes, i );
  2608. // project the aabb onto the seperating axis
  2609. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2610. // project all 3 vertices of the triangle onto the seperating axis
  2611. const p0 = v0.dot( _testAxis );
  2612. const p1 = v1.dot( _testAxis );
  2613. const p2 = v2.dot( _testAxis );
  2614. // actual test, basically see if either of the most extreme of the triangle points intersects r
  2615. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  2616. // points of the projected triangle are outside the projected half-length of the aabb
  2617. // the axis is seperating and we can exit
  2618. return false;
  2619. }
  2620. }
  2621. return true;
  2622. }
  2623. const _points = [
  2624. /*@__PURE__*/ new Vector3(),
  2625. /*@__PURE__*/ new Vector3(),
  2626. /*@__PURE__*/ new Vector3(),
  2627. /*@__PURE__*/ new Vector3(),
  2628. /*@__PURE__*/ new Vector3(),
  2629. /*@__PURE__*/ new Vector3(),
  2630. /*@__PURE__*/ new Vector3(),
  2631. /*@__PURE__*/ new Vector3()
  2632. ];
  2633. const _vector$1 = /*@__PURE__*/ new Vector3();
  2634. const _box = /*@__PURE__*/ new Box3();
  2635. // triangle centered vertices
  2636. const _v0 = /*@__PURE__*/ new Vector3();
  2637. const _v1 = /*@__PURE__*/ new Vector3();
  2638. const _v2 = /*@__PURE__*/ new Vector3();
  2639. // triangle edge vectors
  2640. const _f0 = /*@__PURE__*/ new Vector3();
  2641. const _f1 = /*@__PURE__*/ new Vector3();
  2642. const _f2 = /*@__PURE__*/ new Vector3();
  2643. const _center = /*@__PURE__*/ new Vector3();
  2644. const _extents = /*@__PURE__*/ new Vector3();
  2645. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2646. const _testAxis = /*@__PURE__*/ new Vector3();
  2647. const _box$1 = /*@__PURE__*/ new Box3();
  2648. class Sphere {
  2649. constructor( center, radius ) {
  2650. this.center = ( center !== undefined ) ? center : new Vector3();
  2651. this.radius = ( radius !== undefined ) ? radius : - 1;
  2652. }
  2653. set( center, radius ) {
  2654. this.center.copy( center );
  2655. this.radius = radius;
  2656. return this;
  2657. }
  2658. setFromPoints( points, optionalCenter ) {
  2659. const center = this.center;
  2660. if ( optionalCenter !== undefined ) {
  2661. center.copy( optionalCenter );
  2662. } else {
  2663. _box$1.setFromPoints( points ).getCenter( center );
  2664. }
  2665. let maxRadiusSq = 0;
  2666. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2667. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  2668. }
  2669. this.radius = Math.sqrt( maxRadiusSq );
  2670. return this;
  2671. }
  2672. clone() {
  2673. return new this.constructor().copy( this );
  2674. }
  2675. copy( sphere ) {
  2676. this.center.copy( sphere.center );
  2677. this.radius = sphere.radius;
  2678. return this;
  2679. }
  2680. isEmpty() {
  2681. return ( this.radius < 0 );
  2682. }
  2683. makeEmpty() {
  2684. this.center.set( 0, 0, 0 );
  2685. this.radius = - 1;
  2686. return this;
  2687. }
  2688. containsPoint( point ) {
  2689. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2690. }
  2691. distanceToPoint( point ) {
  2692. return ( point.distanceTo( this.center ) - this.radius );
  2693. }
  2694. intersectsSphere( sphere ) {
  2695. const radiusSum = this.radius + sphere.radius;
  2696. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2697. }
  2698. intersectsBox( box ) {
  2699. return box.intersectsSphere( this );
  2700. }
  2701. intersectsPlane( plane ) {
  2702. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  2703. }
  2704. clampPoint( point, target ) {
  2705. const deltaLengthSq = this.center.distanceToSquared( point );
  2706. if ( target === undefined ) {
  2707. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  2708. target = new Vector3();
  2709. }
  2710. target.copy( point );
  2711. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2712. target.sub( this.center ).normalize();
  2713. target.multiplyScalar( this.radius ).add( this.center );
  2714. }
  2715. return target;
  2716. }
  2717. getBoundingBox( target ) {
  2718. if ( target === undefined ) {
  2719. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  2720. target = new Box3();
  2721. }
  2722. if ( this.isEmpty() ) {
  2723. // Empty sphere produces empty bounding box
  2724. target.makeEmpty();
  2725. return target;
  2726. }
  2727. target.set( this.center, this.center );
  2728. target.expandByScalar( this.radius );
  2729. return target;
  2730. }
  2731. applyMatrix4( matrix ) {
  2732. this.center.applyMatrix4( matrix );
  2733. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2734. return this;
  2735. }
  2736. translate( offset ) {
  2737. this.center.add( offset );
  2738. return this;
  2739. }
  2740. equals( sphere ) {
  2741. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2742. }
  2743. }
  2744. const _vector$2 = /*@__PURE__*/ new Vector3();
  2745. const _segCenter = /*@__PURE__*/ new Vector3();
  2746. const _segDir = /*@__PURE__*/ new Vector3();
  2747. const _diff = /*@__PURE__*/ new Vector3();
  2748. const _edge1 = /*@__PURE__*/ new Vector3();
  2749. const _edge2 = /*@__PURE__*/ new Vector3();
  2750. const _normal = /*@__PURE__*/ new Vector3();
  2751. class Ray {
  2752. constructor( origin, direction ) {
  2753. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  2754. this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );
  2755. }
  2756. set( origin, direction ) {
  2757. this.origin.copy( origin );
  2758. this.direction.copy( direction );
  2759. return this;
  2760. }
  2761. clone() {
  2762. return new this.constructor().copy( this );
  2763. }
  2764. copy( ray ) {
  2765. this.origin.copy( ray.origin );
  2766. this.direction.copy( ray.direction );
  2767. return this;
  2768. }
  2769. at( t, target ) {
  2770. if ( target === undefined ) {
  2771. console.warn( 'THREE.Ray: .at() target is now required' );
  2772. target = new Vector3();
  2773. }
  2774. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2775. }
  2776. lookAt( v ) {
  2777. this.direction.copy( v ).sub( this.origin ).normalize();
  2778. return this;
  2779. }
  2780. recast( t ) {
  2781. this.origin.copy( this.at( t, _vector$2 ) );
  2782. return this;
  2783. }
  2784. closestPointToPoint( point, target ) {
  2785. if ( target === undefined ) {
  2786. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  2787. target = new Vector3();
  2788. }
  2789. target.subVectors( point, this.origin );
  2790. const directionDistance = target.dot( this.direction );
  2791. if ( directionDistance < 0 ) {
  2792. return target.copy( this.origin );
  2793. }
  2794. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2795. }
  2796. distanceToPoint( point ) {
  2797. return Math.sqrt( this.distanceSqToPoint( point ) );
  2798. }
  2799. distanceSqToPoint( point ) {
  2800. const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
  2801. // point behind the ray
  2802. if ( directionDistance < 0 ) {
  2803. return this.origin.distanceToSquared( point );
  2804. }
  2805. _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2806. return _vector$2.distanceToSquared( point );
  2807. }
  2808. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  2809. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  2810. // It returns the min distance between the ray and the segment
  2811. // defined by v0 and v1
  2812. // It can also set two optional targets :
  2813. // - The closest point on the ray
  2814. // - The closest point on the segment
  2815. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  2816. _segDir.copy( v1 ).sub( v0 ).normalize();
  2817. _diff.copy( this.origin ).sub( _segCenter );
  2818. const segExtent = v0.distanceTo( v1 ) * 0.5;
  2819. const a01 = - this.direction.dot( _segDir );
  2820. const b0 = _diff.dot( this.direction );
  2821. const b1 = - _diff.dot( _segDir );
  2822. const c = _diff.lengthSq();
  2823. const det = Math.abs( 1 - a01 * a01 );
  2824. let s0, s1, sqrDist, extDet;
  2825. if ( det > 0 ) {
  2826. // The ray and segment are not parallel.
  2827. s0 = a01 * b1 - b0;
  2828. s1 = a01 * b0 - b1;
  2829. extDet = segExtent * det;
  2830. if ( s0 >= 0 ) {
  2831. if ( s1 >= - extDet ) {
  2832. if ( s1 <= extDet ) {
  2833. // region 0
  2834. // Minimum at interior points of ray and segment.
  2835. const invDet = 1 / det;
  2836. s0 *= invDet;
  2837. s1 *= invDet;
  2838. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  2839. } else {
  2840. // region 1
  2841. s1 = segExtent;
  2842. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2843. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2844. }
  2845. } else {
  2846. // region 5
  2847. s1 = - segExtent;
  2848. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2849. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2850. }
  2851. } else {
  2852. if ( s1 <= - extDet ) {
  2853. // region 4
  2854. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  2855. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2856. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2857. } else if ( s1 <= extDet ) {
  2858. // region 3
  2859. s0 = 0;
  2860. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2861. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  2862. } else {
  2863. // region 2
  2864. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  2865. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  2866. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2867. }
  2868. }
  2869. } else {
  2870. // Ray and segment are parallel.
  2871. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  2872. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  2873. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  2874. }
  2875. if ( optionalPointOnRay ) {
  2876. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  2877. }
  2878. if ( optionalPointOnSegment ) {
  2879. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  2880. }
  2881. return sqrDist;
  2882. }
  2883. intersectSphere( sphere, target ) {
  2884. _vector$2.subVectors( sphere.center, this.origin );
  2885. const tca = _vector$2.dot( this.direction );
  2886. const d2 = _vector$2.dot( _vector$2 ) - tca * tca;
  2887. const radius2 = sphere.radius * sphere.radius;
  2888. if ( d2 > radius2 ) return null;
  2889. const thc = Math.sqrt( radius2 - d2 );
  2890. // t0 = first intersect point - entrance on front of sphere
  2891. const t0 = tca - thc;
  2892. // t1 = second intersect point - exit point on back of sphere
  2893. const t1 = tca + thc;
  2894. // test to see if both t0 and t1 are behind the ray - if so, return null
  2895. if ( t0 < 0 && t1 < 0 ) return null;
  2896. // test to see if t0 is behind the ray:
  2897. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  2898. // in order to always return an intersect point that is in front of the ray.
  2899. if ( t0 < 0 ) return this.at( t1, target );
  2900. // else t0 is in front of the ray, so return the first collision point scaled by t0
  2901. return this.at( t0, target );
  2902. }
  2903. intersectsSphere( sphere ) {
  2904. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  2905. }
  2906. distanceToPlane( plane ) {
  2907. const denominator = plane.normal.dot( this.direction );
  2908. if ( denominator === 0 ) {
  2909. // line is coplanar, return origin
  2910. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  2911. return 0;
  2912. }
  2913. // Null is preferable to undefined since undefined means.... it is undefined
  2914. return null;
  2915. }
  2916. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2917. // Return if the ray never intersects the plane
  2918. return t >= 0 ? t : null;
  2919. }
  2920. intersectPlane( plane, target ) {
  2921. const t = this.distanceToPlane( plane );
  2922. if ( t === null ) {
  2923. return null;
  2924. }
  2925. return this.at( t, target );
  2926. }
  2927. intersectsPlane( plane ) {
  2928. // check if the ray lies on the plane first
  2929. const distToPoint = plane.distanceToPoint( this.origin );
  2930. if ( distToPoint === 0 ) {
  2931. return true;
  2932. }
  2933. const denominator = plane.normal.dot( this.direction );
  2934. if ( denominator * distToPoint < 0 ) {
  2935. return true;
  2936. }
  2937. // ray origin is behind the plane (and is pointing behind it)
  2938. return false;
  2939. }
  2940. intersectBox( box, target ) {
  2941. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  2942. const invdirx = 1 / this.direction.x,
  2943. invdiry = 1 / this.direction.y,
  2944. invdirz = 1 / this.direction.z;
  2945. const origin = this.origin;
  2946. if ( invdirx >= 0 ) {
  2947. tmin = ( box.min.x - origin.x ) * invdirx;
  2948. tmax = ( box.max.x - origin.x ) * invdirx;
  2949. } else {
  2950. tmin = ( box.max.x - origin.x ) * invdirx;
  2951. tmax = ( box.min.x - origin.x ) * invdirx;
  2952. }
  2953. if ( invdiry >= 0 ) {
  2954. tymin = ( box.min.y - origin.y ) * invdiry;
  2955. tymax = ( box.max.y - origin.y ) * invdiry;
  2956. } else {
  2957. tymin = ( box.max.y - origin.y ) * invdiry;
  2958. tymax = ( box.min.y - origin.y ) * invdiry;
  2959. }
  2960. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  2961. // These lines also handle the case where tmin or tmax is NaN
  2962. // (result of 0 * Infinity). x !== x returns true if x is NaN
  2963. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  2964. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  2965. if ( invdirz >= 0 ) {
  2966. tzmin = ( box.min.z - origin.z ) * invdirz;
  2967. tzmax = ( box.max.z - origin.z ) * invdirz;
  2968. } else {
  2969. tzmin = ( box.max.z - origin.z ) * invdirz;
  2970. tzmax = ( box.min.z - origin.z ) * invdirz;
  2971. }
  2972. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  2973. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  2974. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  2975. //return point closest to the ray (positive side)
  2976. if ( tmax < 0 ) return null;
  2977. return this.at( tmin >= 0 ? tmin : tmax, target );
  2978. }
  2979. intersectsBox( box ) {
  2980. return this.intersectBox( box, _vector$2 ) !== null;
  2981. }
  2982. intersectTriangle( a, b, c, backfaceCulling, target ) {
  2983. // Compute the offset origin, edges, and normal.
  2984. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  2985. _edge1.subVectors( b, a );
  2986. _edge2.subVectors( c, a );
  2987. _normal.crossVectors( _edge1, _edge2 );
  2988. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  2989. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  2990. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  2991. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  2992. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  2993. let DdN = this.direction.dot( _normal );
  2994. let sign;
  2995. if ( DdN > 0 ) {
  2996. if ( backfaceCulling ) return null;
  2997. sign = 1;
  2998. } else if ( DdN < 0 ) {
  2999. sign = - 1;
  3000. DdN = - DdN;
  3001. } else {
  3002. return null;
  3003. }
  3004. _diff.subVectors( this.origin, a );
  3005. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3006. // b1 < 0, no intersection
  3007. if ( DdQxE2 < 0 ) {
  3008. return null;
  3009. }
  3010. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3011. // b2 < 0, no intersection
  3012. if ( DdE1xQ < 0 ) {
  3013. return null;
  3014. }
  3015. // b1+b2 > 1, no intersection
  3016. if ( DdQxE2 + DdE1xQ > DdN ) {
  3017. return null;
  3018. }
  3019. // Line intersects triangle, check if ray does.
  3020. const QdN = - sign * _diff.dot( _normal );
  3021. // t < 0, no intersection
  3022. if ( QdN < 0 ) {
  3023. return null;
  3024. }
  3025. // Ray intersects triangle.
  3026. return this.at( QdN / DdN, target );
  3027. }
  3028. applyMatrix4( matrix4 ) {
  3029. this.origin.applyMatrix4( matrix4 );
  3030. this.direction.transformDirection( matrix4 );
  3031. return this;
  3032. }
  3033. equals( ray ) {
  3034. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3035. }
  3036. }
  3037. class Matrix4 {
  3038. constructor() {
  3039. Object.defineProperty( this, 'isMatrix4', { value: true } );
  3040. this.elements = [
  3041. 1, 0, 0, 0,
  3042. 0, 1, 0, 0,
  3043. 0, 0, 1, 0,
  3044. 0, 0, 0, 1
  3045. ];
  3046. if ( arguments.length > 0 ) {
  3047. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3048. }
  3049. }
  3050. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3051. const te = this.elements;
  3052. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3053. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3054. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3055. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3056. return this;
  3057. }
  3058. identity() {
  3059. this.set(
  3060. 1, 0, 0, 0,
  3061. 0, 1, 0, 0,
  3062. 0, 0, 1, 0,
  3063. 0, 0, 0, 1
  3064. );
  3065. return this;
  3066. }
  3067. clone() {
  3068. return new Matrix4().fromArray( this.elements );
  3069. }
  3070. copy( m ) {
  3071. const te = this.elements;
  3072. const me = m.elements;
  3073. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3074. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3075. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3076. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3077. return this;
  3078. }
  3079. copyPosition( m ) {
  3080. const te = this.elements, me = m.elements;
  3081. te[ 12 ] = me[ 12 ];
  3082. te[ 13 ] = me[ 13 ];
  3083. te[ 14 ] = me[ 14 ];
  3084. return this;
  3085. }
  3086. extractBasis( xAxis, yAxis, zAxis ) {
  3087. xAxis.setFromMatrixColumn( this, 0 );
  3088. yAxis.setFromMatrixColumn( this, 1 );
  3089. zAxis.setFromMatrixColumn( this, 2 );
  3090. return this;
  3091. }
  3092. makeBasis( xAxis, yAxis, zAxis ) {
  3093. this.set(
  3094. xAxis.x, yAxis.x, zAxis.x, 0,
  3095. xAxis.y, yAxis.y, zAxis.y, 0,
  3096. xAxis.z, yAxis.z, zAxis.z, 0,
  3097. 0, 0, 0, 1
  3098. );
  3099. return this;
  3100. }
  3101. extractRotation( m ) {
  3102. // this method does not support reflection matrices
  3103. const te = this.elements;
  3104. const me = m.elements;
  3105. const scaleX = 1 / _v1$1.setFromMatrixColumn( m, 0 ).length();
  3106. const scaleY = 1 / _v1$1.setFromMatrixColumn( m, 1 ).length();
  3107. const scaleZ = 1 / _v1$1.setFromMatrixColumn( m, 2 ).length();
  3108. te[ 0 ] = me[ 0 ] * scaleX;
  3109. te[ 1 ] = me[ 1 ] * scaleX;
  3110. te[ 2 ] = me[ 2 ] * scaleX;
  3111. te[ 3 ] = 0;
  3112. te[ 4 ] = me[ 4 ] * scaleY;
  3113. te[ 5 ] = me[ 5 ] * scaleY;
  3114. te[ 6 ] = me[ 6 ] * scaleY;
  3115. te[ 7 ] = 0;
  3116. te[ 8 ] = me[ 8 ] * scaleZ;
  3117. te[ 9 ] = me[ 9 ] * scaleZ;
  3118. te[ 10 ] = me[ 10 ] * scaleZ;
  3119. te[ 11 ] = 0;
  3120. te[ 12 ] = 0;
  3121. te[ 13 ] = 0;
  3122. te[ 14 ] = 0;
  3123. te[ 15 ] = 1;
  3124. return this;
  3125. }
  3126. makeRotationFromEuler( euler ) {
  3127. if ( ! ( euler && euler.isEuler ) ) {
  3128. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3129. }
  3130. const te = this.elements;
  3131. const x = euler.x, y = euler.y, z = euler.z;
  3132. const a = Math.cos( x ), b = Math.sin( x );
  3133. const c = Math.cos( y ), d = Math.sin( y );
  3134. const e = Math.cos( z ), f = Math.sin( z );
  3135. if ( euler.order === 'XYZ' ) {
  3136. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3137. te[ 0 ] = c * e;
  3138. te[ 4 ] = - c * f;
  3139. te[ 8 ] = d;
  3140. te[ 1 ] = af + be * d;
  3141. te[ 5 ] = ae - bf * d;
  3142. te[ 9 ] = - b * c;
  3143. te[ 2 ] = bf - ae * d;
  3144. te[ 6 ] = be + af * d;
  3145. te[ 10 ] = a * c;
  3146. } else if ( euler.order === 'YXZ' ) {
  3147. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3148. te[ 0 ] = ce + df * b;
  3149. te[ 4 ] = de * b - cf;
  3150. te[ 8 ] = a * d;
  3151. te[ 1 ] = a * f;
  3152. te[ 5 ] = a * e;
  3153. te[ 9 ] = - b;
  3154. te[ 2 ] = cf * b - de;
  3155. te[ 6 ] = df + ce * b;
  3156. te[ 10 ] = a * c;
  3157. } else if ( euler.order === 'ZXY' ) {
  3158. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3159. te[ 0 ] = ce - df * b;
  3160. te[ 4 ] = - a * f;
  3161. te[ 8 ] = de + cf * b;
  3162. te[ 1 ] = cf + de * b;
  3163. te[ 5 ] = a * e;
  3164. te[ 9 ] = df - ce * b;
  3165. te[ 2 ] = - a * d;
  3166. te[ 6 ] = b;
  3167. te[ 10 ] = a * c;
  3168. } else if ( euler.order === 'ZYX' ) {
  3169. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3170. te[ 0 ] = c * e;
  3171. te[ 4 ] = be * d - af;
  3172. te[ 8 ] = ae * d + bf;
  3173. te[ 1 ] = c * f;
  3174. te[ 5 ] = bf * d + ae;
  3175. te[ 9 ] = af * d - be;
  3176. te[ 2 ] = - d;
  3177. te[ 6 ] = b * c;
  3178. te[ 10 ] = a * c;
  3179. } else if ( euler.order === 'YZX' ) {
  3180. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3181. te[ 0 ] = c * e;
  3182. te[ 4 ] = bd - ac * f;
  3183. te[ 8 ] = bc * f + ad;
  3184. te[ 1 ] = f;
  3185. te[ 5 ] = a * e;
  3186. te[ 9 ] = - b * e;
  3187. te[ 2 ] = - d * e;
  3188. te[ 6 ] = ad * f + bc;
  3189. te[ 10 ] = ac - bd * f;
  3190. } else if ( euler.order === 'XZY' ) {
  3191. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3192. te[ 0 ] = c * e;
  3193. te[ 4 ] = - f;
  3194. te[ 8 ] = d * e;
  3195. te[ 1 ] = ac * f + bd;
  3196. te[ 5 ] = a * e;
  3197. te[ 9 ] = ad * f - bc;
  3198. te[ 2 ] = bc * f - ad;
  3199. te[ 6 ] = b * e;
  3200. te[ 10 ] = bd * f + ac;
  3201. }
  3202. // bottom row
  3203. te[ 3 ] = 0;
  3204. te[ 7 ] = 0;
  3205. te[ 11 ] = 0;
  3206. // last column
  3207. te[ 12 ] = 0;
  3208. te[ 13 ] = 0;
  3209. te[ 14 ] = 0;
  3210. te[ 15 ] = 1;
  3211. return this;
  3212. }
  3213. makeRotationFromQuaternion( q ) {
  3214. return this.compose( _zero, q, _one );
  3215. }
  3216. lookAt( eye, target, up ) {
  3217. const te = this.elements;
  3218. _z.subVectors( eye, target );
  3219. if ( _z.lengthSq() === 0 ) {
  3220. // eye and target are in the same position
  3221. _z.z = 1;
  3222. }
  3223. _z.normalize();
  3224. _x.crossVectors( up, _z );
  3225. if ( _x.lengthSq() === 0 ) {
  3226. // up and z are parallel
  3227. if ( Math.abs( up.z ) === 1 ) {
  3228. _z.x += 0.0001;
  3229. } else {
  3230. _z.z += 0.0001;
  3231. }
  3232. _z.normalize();
  3233. _x.crossVectors( up, _z );
  3234. }
  3235. _x.normalize();
  3236. _y.crossVectors( _z, _x );
  3237. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3238. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3239. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3240. return this;
  3241. }
  3242. multiply( m, n ) {
  3243. if ( n !== undefined ) {
  3244. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3245. return this.multiplyMatrices( m, n );
  3246. }
  3247. return this.multiplyMatrices( this, m );
  3248. }
  3249. premultiply( m ) {
  3250. return this.multiplyMatrices( m, this );
  3251. }
  3252. multiplyMatrices( a, b ) {
  3253. const ae = a.elements;
  3254. const be = b.elements;
  3255. const te = this.elements;
  3256. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3257. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3258. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3259. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3260. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3261. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3262. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3263. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3264. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3265. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3266. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3267. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3268. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3269. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3270. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3271. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3272. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3273. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3274. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3275. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3276. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3277. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3278. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3279. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3280. return this;
  3281. }
  3282. multiplyScalar( s ) {
  3283. const te = this.elements;
  3284. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3285. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3286. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3287. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3288. return this;
  3289. }
  3290. determinant() {
  3291. const te = this.elements;
  3292. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3293. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3294. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3295. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3296. //TODO: make this more efficient
  3297. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3298. return (
  3299. n41 * (
  3300. + n14 * n23 * n32
  3301. - n13 * n24 * n32
  3302. - n14 * n22 * n33
  3303. + n12 * n24 * n33
  3304. + n13 * n22 * n34
  3305. - n12 * n23 * n34
  3306. ) +
  3307. n42 * (
  3308. + n11 * n23 * n34
  3309. - n11 * n24 * n33
  3310. + n14 * n21 * n33
  3311. - n13 * n21 * n34
  3312. + n13 * n24 * n31
  3313. - n14 * n23 * n31
  3314. ) +
  3315. n43 * (
  3316. + n11 * n24 * n32
  3317. - n11 * n22 * n34
  3318. - n14 * n21 * n32
  3319. + n12 * n21 * n34
  3320. + n14 * n22 * n31
  3321. - n12 * n24 * n31
  3322. ) +
  3323. n44 * (
  3324. - n13 * n22 * n31
  3325. - n11 * n23 * n32
  3326. + n11 * n22 * n33
  3327. + n13 * n21 * n32
  3328. - n12 * n21 * n33
  3329. + n12 * n23 * n31
  3330. )
  3331. );
  3332. }
  3333. transpose() {
  3334. const te = this.elements;
  3335. let tmp;
  3336. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3337. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3338. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3339. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3340. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3341. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3342. return this;
  3343. }
  3344. setPosition( x, y, z ) {
  3345. const te = this.elements;
  3346. if ( x.isVector3 ) {
  3347. te[ 12 ] = x.x;
  3348. te[ 13 ] = x.y;
  3349. te[ 14 ] = x.z;
  3350. } else {
  3351. te[ 12 ] = x;
  3352. te[ 13 ] = y;
  3353. te[ 14 ] = z;
  3354. }
  3355. return this;
  3356. }
  3357. invert() {
  3358. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3359. const te = this.elements,
  3360. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3361. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3362. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3363. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3364. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3365. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3366. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3367. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3368. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3369. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3370. const detInv = 1 / det;
  3371. te[ 0 ] = t11 * detInv;
  3372. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3373. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3374. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3375. te[ 4 ] = t12 * detInv;
  3376. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3377. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3378. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3379. te[ 8 ] = t13 * detInv;
  3380. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3381. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3382. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3383. te[ 12 ] = t14 * detInv;
  3384. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3385. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3386. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3387. return this;
  3388. }
  3389. scale( v ) {
  3390. const te = this.elements;
  3391. const x = v.x, y = v.y, z = v.z;
  3392. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3393. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3394. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3395. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3396. return this;
  3397. }
  3398. getMaxScaleOnAxis() {
  3399. const te = this.elements;
  3400. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3401. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3402. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3403. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3404. }
  3405. makeTranslation( x, y, z ) {
  3406. this.set(
  3407. 1, 0, 0, x,
  3408. 0, 1, 0, y,
  3409. 0, 0, 1, z,
  3410. 0, 0, 0, 1
  3411. );
  3412. return this;
  3413. }
  3414. makeRotationX( theta ) {
  3415. const c = Math.cos( theta ), s = Math.sin( theta );
  3416. this.set(
  3417. 1, 0, 0, 0,
  3418. 0, c, - s, 0,
  3419. 0, s, c, 0,
  3420. 0, 0, 0, 1
  3421. );
  3422. return this;
  3423. }
  3424. makeRotationY( theta ) {
  3425. const c = Math.cos( theta ), s = Math.sin( theta );
  3426. this.set(
  3427. c, 0, s, 0,
  3428. 0, 1, 0, 0,
  3429. - s, 0, c, 0,
  3430. 0, 0, 0, 1
  3431. );
  3432. return this;
  3433. }
  3434. makeRotationZ( theta ) {
  3435. const c = Math.cos( theta ), s = Math.sin( theta );
  3436. this.set(
  3437. c, - s, 0, 0,
  3438. s, c, 0, 0,
  3439. 0, 0, 1, 0,
  3440. 0, 0, 0, 1
  3441. );
  3442. return this;
  3443. }
  3444. makeRotationAxis( axis, angle ) {
  3445. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3446. const c = Math.cos( angle );
  3447. const s = Math.sin( angle );
  3448. const t = 1 - c;
  3449. const x = axis.x, y = axis.y, z = axis.z;
  3450. const tx = t * x, ty = t * y;
  3451. this.set(
  3452. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3453. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3454. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3455. 0, 0, 0, 1
  3456. );
  3457. return this;
  3458. }
  3459. makeScale( x, y, z ) {
  3460. this.set(
  3461. x, 0, 0, 0,
  3462. 0, y, 0, 0,
  3463. 0, 0, z, 0,
  3464. 0, 0, 0, 1
  3465. );
  3466. return this;
  3467. }
  3468. makeShear( x, y, z ) {
  3469. this.set(
  3470. 1, y, z, 0,
  3471. x, 1, z, 0,
  3472. x, y, 1, 0,
  3473. 0, 0, 0, 1
  3474. );
  3475. return this;
  3476. }
  3477. compose( position, quaternion, scale ) {
  3478. const te = this.elements;
  3479. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3480. const x2 = x + x, y2 = y + y, z2 = z + z;
  3481. const xx = x * x2, xy = x * y2, xz = x * z2;
  3482. const yy = y * y2, yz = y * z2, zz = z * z2;
  3483. const wx = w * x2, wy = w * y2, wz = w * z2;
  3484. const sx = scale.x, sy = scale.y, sz = scale.z;
  3485. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3486. te[ 1 ] = ( xy + wz ) * sx;
  3487. te[ 2 ] = ( xz - wy ) * sx;
  3488. te[ 3 ] = 0;
  3489. te[ 4 ] = ( xy - wz ) * sy;
  3490. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3491. te[ 6 ] = ( yz + wx ) * sy;
  3492. te[ 7 ] = 0;
  3493. te[ 8 ] = ( xz + wy ) * sz;
  3494. te[ 9 ] = ( yz - wx ) * sz;
  3495. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3496. te[ 11 ] = 0;
  3497. te[ 12 ] = position.x;
  3498. te[ 13 ] = position.y;
  3499. te[ 14 ] = position.z;
  3500. te[ 15 ] = 1;
  3501. return this;
  3502. }
  3503. decompose( position, quaternion, scale ) {
  3504. const te = this.elements;
  3505. let sx = _v1$1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3506. const sy = _v1$1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3507. const sz = _v1$1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3508. // if determine is negative, we need to invert one scale
  3509. const det = this.determinant();
  3510. if ( det < 0 ) sx = - sx;
  3511. position.x = te[ 12 ];
  3512. position.y = te[ 13 ];
  3513. position.z = te[ 14 ];
  3514. // scale the rotation part
  3515. _m1.copy( this );
  3516. const invSX = 1 / sx;
  3517. const invSY = 1 / sy;
  3518. const invSZ = 1 / sz;
  3519. _m1.elements[ 0 ] *= invSX;
  3520. _m1.elements[ 1 ] *= invSX;
  3521. _m1.elements[ 2 ] *= invSX;
  3522. _m1.elements[ 4 ] *= invSY;
  3523. _m1.elements[ 5 ] *= invSY;
  3524. _m1.elements[ 6 ] *= invSY;
  3525. _m1.elements[ 8 ] *= invSZ;
  3526. _m1.elements[ 9 ] *= invSZ;
  3527. _m1.elements[ 10 ] *= invSZ;
  3528. quaternion.setFromRotationMatrix( _m1 );
  3529. scale.x = sx;
  3530. scale.y = sy;
  3531. scale.z = sz;
  3532. return this;
  3533. }
  3534. makePerspective( left, right, top, bottom, near, far ) {
  3535. if ( far === undefined ) {
  3536. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  3537. }
  3538. const te = this.elements;
  3539. const x = 2 * near / ( right - left );
  3540. const y = 2 * near / ( top - bottom );
  3541. const a = ( right + left ) / ( right - left );
  3542. const b = ( top + bottom ) / ( top - bottom );
  3543. const c = - ( far + near ) / ( far - near );
  3544. const d = - 2 * far * near / ( far - near );
  3545. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3546. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3547. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3548. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3549. return this;
  3550. }
  3551. makeOrthographic( left, right, top, bottom, near, far ) {
  3552. const te = this.elements;
  3553. const w = 1.0 / ( right - left );
  3554. const h = 1.0 / ( top - bottom );
  3555. const p = 1.0 / ( far - near );
  3556. const x = ( right + left ) * w;
  3557. const y = ( top + bottom ) * h;
  3558. const z = ( far + near ) * p;
  3559. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3560. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3561. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3562. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3563. return this;
  3564. }
  3565. equals( matrix ) {
  3566. const te = this.elements;
  3567. const me = matrix.elements;
  3568. for ( let i = 0; i < 16; i ++ ) {
  3569. if ( te[ i ] !== me[ i ] ) return false;
  3570. }
  3571. return true;
  3572. }
  3573. fromArray( array, offset = 0 ) {
  3574. for ( let i = 0; i < 16; i ++ ) {
  3575. this.elements[ i ] = array[ i + offset ];
  3576. }
  3577. return this;
  3578. }
  3579. toArray( array = [], offset = 0 ) {
  3580. const te = this.elements;
  3581. array[ offset ] = te[ 0 ];
  3582. array[ offset + 1 ] = te[ 1 ];
  3583. array[ offset + 2 ] = te[ 2 ];
  3584. array[ offset + 3 ] = te[ 3 ];
  3585. array[ offset + 4 ] = te[ 4 ];
  3586. array[ offset + 5 ] = te[ 5 ];
  3587. array[ offset + 6 ] = te[ 6 ];
  3588. array[ offset + 7 ] = te[ 7 ];
  3589. array[ offset + 8 ] = te[ 8 ];
  3590. array[ offset + 9 ] = te[ 9 ];
  3591. array[ offset + 10 ] = te[ 10 ];
  3592. array[ offset + 11 ] = te[ 11 ];
  3593. array[ offset + 12 ] = te[ 12 ];
  3594. array[ offset + 13 ] = te[ 13 ];
  3595. array[ offset + 14 ] = te[ 14 ];
  3596. array[ offset + 15 ] = te[ 15 ];
  3597. return array;
  3598. }
  3599. }
  3600. const _v1$1 = /*@__PURE__*/ new Vector3();
  3601. const _m1 = /*@__PURE__*/ new Matrix4();
  3602. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3603. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3604. const _x = /*@__PURE__*/ new Vector3();
  3605. const _y = /*@__PURE__*/ new Vector3();
  3606. const _z = /*@__PURE__*/ new Vector3();
  3607. class Euler {
  3608. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  3609. Object.defineProperty( this, 'isEuler', { value: true } );
  3610. this._x = x;
  3611. this._y = y;
  3612. this._z = z;
  3613. this._order = order;
  3614. }
  3615. get x() {
  3616. return this._x;
  3617. }
  3618. set x( value ) {
  3619. this._x = value;
  3620. this._onChangeCallback();
  3621. }
  3622. get y() {
  3623. return this._y;
  3624. }
  3625. set y( value ) {
  3626. this._y = value;
  3627. this._onChangeCallback();
  3628. }
  3629. get z() {
  3630. return this._z;
  3631. }
  3632. set z( value ) {
  3633. this._z = value;
  3634. this._onChangeCallback();
  3635. }
  3636. get order() {
  3637. return this._order;
  3638. }
  3639. set order( value ) {
  3640. this._order = value;
  3641. this._onChangeCallback();
  3642. }
  3643. set( x, y, z, order ) {
  3644. this._x = x;
  3645. this._y = y;
  3646. this._z = z;
  3647. this._order = order || this._order;
  3648. this._onChangeCallback();
  3649. return this;
  3650. }
  3651. clone() {
  3652. return new this.constructor( this._x, this._y, this._z, this._order );
  3653. }
  3654. copy( euler ) {
  3655. this._x = euler._x;
  3656. this._y = euler._y;
  3657. this._z = euler._z;
  3658. this._order = euler._order;
  3659. this._onChangeCallback();
  3660. return this;
  3661. }
  3662. setFromRotationMatrix( m, order, update ) {
  3663. const clamp = MathUtils.clamp;
  3664. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3665. const te = m.elements;
  3666. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  3667. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  3668. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3669. order = order || this._order;
  3670. switch ( order ) {
  3671. case 'XYZ':
  3672. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  3673. if ( Math.abs( m13 ) < 0.9999999 ) {
  3674. this._x = Math.atan2( - m23, m33 );
  3675. this._z = Math.atan2( - m12, m11 );
  3676. } else {
  3677. this._x = Math.atan2( m32, m22 );
  3678. this._z = 0;
  3679. }
  3680. break;
  3681. case 'YXZ':
  3682. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  3683. if ( Math.abs( m23 ) < 0.9999999 ) {
  3684. this._y = Math.atan2( m13, m33 );
  3685. this._z = Math.atan2( m21, m22 );
  3686. } else {
  3687. this._y = Math.atan2( - m31, m11 );
  3688. this._z = 0;
  3689. }
  3690. break;
  3691. case 'ZXY':
  3692. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  3693. if ( Math.abs( m32 ) < 0.9999999 ) {
  3694. this._y = Math.atan2( - m31, m33 );
  3695. this._z = Math.atan2( - m12, m22 );
  3696. } else {
  3697. this._y = 0;
  3698. this._z = Math.atan2( m21, m11 );
  3699. }
  3700. break;
  3701. case 'ZYX':
  3702. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  3703. if ( Math.abs( m31 ) < 0.9999999 ) {
  3704. this._x = Math.atan2( m32, m33 );
  3705. this._z = Math.atan2( m21, m11 );
  3706. } else {
  3707. this._x = 0;
  3708. this._z = Math.atan2( - m12, m22 );
  3709. }
  3710. break;
  3711. case 'YZX':
  3712. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  3713. if ( Math.abs( m21 ) < 0.9999999 ) {
  3714. this._x = Math.atan2( - m23, m22 );
  3715. this._y = Math.atan2( - m31, m11 );
  3716. } else {
  3717. this._x = 0;
  3718. this._y = Math.atan2( m13, m33 );
  3719. }
  3720. break;
  3721. case 'XZY':
  3722. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  3723. if ( Math.abs( m12 ) < 0.9999999 ) {
  3724. this._x = Math.atan2( m32, m22 );
  3725. this._y = Math.atan2( m13, m11 );
  3726. } else {
  3727. this._x = Math.atan2( - m23, m33 );
  3728. this._y = 0;
  3729. }
  3730. break;
  3731. default:
  3732. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  3733. }
  3734. this._order = order;
  3735. if ( update !== false ) this._onChangeCallback();
  3736. return this;
  3737. }
  3738. setFromQuaternion( q, order, update ) {
  3739. _matrix.makeRotationFromQuaternion( q );
  3740. return this.setFromRotationMatrix( _matrix, order, update );
  3741. }
  3742. setFromVector3( v, order ) {
  3743. return this.set( v.x, v.y, v.z, order || this._order );
  3744. }
  3745. reorder( newOrder ) {
  3746. // WARNING: this discards revolution information -bhouston
  3747. _quaternion$1.setFromEuler( this );
  3748. return this.setFromQuaternion( _quaternion$1, newOrder );
  3749. }
  3750. equals( euler ) {
  3751. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  3752. }
  3753. fromArray( array ) {
  3754. this._x = array[ 0 ];
  3755. this._y = array[ 1 ];
  3756. this._z = array[ 2 ];
  3757. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  3758. this._onChangeCallback();
  3759. return this;
  3760. }
  3761. toArray( array = [], offset = 0 ) {
  3762. array[ offset ] = this._x;
  3763. array[ offset + 1 ] = this._y;
  3764. array[ offset + 2 ] = this._z;
  3765. array[ offset + 3 ] = this._order;
  3766. return array;
  3767. }
  3768. toVector3( optionalResult ) {
  3769. if ( optionalResult ) {
  3770. return optionalResult.set( this._x, this._y, this._z );
  3771. } else {
  3772. return new Vector3( this._x, this._y, this._z );
  3773. }
  3774. }
  3775. _onChange( callback ) {
  3776. this._onChangeCallback = callback;
  3777. return this;
  3778. }
  3779. _onChangeCallback() {}
  3780. }
  3781. Euler.DefaultOrder = 'XYZ';
  3782. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  3783. const _matrix = /*@__PURE__*/ new Matrix4();
  3784. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  3785. class Layers {
  3786. constructor() {
  3787. this.mask = 1 | 0;
  3788. }
  3789. set( channel ) {
  3790. this.mask = 1 << channel | 0;
  3791. }
  3792. enable( channel ) {
  3793. this.mask |= 1 << channel | 0;
  3794. }
  3795. enableAll() {
  3796. this.mask = 0xffffffff | 0;
  3797. }
  3798. toggle( channel ) {
  3799. this.mask ^= 1 << channel | 0;
  3800. }
  3801. disable( channel ) {
  3802. this.mask &= ~ ( 1 << channel | 0 );
  3803. }
  3804. disableAll() {
  3805. this.mask = 0;
  3806. }
  3807. test( layers ) {
  3808. return ( this.mask & layers.mask ) !== 0;
  3809. }
  3810. }
  3811. let _object3DId = 0;
  3812. const _v1$2 = new Vector3();
  3813. const _q1 = new Quaternion();
  3814. const _m1$1 = new Matrix4();
  3815. const _target = new Vector3();
  3816. const _position = new Vector3();
  3817. const _scale = new Vector3();
  3818. const _quaternion$2 = new Quaternion();
  3819. const _xAxis = new Vector3( 1, 0, 0 );
  3820. const _yAxis = new Vector3( 0, 1, 0 );
  3821. const _zAxis = new Vector3( 0, 0, 1 );
  3822. const _addedEvent = { type: 'added' };
  3823. const _removedEvent = { type: 'removed' };
  3824. function Object3D() {
  3825. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  3826. this.uuid = MathUtils.generateUUID();
  3827. this.name = '';
  3828. this.type = 'Object3D';
  3829. this.parent = null;
  3830. this.children = [];
  3831. this.up = Object3D.DefaultUp.clone();
  3832. const position = new Vector3();
  3833. const rotation = new Euler();
  3834. const quaternion = new Quaternion();
  3835. const scale = new Vector3( 1, 1, 1 );
  3836. function onRotationChange() {
  3837. quaternion.setFromEuler( rotation, false );
  3838. }
  3839. function onQuaternionChange() {
  3840. rotation.setFromQuaternion( quaternion, undefined, false );
  3841. }
  3842. rotation._onChange( onRotationChange );
  3843. quaternion._onChange( onQuaternionChange );
  3844. Object.defineProperties( this, {
  3845. position: {
  3846. configurable: true,
  3847. enumerable: true,
  3848. value: position
  3849. },
  3850. rotation: {
  3851. configurable: true,
  3852. enumerable: true,
  3853. value: rotation
  3854. },
  3855. quaternion: {
  3856. configurable: true,
  3857. enumerable: true,
  3858. value: quaternion
  3859. },
  3860. scale: {
  3861. configurable: true,
  3862. enumerable: true,
  3863. value: scale
  3864. },
  3865. modelViewMatrix: {
  3866. value: new Matrix4()
  3867. },
  3868. normalMatrix: {
  3869. value: new Matrix3()
  3870. }
  3871. } );
  3872. this.matrix = new Matrix4();
  3873. this.matrixWorld = new Matrix4();
  3874. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  3875. this.matrixWorldNeedsUpdate = false;
  3876. this.layers = new Layers();
  3877. this.visible = true;
  3878. this.castShadow = false;
  3879. this.receiveShadow = false;
  3880. this.frustumCulled = true;
  3881. this.renderOrder = 0;
  3882. this.animations = [];
  3883. this.userData = {};
  3884. }
  3885. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  3886. Object3D.DefaultMatrixAutoUpdate = true;
  3887. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  3888. constructor: Object3D,
  3889. isObject3D: true,
  3890. onBeforeRender: function () {},
  3891. onAfterRender: function () {},
  3892. applyMatrix4: function ( matrix ) {
  3893. if ( this.matrixAutoUpdate ) this.updateMatrix();
  3894. this.matrix.premultiply( matrix );
  3895. this.matrix.decompose( this.position, this.quaternion, this.scale );
  3896. },
  3897. applyQuaternion: function ( q ) {
  3898. this.quaternion.premultiply( q );
  3899. return this;
  3900. },
  3901. setRotationFromAxisAngle: function ( axis, angle ) {
  3902. // assumes axis is normalized
  3903. this.quaternion.setFromAxisAngle( axis, angle );
  3904. },
  3905. setRotationFromEuler: function ( euler ) {
  3906. this.quaternion.setFromEuler( euler, true );
  3907. },
  3908. setRotationFromMatrix: function ( m ) {
  3909. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3910. this.quaternion.setFromRotationMatrix( m );
  3911. },
  3912. setRotationFromQuaternion: function ( q ) {
  3913. // assumes q is normalized
  3914. this.quaternion.copy( q );
  3915. },
  3916. rotateOnAxis: function ( axis, angle ) {
  3917. // rotate object on axis in object space
  3918. // axis is assumed to be normalized
  3919. _q1.setFromAxisAngle( axis, angle );
  3920. this.quaternion.multiply( _q1 );
  3921. return this;
  3922. },
  3923. rotateOnWorldAxis: function ( axis, angle ) {
  3924. // rotate object on axis in world space
  3925. // axis is assumed to be normalized
  3926. // method assumes no rotated parent
  3927. _q1.setFromAxisAngle( axis, angle );
  3928. this.quaternion.premultiply( _q1 );
  3929. return this;
  3930. },
  3931. rotateX: function ( angle ) {
  3932. return this.rotateOnAxis( _xAxis, angle );
  3933. },
  3934. rotateY: function ( angle ) {
  3935. return this.rotateOnAxis( _yAxis, angle );
  3936. },
  3937. rotateZ: function ( angle ) {
  3938. return this.rotateOnAxis( _zAxis, angle );
  3939. },
  3940. translateOnAxis: function ( axis, distance ) {
  3941. // translate object by distance along axis in object space
  3942. // axis is assumed to be normalized
  3943. _v1$2.copy( axis ).applyQuaternion( this.quaternion );
  3944. this.position.add( _v1$2.multiplyScalar( distance ) );
  3945. return this;
  3946. },
  3947. translateX: function ( distance ) {
  3948. return this.translateOnAxis( _xAxis, distance );
  3949. },
  3950. translateY: function ( distance ) {
  3951. return this.translateOnAxis( _yAxis, distance );
  3952. },
  3953. translateZ: function ( distance ) {
  3954. return this.translateOnAxis( _zAxis, distance );
  3955. },
  3956. localToWorld: function ( vector ) {
  3957. return vector.applyMatrix4( this.matrixWorld );
  3958. },
  3959. worldToLocal: function ( vector ) {
  3960. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  3961. },
  3962. lookAt: function ( x, y, z ) {
  3963. // This method does not support objects having non-uniformly-scaled parent(s)
  3964. if ( x.isVector3 ) {
  3965. _target.copy( x );
  3966. } else {
  3967. _target.set( x, y, z );
  3968. }
  3969. const parent = this.parent;
  3970. this.updateWorldMatrix( true, false );
  3971. _position.setFromMatrixPosition( this.matrixWorld );
  3972. if ( this.isCamera || this.isLight ) {
  3973. _m1$1.lookAt( _position, _target, this.up );
  3974. } else {
  3975. _m1$1.lookAt( _target, _position, this.up );
  3976. }
  3977. this.quaternion.setFromRotationMatrix( _m1$1 );
  3978. if ( parent ) {
  3979. _m1$1.extractRotation( parent.matrixWorld );
  3980. _q1.setFromRotationMatrix( _m1$1 );
  3981. this.quaternion.premultiply( _q1.invert() );
  3982. }
  3983. },
  3984. add: function ( object ) {
  3985. if ( arguments.length > 1 ) {
  3986. for ( let i = 0; i < arguments.length; i ++ ) {
  3987. this.add( arguments[ i ] );
  3988. }
  3989. return this;
  3990. }
  3991. if ( object === this ) {
  3992. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  3993. return this;
  3994. }
  3995. if ( object && object.isObject3D ) {
  3996. if ( object.parent !== null ) {
  3997. object.parent.remove( object );
  3998. }
  3999. object.parent = this;
  4000. this.children.push( object );
  4001. object.dispatchEvent( _addedEvent );
  4002. } else {
  4003. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4004. }
  4005. return this;
  4006. },
  4007. remove: function ( object ) {
  4008. if ( arguments.length > 1 ) {
  4009. for ( let i = 0; i < arguments.length; i ++ ) {
  4010. this.remove( arguments[ i ] );
  4011. }
  4012. return this;
  4013. }
  4014. const index = this.children.indexOf( object );
  4015. if ( index !== - 1 ) {
  4016. object.parent = null;
  4017. this.children.splice( index, 1 );
  4018. object.dispatchEvent( _removedEvent );
  4019. }
  4020. return this;
  4021. },
  4022. clear: function () {
  4023. for ( let i = 0; i < this.children.length; i ++ ) {
  4024. const object = this.children[ i ];
  4025. object.parent = null;
  4026. object.dispatchEvent( _removedEvent );
  4027. }
  4028. this.children.length = 0;
  4029. return this;
  4030. },
  4031. attach: function ( object ) {
  4032. // adds object as a child of this, while maintaining the object's world transform
  4033. this.updateWorldMatrix( true, false );
  4034. _m1$1.copy( this.matrixWorld ).invert();
  4035. if ( object.parent !== null ) {
  4036. object.parent.updateWorldMatrix( true, false );
  4037. _m1$1.multiply( object.parent.matrixWorld );
  4038. }
  4039. object.applyMatrix4( _m1$1 );
  4040. object.updateWorldMatrix( false, false );
  4041. this.add( object );
  4042. return this;
  4043. },
  4044. getObjectById: function ( id ) {
  4045. return this.getObjectByProperty( 'id', id );
  4046. },
  4047. getObjectByName: function ( name ) {
  4048. return this.getObjectByProperty( 'name', name );
  4049. },
  4050. getObjectByProperty: function ( name, value ) {
  4051. if ( this[ name ] === value ) return this;
  4052. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4053. const child = this.children[ i ];
  4054. const object = child.getObjectByProperty( name, value );
  4055. if ( object !== undefined ) {
  4056. return object;
  4057. }
  4058. }
  4059. return undefined;
  4060. },
  4061. getWorldPosition: function ( target ) {
  4062. if ( target === undefined ) {
  4063. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  4064. target = new Vector3();
  4065. }
  4066. this.updateWorldMatrix( true, false );
  4067. return target.setFromMatrixPosition( this.matrixWorld );
  4068. },
  4069. getWorldQuaternion: function ( target ) {
  4070. if ( target === undefined ) {
  4071. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  4072. target = new Quaternion();
  4073. }
  4074. this.updateWorldMatrix( true, false );
  4075. this.matrixWorld.decompose( _position, target, _scale );
  4076. return target;
  4077. },
  4078. getWorldScale: function ( target ) {
  4079. if ( target === undefined ) {
  4080. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  4081. target = new Vector3();
  4082. }
  4083. this.updateWorldMatrix( true, false );
  4084. this.matrixWorld.decompose( _position, _quaternion$2, target );
  4085. return target;
  4086. },
  4087. getWorldDirection: function ( target ) {
  4088. if ( target === undefined ) {
  4089. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  4090. target = new Vector3();
  4091. }
  4092. this.updateWorldMatrix( true, false );
  4093. const e = this.matrixWorld.elements;
  4094. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4095. },
  4096. raycast: function () {},
  4097. traverse: function ( callback ) {
  4098. callback( this );
  4099. const children = this.children;
  4100. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4101. children[ i ].traverse( callback );
  4102. }
  4103. },
  4104. traverseVisible: function ( callback ) {
  4105. if ( this.visible === false ) return;
  4106. callback( this );
  4107. const children = this.children;
  4108. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4109. children[ i ].traverseVisible( callback );
  4110. }
  4111. },
  4112. traverseAncestors: function ( callback ) {
  4113. const parent = this.parent;
  4114. if ( parent !== null ) {
  4115. callback( parent );
  4116. parent.traverseAncestors( callback );
  4117. }
  4118. },
  4119. updateMatrix: function () {
  4120. this.matrix.compose( this.position, this.quaternion, this.scale );
  4121. this.matrixWorldNeedsUpdate = true;
  4122. },
  4123. updateMatrixWorld: function ( force ) {
  4124. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4125. if ( this.matrixWorldNeedsUpdate || force ) {
  4126. if ( this.parent === null ) {
  4127. this.matrixWorld.copy( this.matrix );
  4128. } else {
  4129. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4130. }
  4131. this.matrixWorldNeedsUpdate = false;
  4132. force = true;
  4133. }
  4134. // update children
  4135. const children = this.children;
  4136. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4137. children[ i ].updateMatrixWorld( force );
  4138. }
  4139. },
  4140. updateWorldMatrix: function ( updateParents, updateChildren ) {
  4141. const parent = this.parent;
  4142. if ( updateParents === true && parent !== null ) {
  4143. parent.updateWorldMatrix( true, false );
  4144. }
  4145. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4146. if ( this.parent === null ) {
  4147. this.matrixWorld.copy( this.matrix );
  4148. } else {
  4149. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4150. }
  4151. // update children
  4152. if ( updateChildren === true ) {
  4153. const children = this.children;
  4154. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4155. children[ i ].updateWorldMatrix( false, true );
  4156. }
  4157. }
  4158. },
  4159. toJSON: function ( meta ) {
  4160. // meta is a string when called from JSON.stringify
  4161. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4162. const output = {};
  4163. // meta is a hash used to collect geometries, materials.
  4164. // not providing it implies that this is the root object
  4165. // being serialized.
  4166. if ( isRootObject ) {
  4167. // initialize meta obj
  4168. meta = {
  4169. geometries: {},
  4170. materials: {},
  4171. textures: {},
  4172. images: {},
  4173. shapes: {},
  4174. skeletons: {},
  4175. animations: {}
  4176. };
  4177. output.metadata = {
  4178. version: 4.5,
  4179. type: 'Object',
  4180. generator: 'Object3D.toJSON'
  4181. };
  4182. }
  4183. // standard Object3D serialization
  4184. const object = {};
  4185. object.uuid = this.uuid;
  4186. object.type = this.type;
  4187. if ( this.name !== '' ) object.name = this.name;
  4188. if ( this.castShadow === true ) object.castShadow = true;
  4189. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4190. if ( this.visible === false ) object.visible = false;
  4191. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4192. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4193. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4194. object.layers = this.layers.mask;
  4195. object.matrix = this.matrix.toArray();
  4196. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4197. // object specific properties
  4198. if ( this.isInstancedMesh ) {
  4199. object.type = 'InstancedMesh';
  4200. object.count = this.count;
  4201. object.instanceMatrix = this.instanceMatrix.toJSON();
  4202. }
  4203. //
  4204. function serialize( library, element ) {
  4205. if ( library[ element.uuid ] === undefined ) {
  4206. library[ element.uuid ] = element.toJSON( meta );
  4207. }
  4208. return element.uuid;
  4209. }
  4210. if ( this.isMesh || this.isLine || this.isPoints ) {
  4211. object.geometry = serialize( meta.geometries, this.geometry );
  4212. const parameters = this.geometry.parameters;
  4213. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4214. const shapes = parameters.shapes;
  4215. if ( Array.isArray( shapes ) ) {
  4216. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4217. const shape = shapes[ i ];
  4218. serialize( meta.shapes, shape );
  4219. }
  4220. } else {
  4221. serialize( meta.shapes, shapes );
  4222. }
  4223. }
  4224. }
  4225. if ( this.isSkinnedMesh ) {
  4226. object.bindMode = this.bindMode;
  4227. object.bindMatrix = this.bindMatrix.toArray();
  4228. if ( this.skeleton !== undefined ) {
  4229. serialize( meta.skeletons, this.skeleton );
  4230. object.skeleton = this.skeleton.uuid;
  4231. }
  4232. }
  4233. if ( this.material !== undefined ) {
  4234. if ( Array.isArray( this.material ) ) {
  4235. const uuids = [];
  4236. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4237. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4238. }
  4239. object.material = uuids;
  4240. } else {
  4241. object.material = serialize( meta.materials, this.material );
  4242. }
  4243. }
  4244. //
  4245. if ( this.children.length > 0 ) {
  4246. object.children = [];
  4247. for ( let i = 0; i < this.children.length; i ++ ) {
  4248. object.children.push( this.children[ i ].toJSON( meta ).object );
  4249. }
  4250. }
  4251. //
  4252. if ( this.animations.length > 0 ) {
  4253. object.animations = [];
  4254. for ( let i = 0; i < this.animations.length; i ++ ) {
  4255. const animation = this.animations[ i ];
  4256. object.animations.push( serialize( meta.animations, animation ) );
  4257. }
  4258. }
  4259. if ( isRootObject ) {
  4260. const geometries = extractFromCache( meta.geometries );
  4261. const materials = extractFromCache( meta.materials );
  4262. const textures = extractFromCache( meta.textures );
  4263. const images = extractFromCache( meta.images );
  4264. const shapes = extractFromCache( meta.shapes );
  4265. const skeletons = extractFromCache( meta.skeletons );
  4266. const animations = extractFromCache( meta.animations );
  4267. if ( geometries.length > 0 ) output.geometries = geometries;
  4268. if ( materials.length > 0 ) output.materials = materials;
  4269. if ( textures.length > 0 ) output.textures = textures;
  4270. if ( images.length > 0 ) output.images = images;
  4271. if ( shapes.length > 0 ) output.shapes = shapes;
  4272. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4273. if ( animations.length > 0 ) output.animations = animations;
  4274. }
  4275. output.object = object;
  4276. return output;
  4277. // extract data from the cache hash
  4278. // remove metadata on each item
  4279. // and return as array
  4280. function extractFromCache( cache ) {
  4281. const values = [];
  4282. for ( const key in cache ) {
  4283. const data = cache[ key ];
  4284. delete data.metadata;
  4285. values.push( data );
  4286. }
  4287. return values;
  4288. }
  4289. },
  4290. clone: function ( recursive ) {
  4291. return new this.constructor().copy( this, recursive );
  4292. },
  4293. copy: function ( source, recursive = true ) {
  4294. this.name = source.name;
  4295. this.up.copy( source.up );
  4296. this.position.copy( source.position );
  4297. this.rotation.order = source.rotation.order;
  4298. this.quaternion.copy( source.quaternion );
  4299. this.scale.copy( source.scale );
  4300. this.matrix.copy( source.matrix );
  4301. this.matrixWorld.copy( source.matrixWorld );
  4302. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4303. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4304. this.layers.mask = source.layers.mask;
  4305. this.visible = source.visible;
  4306. this.castShadow = source.castShadow;
  4307. this.receiveShadow = source.receiveShadow;
  4308. this.frustumCulled = source.frustumCulled;
  4309. this.renderOrder = source.renderOrder;
  4310. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4311. if ( recursive === true ) {
  4312. for ( let i = 0; i < source.children.length; i ++ ) {
  4313. const child = source.children[ i ];
  4314. this.add( child.clone() );
  4315. }
  4316. }
  4317. return this;
  4318. }
  4319. } );
  4320. const _vector1 = /*@__PURE__*/ new Vector3();
  4321. const _vector2 = /*@__PURE__*/ new Vector3();
  4322. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  4323. class Plane {
  4324. constructor( normal, constant ) {
  4325. Object.defineProperty( this, 'isPlane', { value: true } );
  4326. // normal is assumed to be normalized
  4327. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  4328. this.constant = ( constant !== undefined ) ? constant : 0;
  4329. }
  4330. set( normal, constant ) {
  4331. this.normal.copy( normal );
  4332. this.constant = constant;
  4333. return this;
  4334. }
  4335. setComponents( x, y, z, w ) {
  4336. this.normal.set( x, y, z );
  4337. this.constant = w;
  4338. return this;
  4339. }
  4340. setFromNormalAndCoplanarPoint( normal, point ) {
  4341. this.normal.copy( normal );
  4342. this.constant = - point.dot( this.normal );
  4343. return this;
  4344. }
  4345. setFromCoplanarPoints( a, b, c ) {
  4346. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  4347. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4348. this.setFromNormalAndCoplanarPoint( normal, a );
  4349. return this;
  4350. }
  4351. clone() {
  4352. return new this.constructor().copy( this );
  4353. }
  4354. copy( plane ) {
  4355. this.normal.copy( plane.normal );
  4356. this.constant = plane.constant;
  4357. return this;
  4358. }
  4359. normalize() {
  4360. // Note: will lead to a divide by zero if the plane is invalid.
  4361. const inverseNormalLength = 1.0 / this.normal.length();
  4362. this.normal.multiplyScalar( inverseNormalLength );
  4363. this.constant *= inverseNormalLength;
  4364. return this;
  4365. }
  4366. negate() {
  4367. this.constant *= - 1;
  4368. this.normal.negate();
  4369. return this;
  4370. }
  4371. distanceToPoint( point ) {
  4372. return this.normal.dot( point ) + this.constant;
  4373. }
  4374. distanceToSphere( sphere ) {
  4375. return this.distanceToPoint( sphere.center ) - sphere.radius;
  4376. }
  4377. projectPoint( point, target ) {
  4378. if ( target === undefined ) {
  4379. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  4380. target = new Vector3();
  4381. }
  4382. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  4383. }
  4384. intersectLine( line, target ) {
  4385. if ( target === undefined ) {
  4386. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  4387. target = new Vector3();
  4388. }
  4389. const direction = line.delta( _vector1 );
  4390. const denominator = this.normal.dot( direction );
  4391. if ( denominator === 0 ) {
  4392. // line is coplanar, return origin
  4393. if ( this.distanceToPoint( line.start ) === 0 ) {
  4394. return target.copy( line.start );
  4395. }
  4396. // Unsure if this is the correct method to handle this case.
  4397. return undefined;
  4398. }
  4399. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  4400. if ( t < 0 || t > 1 ) {
  4401. return undefined;
  4402. }
  4403. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  4404. }
  4405. intersectsLine( line ) {
  4406. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4407. const startSign = this.distanceToPoint( line.start );
  4408. const endSign = this.distanceToPoint( line.end );
  4409. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  4410. }
  4411. intersectsBox( box ) {
  4412. return box.intersectsPlane( this );
  4413. }
  4414. intersectsSphere( sphere ) {
  4415. return sphere.intersectsPlane( this );
  4416. }
  4417. coplanarPoint( target ) {
  4418. if ( target === undefined ) {
  4419. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  4420. target = new Vector3();
  4421. }
  4422. return target.copy( this.normal ).multiplyScalar( - this.constant );
  4423. }
  4424. applyMatrix4( matrix, optionalNormalMatrix ) {
  4425. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  4426. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  4427. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  4428. this.constant = - referencePoint.dot( normal );
  4429. return this;
  4430. }
  4431. translate( offset ) {
  4432. this.constant -= offset.dot( this.normal );
  4433. return this;
  4434. }
  4435. equals( plane ) {
  4436. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4437. }
  4438. }
  4439. const _v0$1 = /*@__PURE__*/ new Vector3();
  4440. const _v1$3 = /*@__PURE__*/ new Vector3();
  4441. const _v2$1 = /*@__PURE__*/ new Vector3();
  4442. const _v3 = /*@__PURE__*/ new Vector3();
  4443. const _vab = /*@__PURE__*/ new Vector3();
  4444. const _vac = /*@__PURE__*/ new Vector3();
  4445. const _vbc = /*@__PURE__*/ new Vector3();
  4446. const _vap = /*@__PURE__*/ new Vector3();
  4447. const _vbp = /*@__PURE__*/ new Vector3();
  4448. const _vcp = /*@__PURE__*/ new Vector3();
  4449. class Triangle {
  4450. constructor( a, b, c ) {
  4451. this.a = ( a !== undefined ) ? a : new Vector3();
  4452. this.b = ( b !== undefined ) ? b : new Vector3();
  4453. this.c = ( c !== undefined ) ? c : new Vector3();
  4454. }
  4455. static getNormal( a, b, c, target ) {
  4456. if ( target === undefined ) {
  4457. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  4458. target = new Vector3();
  4459. }
  4460. target.subVectors( c, b );
  4461. _v0$1.subVectors( a, b );
  4462. target.cross( _v0$1 );
  4463. const targetLengthSq = target.lengthSq();
  4464. if ( targetLengthSq > 0 ) {
  4465. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4466. }
  4467. return target.set( 0, 0, 0 );
  4468. }
  4469. // static/instance method to calculate barycentric coordinates
  4470. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4471. static getBarycoord( point, a, b, c, target ) {
  4472. _v0$1.subVectors( c, a );
  4473. _v1$3.subVectors( b, a );
  4474. _v2$1.subVectors( point, a );
  4475. const dot00 = _v0$1.dot( _v0$1 );
  4476. const dot01 = _v0$1.dot( _v1$3 );
  4477. const dot02 = _v0$1.dot( _v2$1 );
  4478. const dot11 = _v1$3.dot( _v1$3 );
  4479. const dot12 = _v1$3.dot( _v2$1 );
  4480. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4481. if ( target === undefined ) {
  4482. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  4483. target = new Vector3();
  4484. }
  4485. // collinear or singular triangle
  4486. if ( denom === 0 ) {
  4487. // arbitrary location outside of triangle?
  4488. // not sure if this is the best idea, maybe should be returning undefined
  4489. return target.set( - 2, - 1, - 1 );
  4490. }
  4491. const invDenom = 1 / denom;
  4492. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4493. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4494. // barycentric coordinates must always sum to 1
  4495. return target.set( 1 - u - v, v, u );
  4496. }
  4497. static containsPoint( point, a, b, c ) {
  4498. this.getBarycoord( point, a, b, c, _v3 );
  4499. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  4500. }
  4501. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4502. this.getBarycoord( point, p1, p2, p3, _v3 );
  4503. target.set( 0, 0 );
  4504. target.addScaledVector( uv1, _v3.x );
  4505. target.addScaledVector( uv2, _v3.y );
  4506. target.addScaledVector( uv3, _v3.z );
  4507. return target;
  4508. }
  4509. static isFrontFacing( a, b, c, direction ) {
  4510. _v0$1.subVectors( c, b );
  4511. _v1$3.subVectors( a, b );
  4512. // strictly front facing
  4513. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4514. }
  4515. set( a, b, c ) {
  4516. this.a.copy( a );
  4517. this.b.copy( b );
  4518. this.c.copy( c );
  4519. return this;
  4520. }
  4521. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4522. this.a.copy( points[ i0 ] );
  4523. this.b.copy( points[ i1 ] );
  4524. this.c.copy( points[ i2 ] );
  4525. return this;
  4526. }
  4527. clone() {
  4528. return new this.constructor().copy( this );
  4529. }
  4530. copy( triangle ) {
  4531. this.a.copy( triangle.a );
  4532. this.b.copy( triangle.b );
  4533. this.c.copy( triangle.c );
  4534. return this;
  4535. }
  4536. getArea() {
  4537. _v0$1.subVectors( this.c, this.b );
  4538. _v1$3.subVectors( this.a, this.b );
  4539. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4540. }
  4541. getMidpoint( target ) {
  4542. if ( target === undefined ) {
  4543. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  4544. target = new Vector3();
  4545. }
  4546. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4547. }
  4548. getNormal( target ) {
  4549. return Triangle.getNormal( this.a, this.b, this.c, target );
  4550. }
  4551. getPlane( target ) {
  4552. if ( target === undefined ) {
  4553. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  4554. target = new Plane();
  4555. }
  4556. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4557. }
  4558. getBarycoord( point, target ) {
  4559. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4560. }
  4561. getUV( point, uv1, uv2, uv3, target ) {
  4562. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4563. }
  4564. containsPoint( point ) {
  4565. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4566. }
  4567. isFrontFacing( direction ) {
  4568. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4569. }
  4570. intersectsBox( box ) {
  4571. return box.intersectsTriangle( this );
  4572. }
  4573. closestPointToPoint( p, target ) {
  4574. if ( target === undefined ) {
  4575. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  4576. target = new Vector3();
  4577. }
  4578. const a = this.a, b = this.b, c = this.c;
  4579. let v, w;
  4580. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4581. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4582. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4583. // basically, we're distinguishing which of the voronoi regions of the triangle
  4584. // the point lies in with the minimum amount of redundant computation.
  4585. _vab.subVectors( b, a );
  4586. _vac.subVectors( c, a );
  4587. _vap.subVectors( p, a );
  4588. const d1 = _vab.dot( _vap );
  4589. const d2 = _vac.dot( _vap );
  4590. if ( d1 <= 0 && d2 <= 0 ) {
  4591. // vertex region of A; barycentric coords (1, 0, 0)
  4592. return target.copy( a );
  4593. }
  4594. _vbp.subVectors( p, b );
  4595. const d3 = _vab.dot( _vbp );
  4596. const d4 = _vac.dot( _vbp );
  4597. if ( d3 >= 0 && d4 <= d3 ) {
  4598. // vertex region of B; barycentric coords (0, 1, 0)
  4599. return target.copy( b );
  4600. }
  4601. const vc = d1 * d4 - d3 * d2;
  4602. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4603. v = d1 / ( d1 - d3 );
  4604. // edge region of AB; barycentric coords (1-v, v, 0)
  4605. return target.copy( a ).addScaledVector( _vab, v );
  4606. }
  4607. _vcp.subVectors( p, c );
  4608. const d5 = _vab.dot( _vcp );
  4609. const d6 = _vac.dot( _vcp );
  4610. if ( d6 >= 0 && d5 <= d6 ) {
  4611. // vertex region of C; barycentric coords (0, 0, 1)
  4612. return target.copy( c );
  4613. }
  4614. const vb = d5 * d2 - d1 * d6;
  4615. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4616. w = d2 / ( d2 - d6 );
  4617. // edge region of AC; barycentric coords (1-w, 0, w)
  4618. return target.copy( a ).addScaledVector( _vac, w );
  4619. }
  4620. const va = d3 * d6 - d5 * d4;
  4621. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4622. _vbc.subVectors( c, b );
  4623. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4624. // edge region of BC; barycentric coords (0, 1-w, w)
  4625. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4626. }
  4627. // face region
  4628. const denom = 1 / ( va + vb + vc );
  4629. // u = va * denom
  4630. v = vb * denom;
  4631. w = vc * denom;
  4632. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4633. }
  4634. equals( triangle ) {
  4635. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4636. }
  4637. }
  4638. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  4639. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  4640. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  4641. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  4642. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  4643. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  4644. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  4645. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  4646. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  4647. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  4648. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  4649. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  4650. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  4651. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  4652. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  4653. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  4654. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  4655. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  4656. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  4657. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  4658. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  4659. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  4660. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  4661. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  4662. const _hslA = { h: 0, s: 0, l: 0 };
  4663. const _hslB = { h: 0, s: 0, l: 0 };
  4664. function hue2rgb( p, q, t ) {
  4665. if ( t < 0 ) t += 1;
  4666. if ( t > 1 ) t -= 1;
  4667. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  4668. if ( t < 1 / 2 ) return q;
  4669. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  4670. return p;
  4671. }
  4672. function SRGBToLinear( c ) {
  4673. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  4674. }
  4675. function LinearToSRGB( c ) {
  4676. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  4677. }
  4678. class Color {
  4679. constructor( r, g, b ) {
  4680. Object.defineProperty( this, 'isColor', { value: true } );
  4681. if ( g === undefined && b === undefined ) {
  4682. // r is THREE.Color, hex or string
  4683. return this.set( r );
  4684. }
  4685. return this.setRGB( r, g, b );
  4686. }
  4687. set( value ) {
  4688. if ( value && value.isColor ) {
  4689. this.copy( value );
  4690. } else if ( typeof value === 'number' ) {
  4691. this.setHex( value );
  4692. } else if ( typeof value === 'string' ) {
  4693. this.setStyle( value );
  4694. }
  4695. return this;
  4696. }
  4697. setScalar( scalar ) {
  4698. this.r = scalar;
  4699. this.g = scalar;
  4700. this.b = scalar;
  4701. return this;
  4702. }
  4703. setHex( hex ) {
  4704. hex = Math.floor( hex );
  4705. this.r = ( hex >> 16 & 255 ) / 255;
  4706. this.g = ( hex >> 8 & 255 ) / 255;
  4707. this.b = ( hex & 255 ) / 255;
  4708. return this;
  4709. }
  4710. setRGB( r, g, b ) {
  4711. this.r = r;
  4712. this.g = g;
  4713. this.b = b;
  4714. return this;
  4715. }
  4716. setHSL( h, s, l ) {
  4717. // h,s,l ranges are in 0.0 - 1.0
  4718. h = MathUtils.euclideanModulo( h, 1 );
  4719. s = MathUtils.clamp( s, 0, 1 );
  4720. l = MathUtils.clamp( l, 0, 1 );
  4721. if ( s === 0 ) {
  4722. this.r = this.g = this.b = l;
  4723. } else {
  4724. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  4725. const q = ( 2 * l ) - p;
  4726. this.r = hue2rgb( q, p, h + 1 / 3 );
  4727. this.g = hue2rgb( q, p, h );
  4728. this.b = hue2rgb( q, p, h - 1 / 3 );
  4729. }
  4730. return this;
  4731. }
  4732. setStyle( style ) {
  4733. function handleAlpha( string ) {
  4734. if ( string === undefined ) return;
  4735. if ( parseFloat( string ) < 1 ) {
  4736. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  4737. }
  4738. }
  4739. let m;
  4740. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  4741. // rgb / hsl
  4742. let color;
  4743. const name = m[ 1 ];
  4744. const components = m[ 2 ];
  4745. switch ( name ) {
  4746. case 'rgb':
  4747. case 'rgba':
  4748. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  4749. // rgb(255,0,0) rgba(255,0,0,0.5)
  4750. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  4751. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  4752. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  4753. handleAlpha( color[ 4 ] );
  4754. return this;
  4755. }
  4756. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  4757. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  4758. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  4759. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  4760. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  4761. handleAlpha( color[ 4 ] );
  4762. return this;
  4763. }
  4764. break;
  4765. case 'hsl':
  4766. case 'hsla':
  4767. if ( color = /^(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  4768. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  4769. const h = parseFloat( color[ 1 ] ) / 360;
  4770. const s = parseInt( color[ 2 ], 10 ) / 100;
  4771. const l = parseInt( color[ 3 ], 10 ) / 100;
  4772. handleAlpha( color[ 4 ] );
  4773. return this.setHSL( h, s, l );
  4774. }
  4775. break;
  4776. }
  4777. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  4778. // hex color
  4779. const hex = m[ 1 ];
  4780. const size = hex.length;
  4781. if ( size === 3 ) {
  4782. // #ff0
  4783. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  4784. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  4785. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  4786. return this;
  4787. } else if ( size === 6 ) {
  4788. // #ff0000
  4789. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  4790. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  4791. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  4792. return this;
  4793. }
  4794. }
  4795. if ( style && style.length > 0 ) {
  4796. return this.setColorName( style );
  4797. }
  4798. return this;
  4799. }
  4800. setColorName( style ) {
  4801. // color keywords
  4802. const hex = _colorKeywords[ style ];
  4803. if ( hex !== undefined ) {
  4804. // red
  4805. this.setHex( hex );
  4806. } else {
  4807. // unknown color
  4808. console.warn( 'THREE.Color: Unknown color ' + style );
  4809. }
  4810. return this;
  4811. }
  4812. clone() {
  4813. return new this.constructor( this.r, this.g, this.b );
  4814. }
  4815. copy( color ) {
  4816. this.r = color.r;
  4817. this.g = color.g;
  4818. this.b = color.b;
  4819. return this;
  4820. }
  4821. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  4822. this.r = Math.pow( color.r, gammaFactor );
  4823. this.g = Math.pow( color.g, gammaFactor );
  4824. this.b = Math.pow( color.b, gammaFactor );
  4825. return this;
  4826. }
  4827. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  4828. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  4829. this.r = Math.pow( color.r, safeInverse );
  4830. this.g = Math.pow( color.g, safeInverse );
  4831. this.b = Math.pow( color.b, safeInverse );
  4832. return this;
  4833. }
  4834. convertGammaToLinear( gammaFactor ) {
  4835. this.copyGammaToLinear( this, gammaFactor );
  4836. return this;
  4837. }
  4838. convertLinearToGamma( gammaFactor ) {
  4839. this.copyLinearToGamma( this, gammaFactor );
  4840. return this;
  4841. }
  4842. copySRGBToLinear( color ) {
  4843. this.r = SRGBToLinear( color.r );
  4844. this.g = SRGBToLinear( color.g );
  4845. this.b = SRGBToLinear( color.b );
  4846. return this;
  4847. }
  4848. copyLinearToSRGB( color ) {
  4849. this.r = LinearToSRGB( color.r );
  4850. this.g = LinearToSRGB( color.g );
  4851. this.b = LinearToSRGB( color.b );
  4852. return this;
  4853. }
  4854. convertSRGBToLinear() {
  4855. this.copySRGBToLinear( this );
  4856. return this;
  4857. }
  4858. convertLinearToSRGB() {
  4859. this.copyLinearToSRGB( this );
  4860. return this;
  4861. }
  4862. getHex() {
  4863. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  4864. }
  4865. getHexString() {
  4866. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  4867. }
  4868. getHSL( target ) {
  4869. // h,s,l ranges are in 0.0 - 1.0
  4870. if ( target === undefined ) {
  4871. console.warn( 'THREE.Color: .getHSL() target is now required' );
  4872. target = { h: 0, s: 0, l: 0 };
  4873. }
  4874. const r = this.r, g = this.g, b = this.b;
  4875. const max = Math.max( r, g, b );
  4876. const min = Math.min( r, g, b );
  4877. let hue, saturation;
  4878. const lightness = ( min + max ) / 2.0;
  4879. if ( min === max ) {
  4880. hue = 0;
  4881. saturation = 0;
  4882. } else {
  4883. const delta = max - min;
  4884. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  4885. switch ( max ) {
  4886. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  4887. case g: hue = ( b - r ) / delta + 2; break;
  4888. case b: hue = ( r - g ) / delta + 4; break;
  4889. }
  4890. hue /= 6;
  4891. }
  4892. target.h = hue;
  4893. target.s = saturation;
  4894. target.l = lightness;
  4895. return target;
  4896. }
  4897. getStyle() {
  4898. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  4899. }
  4900. offsetHSL( h, s, l ) {
  4901. this.getHSL( _hslA );
  4902. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  4903. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  4904. return this;
  4905. }
  4906. add( color ) {
  4907. this.r += color.r;
  4908. this.g += color.g;
  4909. this.b += color.b;
  4910. return this;
  4911. }
  4912. addColors( color1, color2 ) {
  4913. this.r = color1.r + color2.r;
  4914. this.g = color1.g + color2.g;
  4915. this.b = color1.b + color2.b;
  4916. return this;
  4917. }
  4918. addScalar( s ) {
  4919. this.r += s;
  4920. this.g += s;
  4921. this.b += s;
  4922. return this;
  4923. }
  4924. sub( color ) {
  4925. this.r = Math.max( 0, this.r - color.r );
  4926. this.g = Math.max( 0, this.g - color.g );
  4927. this.b = Math.max( 0, this.b - color.b );
  4928. return this;
  4929. }
  4930. multiply( color ) {
  4931. this.r *= color.r;
  4932. this.g *= color.g;
  4933. this.b *= color.b;
  4934. return this;
  4935. }
  4936. multiplyScalar( s ) {
  4937. this.r *= s;
  4938. this.g *= s;
  4939. this.b *= s;
  4940. return this;
  4941. }
  4942. lerp( color, alpha ) {
  4943. this.r += ( color.r - this.r ) * alpha;
  4944. this.g += ( color.g - this.g ) * alpha;
  4945. this.b += ( color.b - this.b ) * alpha;
  4946. return this;
  4947. }
  4948. lerpHSL( color, alpha ) {
  4949. this.getHSL( _hslA );
  4950. color.getHSL( _hslB );
  4951. const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
  4952. const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
  4953. const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
  4954. this.setHSL( h, s, l );
  4955. return this;
  4956. }
  4957. equals( c ) {
  4958. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  4959. }
  4960. fromArray( array, offset = 0 ) {
  4961. this.r = array[ offset ];
  4962. this.g = array[ offset + 1 ];
  4963. this.b = array[ offset + 2 ];
  4964. return this;
  4965. }
  4966. toArray( array = [], offset = 0 ) {
  4967. array[ offset ] = this.r;
  4968. array[ offset + 1 ] = this.g;
  4969. array[ offset + 2 ] = this.b;
  4970. return array;
  4971. }
  4972. fromBufferAttribute( attribute, index ) {
  4973. this.r = attribute.getX( index );
  4974. this.g = attribute.getY( index );
  4975. this.b = attribute.getZ( index );
  4976. if ( attribute.normalized === true ) {
  4977. // assuming Uint8Array
  4978. this.r /= 255;
  4979. this.g /= 255;
  4980. this.b /= 255;
  4981. }
  4982. return this;
  4983. }
  4984. toJSON() {
  4985. return this.getHex();
  4986. }
  4987. }
  4988. Color.NAMES = _colorKeywords;
  4989. Color.prototype.r = 1;
  4990. Color.prototype.g = 1;
  4991. Color.prototype.b = 1;
  4992. class Face3 {
  4993. constructor( a, b, c, normal, color, materialIndex = 0 ) {
  4994. this.a = a;
  4995. this.b = b;
  4996. this.c = c;
  4997. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  4998. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  4999. this.color = ( color && color.isColor ) ? color : new Color();
  5000. this.vertexColors = Array.isArray( color ) ? color : [];
  5001. this.materialIndex = materialIndex;
  5002. }
  5003. clone() {
  5004. return new this.constructor().copy( this );
  5005. }
  5006. copy( source ) {
  5007. this.a = source.a;
  5008. this.b = source.b;
  5009. this.c = source.c;
  5010. this.normal.copy( source.normal );
  5011. this.color.copy( source.color );
  5012. this.materialIndex = source.materialIndex;
  5013. for ( let i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5014. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5015. }
  5016. for ( let i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5017. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5018. }
  5019. return this;
  5020. }
  5021. }
  5022. let materialId = 0;
  5023. function Material() {
  5024. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5025. this.uuid = MathUtils.generateUUID();
  5026. this.name = '';
  5027. this.type = 'Material';
  5028. this.fog = true;
  5029. this.blending = NormalBlending;
  5030. this.side = FrontSide;
  5031. this.flatShading = false;
  5032. this.vertexColors = false;
  5033. this.opacity = 1;
  5034. this.transparent = false;
  5035. this.blendSrc = SrcAlphaFactor;
  5036. this.blendDst = OneMinusSrcAlphaFactor;
  5037. this.blendEquation = AddEquation;
  5038. this.blendSrcAlpha = null;
  5039. this.blendDstAlpha = null;
  5040. this.blendEquationAlpha = null;
  5041. this.depthFunc = LessEqualDepth;
  5042. this.depthTest = true;
  5043. this.depthWrite = true;
  5044. this.stencilWriteMask = 0xff;
  5045. this.stencilFunc = AlwaysStencilFunc;
  5046. this.stencilRef = 0;
  5047. this.stencilFuncMask = 0xff;
  5048. this.stencilFail = KeepStencilOp;
  5049. this.stencilZFail = KeepStencilOp;
  5050. this.stencilZPass = KeepStencilOp;
  5051. this.stencilWrite = false;
  5052. this.clippingPlanes = null;
  5053. this.clipIntersection = false;
  5054. this.clipShadows = false;
  5055. this.shadowSide = null;
  5056. this.colorWrite = true;
  5057. this.precision = null; // override the renderer's default precision for this material
  5058. this.polygonOffset = false;
  5059. this.polygonOffsetFactor = 0;
  5060. this.polygonOffsetUnits = 0;
  5061. this.dithering = false;
  5062. this.alphaTest = 0;
  5063. this.premultipliedAlpha = false;
  5064. this.visible = true;
  5065. this.toneMapped = true;
  5066. this.userData = {};
  5067. this.version = 0;
  5068. }
  5069. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  5070. constructor: Material,
  5071. isMaterial: true,
  5072. onBeforeCompile: function ( /* shaderobject, renderer */ ) {},
  5073. customProgramCacheKey: function () {
  5074. return this.onBeforeCompile.toString();
  5075. },
  5076. setValues: function ( values ) {
  5077. if ( values === undefined ) return;
  5078. for ( const key in values ) {
  5079. const newValue = values[ key ];
  5080. if ( newValue === undefined ) {
  5081. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5082. continue;
  5083. }
  5084. // for backward compatability if shading is set in the constructor
  5085. if ( key === 'shading' ) {
  5086. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  5087. this.flatShading = ( newValue === FlatShading$1 ) ? true : false;
  5088. continue;
  5089. }
  5090. const currentValue = this[ key ];
  5091. if ( currentValue === undefined ) {
  5092. //console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5093. continue;
  5094. }
  5095. if ( currentValue && currentValue.isColor ) {
  5096. currentValue.set( newValue );
  5097. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5098. currentValue.copy( newValue );
  5099. } else {
  5100. this[ key ] = newValue;
  5101. }
  5102. }
  5103. },
  5104. toJSON: function ( meta ) {
  5105. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5106. if ( isRoot ) {
  5107. meta = {
  5108. textures: {},
  5109. images: {}
  5110. };
  5111. }
  5112. const data = {
  5113. metadata: {
  5114. version: 4.5,
  5115. type: 'Material',
  5116. generator: 'Material.toJSON'
  5117. }
  5118. };
  5119. // standard Material serialization
  5120. data.uuid = this.uuid;
  5121. data.type = this.type;
  5122. if ( this.name !== '' ) data.name = this.name;
  5123. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5124. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5125. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5126. if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
  5127. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5128. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5129. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5130. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5131. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5132. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5133. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5134. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5135. }
  5136. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5137. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5138. }
  5139. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5140. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5141. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5142. }
  5143. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5144. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5145. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5146. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5147. if ( this.aoMap && this.aoMap.isTexture ) {
  5148. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5149. data.aoMapIntensity = this.aoMapIntensity;
  5150. }
  5151. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5152. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5153. data.bumpScale = this.bumpScale;
  5154. }
  5155. if ( this.normalMap && this.normalMap.isTexture ) {
  5156. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5157. data.normalMapType = this.normalMapType;
  5158. data.normalScale = this.normalScale.toArray();
  5159. }
  5160. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5161. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5162. data.displacementScale = this.displacementScale;
  5163. data.displacementBias = this.displacementBias;
  5164. }
  5165. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5166. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5167. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5168. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5169. if ( this.envMap && this.envMap.isTexture ) {
  5170. data.envMap = this.envMap.toJSON( meta ).uuid;
  5171. data.reflectivity = this.reflectivity; // Scale behind envMap
  5172. data.refractionRatio = this.refractionRatio;
  5173. if ( this.combine !== undefined ) data.combine = this.combine;
  5174. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5175. }
  5176. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5177. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5178. }
  5179. if ( this.size !== undefined ) data.size = this.size;
  5180. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5181. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5182. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5183. if ( this.side !== FrontSide ) data.side = this.side;
  5184. if ( this.vertexColors ) data.vertexColors = true;
  5185. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5186. if ( this.transparent === true ) data.transparent = this.transparent;
  5187. data.depthFunc = this.depthFunc;
  5188. data.depthTest = this.depthTest;
  5189. data.depthWrite = this.depthWrite;
  5190. data.stencilWrite = this.stencilWrite;
  5191. data.stencilWriteMask = this.stencilWriteMask;
  5192. data.stencilFunc = this.stencilFunc;
  5193. data.stencilRef = this.stencilRef;
  5194. data.stencilFuncMask = this.stencilFuncMask;
  5195. data.stencilFail = this.stencilFail;
  5196. data.stencilZFail = this.stencilZFail;
  5197. data.stencilZPass = this.stencilZPass;
  5198. // rotation (SpriteMaterial)
  5199. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  5200. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5201. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5202. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5203. if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5204. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5205. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5206. if ( this.scale !== undefined ) data.scale = this.scale;
  5207. if ( this.dithering === true ) data.dithering = true;
  5208. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5209. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5210. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5211. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5212. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5213. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5214. if ( this.morphTargets === true ) data.morphTargets = true;
  5215. if ( this.morphNormals === true ) data.morphNormals = true;
  5216. if ( this.skinning === true ) data.skinning = true;
  5217. if ( this.visible === false ) data.visible = false;
  5218. if ( this.toneMapped === false ) data.toneMapped = false;
  5219. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5220. // TODO: Copied from Object3D.toJSON
  5221. function extractFromCache( cache ) {
  5222. const values = [];
  5223. for ( const key in cache ) {
  5224. const data = cache[ key ];
  5225. delete data.metadata;
  5226. values.push( data );
  5227. }
  5228. return values;
  5229. }
  5230. if ( isRoot ) {
  5231. const textures = extractFromCache( meta.textures );
  5232. const images = extractFromCache( meta.images );
  5233. if ( textures.length > 0 ) data.textures = textures;
  5234. if ( images.length > 0 ) data.images = images;
  5235. }
  5236. return data;
  5237. },
  5238. clone: function () {
  5239. return new this.constructor().copy( this );
  5240. },
  5241. copy: function ( source ) {
  5242. this.name = source.name;
  5243. this.fog = source.fog;
  5244. this.blending = source.blending;
  5245. this.side = source.side;
  5246. this.flatShading = source.flatShading;
  5247. this.vertexColors = source.vertexColors;
  5248. this.opacity = source.opacity;
  5249. this.transparent = source.transparent;
  5250. this.blendSrc = source.blendSrc;
  5251. this.blendDst = source.blendDst;
  5252. this.blendEquation = source.blendEquation;
  5253. this.blendSrcAlpha = source.blendSrcAlpha;
  5254. this.blendDstAlpha = source.blendDstAlpha;
  5255. this.blendEquationAlpha = source.blendEquationAlpha;
  5256. this.depthFunc = source.depthFunc;
  5257. this.depthTest = source.depthTest;
  5258. this.depthWrite = source.depthWrite;
  5259. this.stencilWriteMask = source.stencilWriteMask;
  5260. this.stencilFunc = source.stencilFunc;
  5261. this.stencilRef = source.stencilRef;
  5262. this.stencilFuncMask = source.stencilFuncMask;
  5263. this.stencilFail = source.stencilFail;
  5264. this.stencilZFail = source.stencilZFail;
  5265. this.stencilZPass = source.stencilZPass;
  5266. this.stencilWrite = source.stencilWrite;
  5267. const srcPlanes = source.clippingPlanes;
  5268. let dstPlanes = null;
  5269. if ( srcPlanes !== null ) {
  5270. const n = srcPlanes.length;
  5271. dstPlanes = new Array( n );
  5272. for ( let i = 0; i !== n; ++ i ) {
  5273. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5274. }
  5275. }
  5276. this.clippingPlanes = dstPlanes;
  5277. this.clipIntersection = source.clipIntersection;
  5278. this.clipShadows = source.clipShadows;
  5279. this.shadowSide = source.shadowSide;
  5280. this.colorWrite = source.colorWrite;
  5281. this.precision = source.precision;
  5282. this.polygonOffset = source.polygonOffset;
  5283. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5284. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5285. this.dithering = source.dithering;
  5286. this.alphaTest = source.alphaTest;
  5287. this.premultipliedAlpha = source.premultipliedAlpha;
  5288. this.visible = source.visible;
  5289. this.toneMapped = source.toneMapped;
  5290. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5291. return this;
  5292. },
  5293. dispose: function () {
  5294. this.dispatchEvent( { type: 'dispose' } );
  5295. }
  5296. } );
  5297. Object.defineProperty( Material.prototype, 'needsUpdate', {
  5298. set: function ( value ) {
  5299. if ( value === true ) this.version ++;
  5300. }
  5301. } );
  5302. /**
  5303. * parameters = {
  5304. * color: <hex>,
  5305. * opacity: <float>,
  5306. * map: new THREE.Texture( <Image> ),
  5307. *
  5308. * lightMap: new THREE.Texture( <Image> ),
  5309. * lightMapIntensity: <float>
  5310. *
  5311. * aoMap: new THREE.Texture( <Image> ),
  5312. * aoMapIntensity: <float>
  5313. *
  5314. * specularMap: new THREE.Texture( <Image> ),
  5315. *
  5316. * alphaMap: new THREE.Texture( <Image> ),
  5317. *
  5318. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5319. * combine: THREE.Multiply,
  5320. * reflectivity: <float>,
  5321. * refractionRatio: <float>,
  5322. *
  5323. * depthTest: <bool>,
  5324. * depthWrite: <bool>,
  5325. *
  5326. * wireframe: <boolean>,
  5327. * wireframeLinewidth: <float>,
  5328. *
  5329. * skinning: <bool>,
  5330. * morphTargets: <bool>
  5331. * }
  5332. */
  5333. function MeshBasicMaterial( parameters ) {
  5334. Material.call( this );
  5335. this.type = 'MeshBasicMaterial';
  5336. this.color = new Color( 0xffffff ); // emissive
  5337. this.map = null;
  5338. this.lightMap = null;
  5339. this.lightMapIntensity = 1.0;
  5340. this.aoMap = null;
  5341. this.aoMapIntensity = 1.0;
  5342. this.specularMap = null;
  5343. this.alphaMap = null;
  5344. this.envMap = null;
  5345. this.combine = MultiplyOperation;
  5346. this.reflectivity = 1;
  5347. this.refractionRatio = 0.98;
  5348. this.wireframe = false;
  5349. this.wireframeLinewidth = 1;
  5350. this.wireframeLinecap = 'round';
  5351. this.wireframeLinejoin = 'round';
  5352. this.skinning = false;
  5353. this.morphTargets = false;
  5354. this.setValues( parameters );
  5355. }
  5356. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  5357. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  5358. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5359. MeshBasicMaterial.prototype.copy = function ( source ) {
  5360. Material.prototype.copy.call( this, source );
  5361. this.color.copy( source.color );
  5362. this.map = source.map;
  5363. this.lightMap = source.lightMap;
  5364. this.lightMapIntensity = source.lightMapIntensity;
  5365. this.aoMap = source.aoMap;
  5366. this.aoMapIntensity = source.aoMapIntensity;
  5367. this.specularMap = source.specularMap;
  5368. this.alphaMap = source.alphaMap;
  5369. this.envMap = source.envMap;
  5370. this.combine = source.combine;
  5371. this.reflectivity = source.reflectivity;
  5372. this.refractionRatio = source.refractionRatio;
  5373. this.wireframe = source.wireframe;
  5374. this.wireframeLinewidth = source.wireframeLinewidth;
  5375. this.wireframeLinecap = source.wireframeLinecap;
  5376. this.wireframeLinejoin = source.wireframeLinejoin;
  5377. this.skinning = source.skinning;
  5378. this.morphTargets = source.morphTargets;
  5379. return this;
  5380. };
  5381. const _vector$3 = new Vector3();
  5382. const _vector2$1 = new Vector2();
  5383. function BufferAttribute( array, itemSize, normalized ) {
  5384. if ( Array.isArray( array ) ) {
  5385. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5386. }
  5387. this.name = '';
  5388. this.array = array;
  5389. this.itemSize = itemSize;
  5390. this.count = array !== undefined ? array.length / itemSize : 0;
  5391. this.normalized = normalized === true;
  5392. this.usage = StaticDrawUsage;
  5393. this.updateRange = { offset: 0, count: - 1 };
  5394. this.version = 0;
  5395. }
  5396. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  5397. set: function ( value ) {
  5398. if ( value === true ) this.version ++;
  5399. }
  5400. } );
  5401. Object.assign( BufferAttribute.prototype, {
  5402. isBufferAttribute: true,
  5403. onUploadCallback: function () {},
  5404. setUsage: function ( value ) {
  5405. this.usage = value;
  5406. return this;
  5407. },
  5408. copy: function ( source ) {
  5409. this.name = source.name;
  5410. this.array = new source.array.constructor( source.array );
  5411. this.itemSize = source.itemSize;
  5412. this.count = source.count;
  5413. this.normalized = source.normalized;
  5414. this.usage = source.usage;
  5415. return this;
  5416. },
  5417. copyAt: function ( index1, attribute, index2 ) {
  5418. index1 *= this.itemSize;
  5419. index2 *= attribute.itemSize;
  5420. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5421. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5422. }
  5423. return this;
  5424. },
  5425. copyArray: function ( array ) {
  5426. this.array.set( array );
  5427. return this;
  5428. },
  5429. copyColorsArray: function ( colors ) {
  5430. const array = this.array;
  5431. let offset = 0;
  5432. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5433. let color = colors[ i ];
  5434. if ( color === undefined ) {
  5435. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5436. color = new Color();
  5437. }
  5438. array[ offset ++ ] = color.r;
  5439. array[ offset ++ ] = color.g;
  5440. array[ offset ++ ] = color.b;
  5441. }
  5442. return this;
  5443. },
  5444. copyVector2sArray: function ( vectors ) {
  5445. const array = this.array;
  5446. let offset = 0;
  5447. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5448. let vector = vectors[ i ];
  5449. if ( vector === undefined ) {
  5450. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5451. vector = new Vector2();
  5452. }
  5453. array[ offset ++ ] = vector.x;
  5454. array[ offset ++ ] = vector.y;
  5455. }
  5456. return this;
  5457. },
  5458. copyVector3sArray: function ( vectors ) {
  5459. const array = this.array;
  5460. let offset = 0;
  5461. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5462. let vector = vectors[ i ];
  5463. if ( vector === undefined ) {
  5464. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5465. vector = new Vector3();
  5466. }
  5467. array[ offset ++ ] = vector.x;
  5468. array[ offset ++ ] = vector.y;
  5469. array[ offset ++ ] = vector.z;
  5470. }
  5471. return this;
  5472. },
  5473. copyVector4sArray: function ( vectors ) {
  5474. const array = this.array;
  5475. let offset = 0;
  5476. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5477. let vector = vectors[ i ];
  5478. if ( vector === undefined ) {
  5479. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5480. vector = new Vector4();
  5481. }
  5482. array[ offset ++ ] = vector.x;
  5483. array[ offset ++ ] = vector.y;
  5484. array[ offset ++ ] = vector.z;
  5485. array[ offset ++ ] = vector.w;
  5486. }
  5487. return this;
  5488. },
  5489. applyMatrix3: function ( m ) {
  5490. if ( this.itemSize === 2 ) {
  5491. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5492. _vector2$1.fromBufferAttribute( this, i );
  5493. _vector2$1.applyMatrix3( m );
  5494. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5495. }
  5496. } else if ( this.itemSize === 3 ) {
  5497. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5498. _vector$3.fromBufferAttribute( this, i );
  5499. _vector$3.applyMatrix3( m );
  5500. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5501. }
  5502. }
  5503. return this;
  5504. },
  5505. applyMatrix4: function ( m ) {
  5506. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5507. _vector$3.x = this.getX( i );
  5508. _vector$3.y = this.getY( i );
  5509. _vector$3.z = this.getZ( i );
  5510. _vector$3.applyMatrix4( m );
  5511. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5512. }
  5513. return this;
  5514. },
  5515. applyNormalMatrix: function ( m ) {
  5516. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5517. _vector$3.x = this.getX( i );
  5518. _vector$3.y = this.getY( i );
  5519. _vector$3.z = this.getZ( i );
  5520. _vector$3.applyNormalMatrix( m );
  5521. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5522. }
  5523. return this;
  5524. },
  5525. transformDirection: function ( m ) {
  5526. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5527. _vector$3.x = this.getX( i );
  5528. _vector$3.y = this.getY( i );
  5529. _vector$3.z = this.getZ( i );
  5530. _vector$3.transformDirection( m );
  5531. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  5532. }
  5533. return this;
  5534. },
  5535. set: function ( value, offset = 0 ) {
  5536. this.array.set( value, offset );
  5537. return this;
  5538. },
  5539. getX: function ( index ) {
  5540. return this.array[ index * this.itemSize ];
  5541. },
  5542. setX: function ( index, x ) {
  5543. this.array[ index * this.itemSize ] = x;
  5544. return this;
  5545. },
  5546. getY: function ( index ) {
  5547. return this.array[ index * this.itemSize + 1 ];
  5548. },
  5549. setY: function ( index, y ) {
  5550. this.array[ index * this.itemSize + 1 ] = y;
  5551. return this;
  5552. },
  5553. getZ: function ( index ) {
  5554. return this.array[ index * this.itemSize + 2 ];
  5555. },
  5556. setZ: function ( index, z ) {
  5557. this.array[ index * this.itemSize + 2 ] = z;
  5558. return this;
  5559. },
  5560. getW: function ( index ) {
  5561. return this.array[ index * this.itemSize + 3 ];
  5562. },
  5563. setW: function ( index, w ) {
  5564. this.array[ index * this.itemSize + 3 ] = w;
  5565. return this;
  5566. },
  5567. setXY: function ( index, x, y ) {
  5568. index *= this.itemSize;
  5569. this.array[ index + 0 ] = x;
  5570. this.array[ index + 1 ] = y;
  5571. return this;
  5572. },
  5573. setXYZ: function ( index, x, y, z ) {
  5574. index *= this.itemSize;
  5575. this.array[ index + 0 ] = x;
  5576. this.array[ index + 1 ] = y;
  5577. this.array[ index + 2 ] = z;
  5578. return this;
  5579. },
  5580. setXYZW: function ( index, x, y, z, w ) {
  5581. index *= this.itemSize;
  5582. this.array[ index + 0 ] = x;
  5583. this.array[ index + 1 ] = y;
  5584. this.array[ index + 2 ] = z;
  5585. this.array[ index + 3 ] = w;
  5586. return this;
  5587. },
  5588. onUpload: function ( callback ) {
  5589. this.onUploadCallback = callback;
  5590. return this;
  5591. },
  5592. clone: function () {
  5593. return new this.constructor( this.array, this.itemSize ).copy( this );
  5594. },
  5595. toJSON: function () {
  5596. return {
  5597. itemSize: this.itemSize,
  5598. type: this.array.constructor.name,
  5599. array: Array.prototype.slice.call( this.array ),
  5600. normalized: this.normalized
  5601. };
  5602. }
  5603. } );
  5604. //
  5605. function Int8BufferAttribute( array, itemSize, normalized ) {
  5606. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  5607. }
  5608. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5609. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  5610. function Uint8BufferAttribute( array, itemSize, normalized ) {
  5611. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  5612. }
  5613. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5614. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  5615. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  5616. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  5617. }
  5618. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5619. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  5620. function Int16BufferAttribute( array, itemSize, normalized ) {
  5621. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  5622. }
  5623. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5624. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  5625. function Uint16BufferAttribute( array, itemSize, normalized ) {
  5626. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  5627. }
  5628. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5629. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  5630. function Int32BufferAttribute( array, itemSize, normalized ) {
  5631. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  5632. }
  5633. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5634. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  5635. function Uint32BufferAttribute( array, itemSize, normalized ) {
  5636. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  5637. }
  5638. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5639. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  5640. function Float16BufferAttribute( array, itemSize, normalized ) {
  5641. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  5642. }
  5643. Float16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5644. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  5645. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5646. function Float32BufferAttribute( array, itemSize, normalized ) {
  5647. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  5648. }
  5649. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5650. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  5651. function Float64BufferAttribute( array, itemSize, normalized ) {
  5652. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  5653. }
  5654. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  5655. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  5656. class DirectGeometry {
  5657. constructor() {
  5658. this.vertices = [];
  5659. this.normals = [];
  5660. this.colors = [];
  5661. this.uvs = [];
  5662. this.uvs2 = [];
  5663. this.groups = [];
  5664. this.morphTargets = {};
  5665. this.skinWeights = [];
  5666. this.skinIndices = [];
  5667. // this.lineDistances = [];
  5668. this.boundingBox = null;
  5669. this.boundingSphere = null;
  5670. // update flags
  5671. this.verticesNeedUpdate = false;
  5672. this.normalsNeedUpdate = false;
  5673. this.colorsNeedUpdate = false;
  5674. this.uvsNeedUpdate = false;
  5675. this.groupsNeedUpdate = false;
  5676. }
  5677. computeGroups( geometry ) {
  5678. const groups = [];
  5679. let group, i;
  5680. let materialIndex = undefined;
  5681. const faces = geometry.faces;
  5682. for ( i = 0; i < faces.length; i ++ ) {
  5683. const face = faces[ i ];
  5684. // materials
  5685. if ( face.materialIndex !== materialIndex ) {
  5686. materialIndex = face.materialIndex;
  5687. if ( group !== undefined ) {
  5688. group.count = ( i * 3 ) - group.start;
  5689. groups.push( group );
  5690. }
  5691. group = {
  5692. start: i * 3,
  5693. materialIndex: materialIndex
  5694. };
  5695. }
  5696. }
  5697. if ( group !== undefined ) {
  5698. group.count = ( i * 3 ) - group.start;
  5699. groups.push( group );
  5700. }
  5701. this.groups = groups;
  5702. }
  5703. fromGeometry( geometry ) {
  5704. const faces = geometry.faces;
  5705. const vertices = geometry.vertices;
  5706. const faceVertexUvs = geometry.faceVertexUvs;
  5707. const hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  5708. const hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  5709. // morphs
  5710. const morphTargets = geometry.morphTargets;
  5711. const morphTargetsLength = morphTargets.length;
  5712. let morphTargetsPosition;
  5713. if ( morphTargetsLength > 0 ) {
  5714. morphTargetsPosition = [];
  5715. for ( let i = 0; i < morphTargetsLength; i ++ ) {
  5716. morphTargetsPosition[ i ] = {
  5717. name: morphTargets[ i ].name,
  5718. data: []
  5719. };
  5720. }
  5721. this.morphTargets.position = morphTargetsPosition;
  5722. }
  5723. const morphNormals = geometry.morphNormals;
  5724. const morphNormalsLength = morphNormals.length;
  5725. let morphTargetsNormal;
  5726. if ( morphNormalsLength > 0 ) {
  5727. morphTargetsNormal = [];
  5728. for ( let i = 0; i < morphNormalsLength; i ++ ) {
  5729. morphTargetsNormal[ i ] = {
  5730. name: morphNormals[ i ].name,
  5731. data: []
  5732. };
  5733. }
  5734. this.morphTargets.normal = morphTargetsNormal;
  5735. }
  5736. // skins
  5737. const skinIndices = geometry.skinIndices;
  5738. const skinWeights = geometry.skinWeights;
  5739. const hasSkinIndices = skinIndices.length === vertices.length;
  5740. const hasSkinWeights = skinWeights.length === vertices.length;
  5741. //
  5742. if ( vertices.length > 0 && faces.length === 0 ) {
  5743. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  5744. }
  5745. for ( let i = 0; i < faces.length; i ++ ) {
  5746. const face = faces[ i ];
  5747. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  5748. const vertexNormals = face.vertexNormals;
  5749. if ( vertexNormals.length === 3 ) {
  5750. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  5751. } else {
  5752. const normal = face.normal;
  5753. this.normals.push( normal, normal, normal );
  5754. }
  5755. const vertexColors = face.vertexColors;
  5756. if ( vertexColors.length === 3 ) {
  5757. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  5758. } else {
  5759. const color = face.color;
  5760. this.colors.push( color, color, color );
  5761. }
  5762. if ( hasFaceVertexUv === true ) {
  5763. const vertexUvs = faceVertexUvs[ 0 ][ i ];
  5764. if ( vertexUvs !== undefined ) {
  5765. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  5766. } else {
  5767. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  5768. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  5769. }
  5770. }
  5771. if ( hasFaceVertexUv2 === true ) {
  5772. const vertexUvs = faceVertexUvs[ 1 ][ i ];
  5773. if ( vertexUvs !== undefined ) {
  5774. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  5775. } else {
  5776. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  5777. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  5778. }
  5779. }
  5780. // morphs
  5781. for ( let j = 0; j < morphTargetsLength; j ++ ) {
  5782. const morphTarget = morphTargets[ j ].vertices;
  5783. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  5784. }
  5785. for ( let j = 0; j < morphNormalsLength; j ++ ) {
  5786. const morphNormal = morphNormals[ j ].vertexNormals[ i ];
  5787. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  5788. }
  5789. // skins
  5790. if ( hasSkinIndices ) {
  5791. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  5792. }
  5793. if ( hasSkinWeights ) {
  5794. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  5795. }
  5796. }
  5797. this.computeGroups( geometry );
  5798. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  5799. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  5800. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  5801. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  5802. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  5803. if ( geometry.boundingSphere !== null ) {
  5804. this.boundingSphere = geometry.boundingSphere.clone();
  5805. }
  5806. if ( geometry.boundingBox !== null ) {
  5807. this.boundingBox = geometry.boundingBox.clone();
  5808. }
  5809. return this;
  5810. }
  5811. }
  5812. function arrayMax( array ) {
  5813. if ( array.length === 0 ) return - Infinity;
  5814. let max = array[ 0 ];
  5815. for ( let i = 1, l = array.length; i < l; ++ i ) {
  5816. if ( array[ i ] > max ) max = array[ i ];
  5817. }
  5818. return max;
  5819. }
  5820. const TYPED_ARRAYS = {
  5821. Int8Array: Int8Array,
  5822. Uint8Array: Uint8Array,
  5823. // Workaround for IE11 pre KB2929437. See #11440
  5824. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  5825. Int16Array: Int16Array,
  5826. Uint16Array: Uint16Array,
  5827. Int32Array: Int32Array,
  5828. Uint32Array: Uint32Array,
  5829. Float32Array: Float32Array,
  5830. Float64Array: Float64Array
  5831. };
  5832. function getTypedArray( type, buffer ) {
  5833. return new TYPED_ARRAYS[ type ]( buffer );
  5834. }
  5835. let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  5836. const _m1$2 = new Matrix4();
  5837. const _obj = new Object3D();
  5838. const _offset = new Vector3();
  5839. const _box$2 = new Box3();
  5840. const _boxMorphTargets = new Box3();
  5841. const _vector$4 = new Vector3();
  5842. function BufferGeometry() {
  5843. Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
  5844. this.uuid = MathUtils.generateUUID();
  5845. this.name = '';
  5846. this.type = 'BufferGeometry';
  5847. this.index = null;
  5848. this.attributes = {};
  5849. this.morphAttributes = {};
  5850. this.morphTargetsRelative = false;
  5851. this.groups = [];
  5852. this.boundingBox = null;
  5853. this.boundingSphere = null;
  5854. this.drawRange = { start: 0, count: Infinity };
  5855. this.userData = {};
  5856. }
  5857. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  5858. constructor: BufferGeometry,
  5859. isBufferGeometry: true,
  5860. getIndex: function () {
  5861. return this.index;
  5862. },
  5863. setIndex: function ( index ) {
  5864. if ( Array.isArray( index ) ) {
  5865. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5866. } else {
  5867. this.index = index;
  5868. }
  5869. return this;
  5870. },
  5871. getAttribute: function ( name ) {
  5872. return this.attributes[ name ];
  5873. },
  5874. setAttribute: function ( name, attribute ) {
  5875. this.attributes[ name ] = attribute;
  5876. return this;
  5877. },
  5878. deleteAttribute: function ( name ) {
  5879. delete this.attributes[ name ];
  5880. return this;
  5881. },
  5882. hasAttribute: function ( name ) {
  5883. return this.attributes[ name ] !== undefined;
  5884. },
  5885. addGroup: function ( start, count, materialIndex = 0 ) {
  5886. this.groups.push( {
  5887. start: start,
  5888. count: count,
  5889. materialIndex: materialIndex
  5890. } );
  5891. },
  5892. clearGroups: function () {
  5893. this.groups = [];
  5894. },
  5895. setDrawRange: function ( start, count ) {
  5896. this.drawRange.start = start;
  5897. this.drawRange.count = count;
  5898. },
  5899. applyMatrix4: function ( matrix ) {
  5900. const position = this.attributes.position;
  5901. if ( position !== undefined ) {
  5902. position.applyMatrix4( matrix );
  5903. position.needsUpdate = true;
  5904. }
  5905. const normal = this.attributes.normal;
  5906. if ( normal !== undefined ) {
  5907. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5908. normal.applyNormalMatrix( normalMatrix );
  5909. normal.needsUpdate = true;
  5910. }
  5911. const tangent = this.attributes.tangent;
  5912. if ( tangent !== undefined ) {
  5913. tangent.transformDirection( matrix );
  5914. tangent.needsUpdate = true;
  5915. }
  5916. if ( this.boundingBox !== null ) {
  5917. this.computeBoundingBox();
  5918. }
  5919. if ( this.boundingSphere !== null ) {
  5920. this.computeBoundingSphere();
  5921. }
  5922. return this;
  5923. },
  5924. rotateX: function ( angle ) {
  5925. // rotate geometry around world x-axis
  5926. _m1$2.makeRotationX( angle );
  5927. this.applyMatrix4( _m1$2 );
  5928. return this;
  5929. },
  5930. rotateY: function ( angle ) {
  5931. // rotate geometry around world y-axis
  5932. _m1$2.makeRotationY( angle );
  5933. this.applyMatrix4( _m1$2 );
  5934. return this;
  5935. },
  5936. rotateZ: function ( angle ) {
  5937. // rotate geometry around world z-axis
  5938. _m1$2.makeRotationZ( angle );
  5939. this.applyMatrix4( _m1$2 );
  5940. return this;
  5941. },
  5942. translate: function ( x, y, z ) {
  5943. // translate geometry
  5944. _m1$2.makeTranslation( x, y, z );
  5945. this.applyMatrix4( _m1$2 );
  5946. return this;
  5947. },
  5948. scale: function ( x, y, z ) {
  5949. // scale geometry
  5950. _m1$2.makeScale( x, y, z );
  5951. this.applyMatrix4( _m1$2 );
  5952. return this;
  5953. },
  5954. lookAt: function ( vector ) {
  5955. _obj.lookAt( vector );
  5956. _obj.updateMatrix();
  5957. this.applyMatrix4( _obj.matrix );
  5958. return this;
  5959. },
  5960. center: function () {
  5961. this.computeBoundingBox();
  5962. this.boundingBox.getCenter( _offset ).negate();
  5963. this.translate( _offset.x, _offset.y, _offset.z );
  5964. return this;
  5965. },
  5966. setFromObject: function ( object ) {
  5967. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  5968. const geometry = object.geometry;
  5969. if ( object.isPoints || object.isLine ) {
  5970. const positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  5971. const colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  5972. this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  5973. this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  5974. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  5975. const lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  5976. this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  5977. }
  5978. if ( geometry.boundingSphere !== null ) {
  5979. this.boundingSphere = geometry.boundingSphere.clone();
  5980. }
  5981. if ( geometry.boundingBox !== null ) {
  5982. this.boundingBox = geometry.boundingBox.clone();
  5983. }
  5984. } else if ( object.isMesh ) {
  5985. if ( geometry && geometry.isGeometry ) {
  5986. this.fromGeometry( geometry );
  5987. }
  5988. }
  5989. return this;
  5990. },
  5991. setFromPoints: function ( points ) {
  5992. const position = [];
  5993. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5994. const point = points[ i ];
  5995. position.push( point.x, point.y, point.z || 0 );
  5996. }
  5997. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5998. return this;
  5999. },
  6000. updateFromObject: function ( object ) {
  6001. let geometry = object.geometry;
  6002. if ( object.isMesh ) {
  6003. let direct = geometry.__directGeometry;
  6004. if ( geometry.elementsNeedUpdate === true ) {
  6005. direct = undefined;
  6006. geometry.elementsNeedUpdate = false;
  6007. }
  6008. if ( direct === undefined ) {
  6009. return this.fromGeometry( geometry );
  6010. }
  6011. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6012. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6013. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6014. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6015. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6016. geometry.verticesNeedUpdate = false;
  6017. geometry.normalsNeedUpdate = false;
  6018. geometry.colorsNeedUpdate = false;
  6019. geometry.uvsNeedUpdate = false;
  6020. geometry.groupsNeedUpdate = false;
  6021. geometry = direct;
  6022. }
  6023. if ( geometry.verticesNeedUpdate === true ) {
  6024. const attribute = this.attributes.position;
  6025. if ( attribute !== undefined ) {
  6026. attribute.copyVector3sArray( geometry.vertices );
  6027. attribute.needsUpdate = true;
  6028. }
  6029. geometry.verticesNeedUpdate = false;
  6030. }
  6031. if ( geometry.normalsNeedUpdate === true ) {
  6032. const attribute = this.attributes.normal;
  6033. if ( attribute !== undefined ) {
  6034. attribute.copyVector3sArray( geometry.normals );
  6035. attribute.needsUpdate = true;
  6036. }
  6037. geometry.normalsNeedUpdate = false;
  6038. }
  6039. if ( geometry.colorsNeedUpdate === true ) {
  6040. const attribute = this.attributes.color;
  6041. if ( attribute !== undefined ) {
  6042. attribute.copyColorsArray( geometry.colors );
  6043. attribute.needsUpdate = true;
  6044. }
  6045. geometry.colorsNeedUpdate = false;
  6046. }
  6047. if ( geometry.uvsNeedUpdate ) {
  6048. const attribute = this.attributes.uv;
  6049. if ( attribute !== undefined ) {
  6050. attribute.copyVector2sArray( geometry.uvs );
  6051. attribute.needsUpdate = true;
  6052. }
  6053. geometry.uvsNeedUpdate = false;
  6054. }
  6055. if ( geometry.lineDistancesNeedUpdate ) {
  6056. const attribute = this.attributes.lineDistance;
  6057. if ( attribute !== undefined ) {
  6058. attribute.copyArray( geometry.lineDistances );
  6059. attribute.needsUpdate = true;
  6060. }
  6061. geometry.lineDistancesNeedUpdate = false;
  6062. }
  6063. if ( geometry.groupsNeedUpdate ) {
  6064. geometry.computeGroups( object.geometry );
  6065. this.groups = geometry.groups;
  6066. geometry.groupsNeedUpdate = false;
  6067. }
  6068. return this;
  6069. },
  6070. fromGeometry: function ( geometry ) {
  6071. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  6072. return this.fromDirectGeometry( geometry.__directGeometry );
  6073. },
  6074. fromDirectGeometry: function ( geometry ) {
  6075. const positions = new Float32Array( geometry.vertices.length * 3 );
  6076. this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6077. if ( geometry.normals.length > 0 ) {
  6078. const normals = new Float32Array( geometry.normals.length * 3 );
  6079. this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6080. }
  6081. if ( geometry.colors.length > 0 ) {
  6082. const colors = new Float32Array( geometry.colors.length * 3 );
  6083. this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6084. }
  6085. if ( geometry.uvs.length > 0 ) {
  6086. const uvs = new Float32Array( geometry.uvs.length * 2 );
  6087. this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6088. }
  6089. if ( geometry.uvs2.length > 0 ) {
  6090. const uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6091. this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6092. }
  6093. // groups
  6094. this.groups = geometry.groups;
  6095. // morphs
  6096. for ( const name in geometry.morphTargets ) {
  6097. const array = [];
  6098. const morphTargets = geometry.morphTargets[ name ];
  6099. for ( let i = 0, l = morphTargets.length; i < l; i ++ ) {
  6100. const morphTarget = morphTargets[ i ];
  6101. const attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  6102. attribute.name = morphTarget.name;
  6103. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  6104. }
  6105. this.morphAttributes[ name ] = array;
  6106. }
  6107. // skinning
  6108. if ( geometry.skinIndices.length > 0 ) {
  6109. const skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  6110. this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6111. }
  6112. if ( geometry.skinWeights.length > 0 ) {
  6113. const skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  6114. this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6115. }
  6116. //
  6117. if ( geometry.boundingSphere !== null ) {
  6118. this.boundingSphere = geometry.boundingSphere.clone();
  6119. }
  6120. if ( geometry.boundingBox !== null ) {
  6121. this.boundingBox = geometry.boundingBox.clone();
  6122. }
  6123. return this;
  6124. },
  6125. computeBoundingBox: function () {
  6126. if ( this.boundingBox === null ) {
  6127. this.boundingBox = new Box3();
  6128. }
  6129. const position = this.attributes.position;
  6130. const morphAttributesPosition = this.morphAttributes.position;
  6131. if ( position && position.isGLBufferAttribute ) {
  6132. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6133. this.boundingBox.set(
  6134. new Vector3( - Infinity, - Infinity, - Infinity ),
  6135. new Vector3( + Infinity, + Infinity, + Infinity )
  6136. );
  6137. return;
  6138. }
  6139. if ( position !== undefined ) {
  6140. this.boundingBox.setFromBufferAttribute( position );
  6141. // process morph attributes if present
  6142. if ( morphAttributesPosition ) {
  6143. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6144. const morphAttribute = morphAttributesPosition[ i ];
  6145. _box$2.setFromBufferAttribute( morphAttribute );
  6146. if ( this.morphTargetsRelative ) {
  6147. _vector$4.addVectors( this.boundingBox.min, _box$2.min );
  6148. this.boundingBox.expandByPoint( _vector$4 );
  6149. _vector$4.addVectors( this.boundingBox.max, _box$2.max );
  6150. this.boundingBox.expandByPoint( _vector$4 );
  6151. } else {
  6152. this.boundingBox.expandByPoint( _box$2.min );
  6153. this.boundingBox.expandByPoint( _box$2.max );
  6154. }
  6155. }
  6156. }
  6157. } else {
  6158. this.boundingBox.makeEmpty();
  6159. }
  6160. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6161. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6162. }
  6163. },
  6164. computeBoundingSphere: function () {
  6165. if ( this.boundingSphere === null ) {
  6166. this.boundingSphere = new Sphere();
  6167. }
  6168. const position = this.attributes.position;
  6169. const morphAttributesPosition = this.morphAttributes.position;
  6170. if ( position && position.isGLBufferAttribute ) {
  6171. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6172. this.boundingSphere.set( new Vector3(), Infinity );
  6173. return;
  6174. }
  6175. if ( position ) {
  6176. // first, find the center of the bounding sphere
  6177. const center = this.boundingSphere.center;
  6178. _box$2.setFromBufferAttribute( position );
  6179. // process morph attributes if present
  6180. if ( morphAttributesPosition ) {
  6181. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6182. const morphAttribute = morphAttributesPosition[ i ];
  6183. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6184. if ( this.morphTargetsRelative ) {
  6185. _vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
  6186. _box$2.expandByPoint( _vector$4 );
  6187. _vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
  6188. _box$2.expandByPoint( _vector$4 );
  6189. } else {
  6190. _box$2.expandByPoint( _boxMorphTargets.min );
  6191. _box$2.expandByPoint( _boxMorphTargets.max );
  6192. }
  6193. }
  6194. }
  6195. _box$2.getCenter( center );
  6196. // second, try to find a boundingSphere with a radius smaller than the
  6197. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6198. let maxRadiusSq = 0;
  6199. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6200. _vector$4.fromBufferAttribute( position, i );
  6201. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6202. }
  6203. // process morph attributes if present
  6204. if ( morphAttributesPosition ) {
  6205. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6206. const morphAttribute = morphAttributesPosition[ i ];
  6207. const morphTargetsRelative = this.morphTargetsRelative;
  6208. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6209. _vector$4.fromBufferAttribute( morphAttribute, j );
  6210. if ( morphTargetsRelative ) {
  6211. _offset.fromBufferAttribute( position, j );
  6212. _vector$4.add( _offset );
  6213. }
  6214. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6215. }
  6216. }
  6217. }
  6218. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6219. if ( isNaN( this.boundingSphere.radius ) ) {
  6220. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6221. }
  6222. }
  6223. },
  6224. computeFaceNormals: function () {
  6225. // backwards compatibility
  6226. },
  6227. computeVertexNormals: function () {
  6228. const index = this.index;
  6229. const positionAttribute = this.getAttribute( 'position' );
  6230. if ( positionAttribute !== undefined ) {
  6231. let normalAttribute = this.getAttribute( 'normal' );
  6232. if ( normalAttribute === undefined ) {
  6233. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6234. this.setAttribute( 'normal', normalAttribute );
  6235. } else {
  6236. // reset existing normals to zero
  6237. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6238. normalAttribute.setXYZ( i, 0, 0, 0 );
  6239. }
  6240. }
  6241. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6242. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6243. const cb = new Vector3(), ab = new Vector3();
  6244. // indexed elements
  6245. if ( index ) {
  6246. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6247. const vA = index.getX( i + 0 );
  6248. const vB = index.getX( i + 1 );
  6249. const vC = index.getX( i + 2 );
  6250. pA.fromBufferAttribute( positionAttribute, vA );
  6251. pB.fromBufferAttribute( positionAttribute, vB );
  6252. pC.fromBufferAttribute( positionAttribute, vC );
  6253. cb.subVectors( pC, pB );
  6254. ab.subVectors( pA, pB );
  6255. cb.cross( ab );
  6256. nA.fromBufferAttribute( normalAttribute, vA );
  6257. nB.fromBufferAttribute( normalAttribute, vB );
  6258. nC.fromBufferAttribute( normalAttribute, vC );
  6259. nA.add( cb );
  6260. nB.add( cb );
  6261. nC.add( cb );
  6262. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6263. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6264. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6265. }
  6266. } else {
  6267. // non-indexed elements (unconnected triangle soup)
  6268. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6269. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6270. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6271. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6272. cb.subVectors( pC, pB );
  6273. ab.subVectors( pA, pB );
  6274. cb.cross( ab );
  6275. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6276. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6277. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6278. }
  6279. }
  6280. this.normalizeNormals();
  6281. normalAttribute.needsUpdate = true;
  6282. }
  6283. },
  6284. merge: function ( geometry, offset ) {
  6285. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  6286. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6287. return;
  6288. }
  6289. if ( offset === undefined ) {
  6290. offset = 0;
  6291. console.warn(
  6292. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  6293. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  6294. );
  6295. }
  6296. const attributes = this.attributes;
  6297. for ( const key in attributes ) {
  6298. if ( geometry.attributes[ key ] === undefined ) continue;
  6299. const attribute1 = attributes[ key ];
  6300. const attributeArray1 = attribute1.array;
  6301. const attribute2 = geometry.attributes[ key ];
  6302. const attributeArray2 = attribute2.array;
  6303. const attributeOffset = attribute2.itemSize * offset;
  6304. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  6305. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  6306. attributeArray1[ j ] = attributeArray2[ i ];
  6307. }
  6308. }
  6309. return this;
  6310. },
  6311. normalizeNormals: function () {
  6312. const normals = this.attributes.normal;
  6313. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6314. _vector$4.fromBufferAttribute( normals, i );
  6315. _vector$4.normalize();
  6316. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  6317. }
  6318. },
  6319. toNonIndexed: function () {
  6320. function convertBufferAttribute( attribute, indices ) {
  6321. const array = attribute.array;
  6322. const itemSize = attribute.itemSize;
  6323. const normalized = attribute.normalized;
  6324. const array2 = new array.constructor( indices.length * itemSize );
  6325. let index = 0, index2 = 0;
  6326. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6327. index = indices[ i ] * itemSize;
  6328. for ( let j = 0; j < itemSize; j ++ ) {
  6329. array2[ index2 ++ ] = array[ index ++ ];
  6330. }
  6331. }
  6332. return new BufferAttribute( array2, itemSize, normalized );
  6333. }
  6334. //
  6335. if ( this.index === null ) {
  6336. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  6337. return this;
  6338. }
  6339. const geometry2 = new BufferGeometry();
  6340. const indices = this.index.array;
  6341. const attributes = this.attributes;
  6342. // attributes
  6343. for ( const name in attributes ) {
  6344. const attribute = attributes[ name ];
  6345. const newAttribute = convertBufferAttribute( attribute, indices );
  6346. geometry2.setAttribute( name, newAttribute );
  6347. }
  6348. // morph attributes
  6349. const morphAttributes = this.morphAttributes;
  6350. for ( const name in morphAttributes ) {
  6351. const morphArray = [];
  6352. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6353. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6354. const attribute = morphAttribute[ i ];
  6355. const newAttribute = convertBufferAttribute( attribute, indices );
  6356. morphArray.push( newAttribute );
  6357. }
  6358. geometry2.morphAttributes[ name ] = morphArray;
  6359. }
  6360. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6361. // groups
  6362. const groups = this.groups;
  6363. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6364. const group = groups[ i ];
  6365. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6366. }
  6367. return geometry2;
  6368. },
  6369. toJSON: function () {
  6370. const data = {
  6371. metadata: {
  6372. version: 4.5,
  6373. type: 'BufferGeometry',
  6374. generator: 'BufferGeometry.toJSON'
  6375. }
  6376. };
  6377. // standard BufferGeometry serialization
  6378. data.uuid = this.uuid;
  6379. data.type = this.type;
  6380. if ( this.name !== '' ) data.name = this.name;
  6381. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6382. if ( this.parameters !== undefined ) {
  6383. const parameters = this.parameters;
  6384. for ( const key in parameters ) {
  6385. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6386. }
  6387. return data;
  6388. }
  6389. data.data = { attributes: {} };
  6390. const index = this.index;
  6391. if ( index !== null ) {
  6392. data.data.index = {
  6393. type: index.array.constructor.name,
  6394. array: Array.prototype.slice.call( index.array )
  6395. };
  6396. }
  6397. const attributes = this.attributes;
  6398. for ( const key in attributes ) {
  6399. const attribute = attributes[ key ];
  6400. const attributeData = attribute.toJSON( data.data );
  6401. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  6402. data.data.attributes[ key ] = attributeData;
  6403. }
  6404. const morphAttributes = {};
  6405. let hasMorphAttributes = false;
  6406. for ( const key in this.morphAttributes ) {
  6407. const attributeArray = this.morphAttributes[ key ];
  6408. const array = [];
  6409. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6410. const attribute = attributeArray[ i ];
  6411. const attributeData = attribute.toJSON( data.data );
  6412. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  6413. array.push( attributeData );
  6414. }
  6415. if ( array.length > 0 ) {
  6416. morphAttributes[ key ] = array;
  6417. hasMorphAttributes = true;
  6418. }
  6419. }
  6420. if ( hasMorphAttributes ) {
  6421. data.data.morphAttributes = morphAttributes;
  6422. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6423. }
  6424. const groups = this.groups;
  6425. if ( groups.length > 0 ) {
  6426. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6427. }
  6428. const boundingSphere = this.boundingSphere;
  6429. if ( boundingSphere !== null ) {
  6430. data.data.boundingSphere = {
  6431. center: boundingSphere.center.toArray(),
  6432. radius: boundingSphere.radius
  6433. };
  6434. }
  6435. return data;
  6436. },
  6437. clone: function () {
  6438. /*
  6439. // Handle primitives
  6440. const parameters = this.parameters;
  6441. if ( parameters !== undefined ) {
  6442. const values = [];
  6443. for ( const key in parameters ) {
  6444. values.push( parameters[ key ] );
  6445. }
  6446. const geometry = Object.create( this.constructor.prototype );
  6447. this.constructor.apply( geometry, values );
  6448. return geometry;
  6449. }
  6450. return new this.constructor().copy( this );
  6451. */
  6452. return new BufferGeometry().copy( this );
  6453. },
  6454. copy: function ( source ) {
  6455. // reset
  6456. this.index = null;
  6457. this.attributes = {};
  6458. this.morphAttributes = {};
  6459. this.groups = [];
  6460. this.boundingBox = null;
  6461. this.boundingSphere = null;
  6462. // used for storing cloned, shared data
  6463. const data = {};
  6464. // name
  6465. this.name = source.name;
  6466. // index
  6467. const index = source.index;
  6468. if ( index !== null ) {
  6469. this.setIndex( index.clone( data ) );
  6470. }
  6471. // attributes
  6472. const attributes = source.attributes;
  6473. for ( const name in attributes ) {
  6474. const attribute = attributes[ name ];
  6475. this.setAttribute( name, attribute.clone( data ) );
  6476. }
  6477. // morph attributes
  6478. const morphAttributes = source.morphAttributes;
  6479. for ( const name in morphAttributes ) {
  6480. const array = [];
  6481. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6482. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6483. array.push( morphAttribute[ i ].clone( data ) );
  6484. }
  6485. this.morphAttributes[ name ] = array;
  6486. }
  6487. this.morphTargetsRelative = source.morphTargetsRelative;
  6488. // groups
  6489. const groups = source.groups;
  6490. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6491. const group = groups[ i ];
  6492. this.addGroup( group.start, group.count, group.materialIndex );
  6493. }
  6494. // bounding box
  6495. const boundingBox = source.boundingBox;
  6496. if ( boundingBox !== null ) {
  6497. this.boundingBox = boundingBox.clone();
  6498. }
  6499. // bounding sphere
  6500. const boundingSphere = source.boundingSphere;
  6501. if ( boundingSphere !== null ) {
  6502. this.boundingSphere = boundingSphere.clone();
  6503. }
  6504. // draw range
  6505. this.drawRange.start = source.drawRange.start;
  6506. this.drawRange.count = source.drawRange.count;
  6507. // user data
  6508. this.userData = source.userData;
  6509. return this;
  6510. },
  6511. dispose: function () {
  6512. this.dispatchEvent( { type: 'dispose' } );
  6513. }
  6514. } );
  6515. const _inverseMatrix = new Matrix4();
  6516. const _ray = new Ray();
  6517. const _sphere = new Sphere();
  6518. const _vA = new Vector3();
  6519. const _vB = new Vector3();
  6520. const _vC = new Vector3();
  6521. const _tempA = new Vector3();
  6522. const _tempB = new Vector3();
  6523. const _tempC = new Vector3();
  6524. const _morphA = new Vector3();
  6525. const _morphB = new Vector3();
  6526. const _morphC = new Vector3();
  6527. const _uvA = new Vector2();
  6528. const _uvB = new Vector2();
  6529. const _uvC = new Vector2();
  6530. const _intersectionPoint = new Vector3();
  6531. const _intersectionPointWorld = new Vector3();
  6532. function Mesh( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6533. Object3D.call( this );
  6534. this.type = 'Mesh';
  6535. this.geometry = geometry;
  6536. this.material = material;
  6537. this.updateMorphTargets();
  6538. }
  6539. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  6540. constructor: Mesh,
  6541. isMesh: true,
  6542. copy: function ( source ) {
  6543. Object3D.prototype.copy.call( this, source );
  6544. if ( source.morphTargetInfluences !== undefined ) {
  6545. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6546. }
  6547. if ( source.morphTargetDictionary !== undefined ) {
  6548. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6549. }
  6550. this.material = source.material;
  6551. this.geometry = source.geometry;
  6552. return this;
  6553. },
  6554. updateMorphTargets: function () {
  6555. const geometry = this.geometry;
  6556. if ( geometry.isBufferGeometry ) {
  6557. const morphAttributes = geometry.morphAttributes;
  6558. const keys = Object.keys( morphAttributes );
  6559. if ( keys.length > 0 ) {
  6560. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6561. if ( morphAttribute !== undefined ) {
  6562. this.morphTargetInfluences = [];
  6563. this.morphTargetDictionary = {};
  6564. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6565. const name = morphAttribute[ m ].name || String( m );
  6566. this.morphTargetInfluences.push( 0 );
  6567. this.morphTargetDictionary[ name ] = m;
  6568. }
  6569. }
  6570. }
  6571. } else {
  6572. const morphTargets = geometry.morphTargets;
  6573. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  6574. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  6575. }
  6576. }
  6577. },
  6578. raycast: function ( raycaster, intersects ) {
  6579. const geometry = this.geometry;
  6580. const material = this.material;
  6581. const matrixWorld = this.matrixWorld;
  6582. if ( material === undefined ) return;
  6583. // Checking boundingSphere distance to ray
  6584. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6585. _sphere.copy( geometry.boundingSphere );
  6586. _sphere.applyMatrix4( matrixWorld );
  6587. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  6588. //
  6589. _inverseMatrix.copy( matrixWorld ).invert();
  6590. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  6591. // Check boundingBox before continuing
  6592. if ( geometry.boundingBox !== null ) {
  6593. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return;
  6594. }
  6595. let intersection;
  6596. if ( geometry.isBufferGeometry ) {
  6597. const index = geometry.index;
  6598. const position = geometry.attributes.position;
  6599. const morphPosition = geometry.morphAttributes.position;
  6600. const morphTargetsRelative = geometry.morphTargetsRelative;
  6601. const uv = geometry.attributes.uv;
  6602. const uv2 = geometry.attributes.uv2;
  6603. const groups = geometry.groups;
  6604. const drawRange = geometry.drawRange;
  6605. if ( index !== null ) {
  6606. // indexed buffer geometry
  6607. if ( Array.isArray( material ) ) {
  6608. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6609. const group = groups[ i ];
  6610. const groupMaterial = material[ group.materialIndex ];
  6611. const start = Math.max( group.start, drawRange.start );
  6612. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6613. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6614. const a = index.getX( j );
  6615. const b = index.getX( j + 1 );
  6616. const c = index.getX( j + 2 );
  6617. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6618. if ( intersection ) {
  6619. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6620. intersection.face.materialIndex = group.materialIndex;
  6621. intersects.push( intersection );
  6622. }
  6623. }
  6624. }
  6625. } else {
  6626. const start = Math.max( 0, drawRange.start );
  6627. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6628. for ( let i = start, il = end; i < il; i += 3 ) {
  6629. const a = index.getX( i );
  6630. const b = index.getX( i + 1 );
  6631. const c = index.getX( i + 2 );
  6632. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6633. if ( intersection ) {
  6634. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6635. intersects.push( intersection );
  6636. }
  6637. }
  6638. }
  6639. } else if ( position !== undefined ) {
  6640. // non-indexed buffer geometry
  6641. if ( Array.isArray( material ) ) {
  6642. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6643. const group = groups[ i ];
  6644. const groupMaterial = material[ group.materialIndex ];
  6645. const start = Math.max( group.start, drawRange.start );
  6646. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  6647. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6648. const a = j;
  6649. const b = j + 1;
  6650. const c = j + 2;
  6651. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6652. if ( intersection ) {
  6653. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6654. intersection.face.materialIndex = group.materialIndex;
  6655. intersects.push( intersection );
  6656. }
  6657. }
  6658. }
  6659. } else {
  6660. const start = Math.max( 0, drawRange.start );
  6661. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6662. for ( let i = start, il = end; i < il; i += 3 ) {
  6663. const a = i;
  6664. const b = i + 1;
  6665. const c = i + 2;
  6666. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6667. if ( intersection ) {
  6668. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6669. intersects.push( intersection );
  6670. }
  6671. }
  6672. }
  6673. }
  6674. } else if ( geometry.isGeometry ) {
  6675. const isMultiMaterial = Array.isArray( material );
  6676. const vertices = geometry.vertices;
  6677. const faces = geometry.faces;
  6678. let uvs;
  6679. const faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  6680. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  6681. for ( let f = 0, fl = faces.length; f < fl; f ++ ) {
  6682. const face = faces[ f ];
  6683. const faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  6684. if ( faceMaterial === undefined ) continue;
  6685. const fvA = vertices[ face.a ];
  6686. const fvB = vertices[ face.b ];
  6687. const fvC = vertices[ face.c ];
  6688. intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
  6689. if ( intersection ) {
  6690. if ( uvs && uvs[ f ] ) {
  6691. const uvs_f = uvs[ f ];
  6692. _uvA.copy( uvs_f[ 0 ] );
  6693. _uvB.copy( uvs_f[ 1 ] );
  6694. _uvC.copy( uvs_f[ 2 ] );
  6695. intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() );
  6696. }
  6697. intersection.face = face;
  6698. intersection.faceIndex = f;
  6699. intersects.push( intersection );
  6700. }
  6701. }
  6702. }
  6703. }
  6704. } );
  6705. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6706. let intersect;
  6707. if ( material.side === BackSide ) {
  6708. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6709. } else {
  6710. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6711. }
  6712. if ( intersect === null ) return null;
  6713. _intersectionPointWorld.copy( point );
  6714. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6715. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6716. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6717. return {
  6718. distance: distance,
  6719. point: _intersectionPointWorld.clone(),
  6720. object: object
  6721. };
  6722. }
  6723. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6724. _vA.fromBufferAttribute( position, a );
  6725. _vB.fromBufferAttribute( position, b );
  6726. _vC.fromBufferAttribute( position, c );
  6727. const morphInfluences = object.morphTargetInfluences;
  6728. if ( material.morphTargets && morphPosition && morphInfluences ) {
  6729. _morphA.set( 0, 0, 0 );
  6730. _morphB.set( 0, 0, 0 );
  6731. _morphC.set( 0, 0, 0 );
  6732. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6733. const influence = morphInfluences[ i ];
  6734. const morphAttribute = morphPosition[ i ];
  6735. if ( influence === 0 ) continue;
  6736. _tempA.fromBufferAttribute( morphAttribute, a );
  6737. _tempB.fromBufferAttribute( morphAttribute, b );
  6738. _tempC.fromBufferAttribute( morphAttribute, c );
  6739. if ( morphTargetsRelative ) {
  6740. _morphA.addScaledVector( _tempA, influence );
  6741. _morphB.addScaledVector( _tempB, influence );
  6742. _morphC.addScaledVector( _tempC, influence );
  6743. } else {
  6744. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  6745. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  6746. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  6747. }
  6748. }
  6749. _vA.add( _morphA );
  6750. _vB.add( _morphB );
  6751. _vC.add( _morphC );
  6752. }
  6753. if ( object.isSkinnedMesh ) {
  6754. object.boneTransform( a, _vA );
  6755. object.boneTransform( b, _vB );
  6756. object.boneTransform( c, _vC );
  6757. }
  6758. const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  6759. if ( intersection ) {
  6760. if ( uv ) {
  6761. _uvA.fromBufferAttribute( uv, a );
  6762. _uvB.fromBufferAttribute( uv, b );
  6763. _uvC.fromBufferAttribute( uv, c );
  6764. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  6765. }
  6766. if ( uv2 ) {
  6767. _uvA.fromBufferAttribute( uv2, a );
  6768. _uvB.fromBufferAttribute( uv2, b );
  6769. _uvC.fromBufferAttribute( uv2, c );
  6770. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );
  6771. }
  6772. const face = new Face3( a, b, c );
  6773. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  6774. intersection.face = face;
  6775. }
  6776. return intersection;
  6777. }
  6778. class BoxBufferGeometry extends BufferGeometry {
  6779. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6780. super();
  6781. this.type = 'BoxBufferGeometry';
  6782. this.parameters = {
  6783. width: width,
  6784. height: height,
  6785. depth: depth,
  6786. widthSegments: widthSegments,
  6787. heightSegments: heightSegments,
  6788. depthSegments: depthSegments
  6789. };
  6790. const scope = this;
  6791. // segments
  6792. widthSegments = Math.floor( widthSegments );
  6793. heightSegments = Math.floor( heightSegments );
  6794. depthSegments = Math.floor( depthSegments );
  6795. // buffers
  6796. const indices = [];
  6797. const vertices = [];
  6798. const normals = [];
  6799. const uvs = [];
  6800. // helper variables
  6801. let numberOfVertices = 0;
  6802. let groupStart = 0;
  6803. // build each side of the box geometry
  6804. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6805. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6806. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6807. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6808. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6809. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6810. // build geometry
  6811. this.setIndex( indices );
  6812. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6813. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6814. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6815. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6816. const segmentWidth = width / gridX;
  6817. const segmentHeight = height / gridY;
  6818. const widthHalf = width / 2;
  6819. const heightHalf = height / 2;
  6820. const depthHalf = depth / 2;
  6821. const gridX1 = gridX + 1;
  6822. const gridY1 = gridY + 1;
  6823. let vertexCounter = 0;
  6824. let groupCount = 0;
  6825. const vector = new Vector3();
  6826. // generate vertices, normals and uvs
  6827. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6828. const y = iy * segmentHeight - heightHalf;
  6829. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6830. const x = ix * segmentWidth - widthHalf;
  6831. // set values to correct vector component
  6832. vector[ u ] = x * udir;
  6833. vector[ v ] = y * vdir;
  6834. vector[ w ] = depthHalf;
  6835. // now apply vector to vertex buffer
  6836. vertices.push( vector.x, vector.y, vector.z );
  6837. // set values to correct vector component
  6838. vector[ u ] = 0;
  6839. vector[ v ] = 0;
  6840. vector[ w ] = depth > 0 ? 1 : - 1;
  6841. // now apply vector to normal buffer
  6842. normals.push( vector.x, vector.y, vector.z );
  6843. // uvs
  6844. uvs.push( ix / gridX );
  6845. uvs.push( 1 - ( iy / gridY ) );
  6846. // counters
  6847. vertexCounter += 1;
  6848. }
  6849. }
  6850. // indices
  6851. // 1. you need three indices to draw a single face
  6852. // 2. a single segment consists of two faces
  6853. // 3. so we need to generate six (2*3) indices per segment
  6854. for ( let iy = 0; iy < gridY; iy ++ ) {
  6855. for ( let ix = 0; ix < gridX; ix ++ ) {
  6856. const a = numberOfVertices + ix + gridX1 * iy;
  6857. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6858. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6859. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6860. // faces
  6861. indices.push( a, b, d );
  6862. indices.push( b, c, d );
  6863. // increase counter
  6864. groupCount += 6;
  6865. }
  6866. }
  6867. // add a group to the geometry. this will ensure multi material support
  6868. scope.addGroup( groupStart, groupCount, materialIndex );
  6869. // calculate new start value for groups
  6870. groupStart += groupCount;
  6871. // update total number of vertices
  6872. numberOfVertices += vertexCounter;
  6873. }
  6874. }
  6875. }
  6876. /**
  6877. * Uniform Utilities
  6878. */
  6879. function cloneUniforms( src ) {
  6880. const dst = {};
  6881. for ( const u in src ) {
  6882. dst[ u ] = {};
  6883. for ( const p in src[ u ] ) {
  6884. const property = src[ u ][ p ];
  6885. if ( property && ( property.isColor ||
  6886. property.isMatrix3 || property.isMatrix4 ||
  6887. property.isVector2 || property.isVector3 || property.isVector4 ||
  6888. property.isTexture ) ) {
  6889. dst[ u ][ p ] = property.clone();
  6890. } else if ( Array.isArray( property ) ) {
  6891. dst[ u ][ p ] = property.slice();
  6892. } else {
  6893. dst[ u ][ p ] = property;
  6894. }
  6895. }
  6896. }
  6897. return dst;
  6898. }
  6899. function mergeUniforms( uniforms ) {
  6900. const merged = {};
  6901. for ( let u = 0; u < uniforms.length; u ++ ) {
  6902. const tmp = cloneUniforms( uniforms[ u ] );
  6903. for ( const p in tmp ) {
  6904. merged[ p ] = tmp[ p ];
  6905. }
  6906. }
  6907. return merged;
  6908. }
  6909. // Legacy
  6910. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6911. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6912. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6913. /**
  6914. * parameters = {
  6915. * defines: { "label" : "value" },
  6916. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6917. *
  6918. * fragmentShader: <string>,
  6919. * vertexShader: <string>,
  6920. *
  6921. * wireframe: <boolean>,
  6922. * wireframeLinewidth: <float>,
  6923. *
  6924. * lights: <bool>,
  6925. *
  6926. * skinning: <bool>,
  6927. * morphTargets: <bool>,
  6928. * morphNormals: <bool>
  6929. * }
  6930. */
  6931. function ShaderMaterial( parameters ) {
  6932. Material.call( this );
  6933. this.type = 'ShaderMaterial';
  6934. this.defines = {};
  6935. this.uniforms = {};
  6936. this.vertexShader = default_vertex;
  6937. this.fragmentShader = default_fragment;
  6938. this.linewidth = 1;
  6939. this.wireframe = false;
  6940. this.wireframeLinewidth = 1;
  6941. this.fog = false; // set to use scene fog
  6942. this.lights = false; // set to use scene lights
  6943. this.clipping = false; // set to use user-defined clipping planes
  6944. this.skinning = false; // set to use skinning attribute streams
  6945. this.morphTargets = false; // set to use morph targets
  6946. this.morphNormals = false; // set to use morph normals
  6947. this.extensions = {
  6948. derivatives: false, // set to use derivatives
  6949. fragDepth: false, // set to use fragment depth values
  6950. drawBuffers: false, // set to use draw buffers
  6951. shaderTextureLOD: false // set to use shader texture LOD
  6952. };
  6953. // When rendered geometry doesn't include these attributes but the material does,
  6954. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6955. this.defaultAttributeValues = {
  6956. 'color': [ 1, 1, 1 ],
  6957. 'uv': [ 0, 0 ],
  6958. 'uv2': [ 0, 0 ]
  6959. };
  6960. this.index0AttributeName = undefined;
  6961. this.uniformsNeedUpdate = false;
  6962. this.glslVersion = null;
  6963. if ( parameters !== undefined ) {
  6964. if ( parameters.attributes !== undefined ) {
  6965. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  6966. }
  6967. this.setValues( parameters );
  6968. }
  6969. }
  6970. ShaderMaterial.prototype = Object.create( Material.prototype );
  6971. ShaderMaterial.prototype.constructor = ShaderMaterial;
  6972. ShaderMaterial.prototype.isShaderMaterial = true;
  6973. ShaderMaterial.prototype.copy = function ( source ) {
  6974. Material.prototype.copy.call( this, source );
  6975. this.fragmentShader = source.fragmentShader;
  6976. this.vertexShader = source.vertexShader;
  6977. this.uniforms = cloneUniforms( source.uniforms );
  6978. this.defines = Object.assign( {}, source.defines );
  6979. this.wireframe = source.wireframe;
  6980. this.wireframeLinewidth = source.wireframeLinewidth;
  6981. this.lights = source.lights;
  6982. this.clipping = source.clipping;
  6983. this.skinning = source.skinning;
  6984. this.morphTargets = source.morphTargets;
  6985. this.morphNormals = source.morphNormals;
  6986. this.extensions = Object.assign( {}, source.extensions );
  6987. this.glslVersion = source.glslVersion;
  6988. return this;
  6989. };
  6990. ShaderMaterial.prototype.toJSON = function ( meta ) {
  6991. const data = Material.prototype.toJSON.call( this, meta );
  6992. data.glslVersion = this.glslVersion;
  6993. data.uniforms = {};
  6994. for ( const name in this.uniforms ) {
  6995. const uniform = this.uniforms[ name ];
  6996. const value = uniform.value;
  6997. if ( value && value.isTexture ) {
  6998. data.uniforms[ name ] = {
  6999. type: 't',
  7000. value: value.toJSON( meta ).uuid
  7001. };
  7002. } else if ( value && value.isColor ) {
  7003. data.uniforms[ name ] = {
  7004. type: 'c',
  7005. value: value.getHex()
  7006. };
  7007. } else if ( value && value.isVector2 ) {
  7008. data.uniforms[ name ] = {
  7009. type: 'v2',
  7010. value: value.toArray()
  7011. };
  7012. } else if ( value && value.isVector3 ) {
  7013. data.uniforms[ name ] = {
  7014. type: 'v3',
  7015. value: value.toArray()
  7016. };
  7017. } else if ( value && value.isVector4 ) {
  7018. data.uniforms[ name ] = {
  7019. type: 'v4',
  7020. value: value.toArray()
  7021. };
  7022. } else if ( value && value.isMatrix3 ) {
  7023. data.uniforms[ name ] = {
  7024. type: 'm3',
  7025. value: value.toArray()
  7026. };
  7027. } else if ( value && value.isMatrix4 ) {
  7028. data.uniforms[ name ] = {
  7029. type: 'm4',
  7030. value: value.toArray()
  7031. };
  7032. } else {
  7033. data.uniforms[ name ] = {
  7034. value: value
  7035. };
  7036. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7037. }
  7038. }
  7039. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7040. data.vertexShader = this.vertexShader;
  7041. data.fragmentShader = this.fragmentShader;
  7042. const extensions = {};
  7043. for ( const key in this.extensions ) {
  7044. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7045. }
  7046. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7047. return data;
  7048. };
  7049. function Camera() {
  7050. Object3D.call( this );
  7051. this.type = 'Camera';
  7052. this.matrixWorldInverse = new Matrix4();
  7053. this.projectionMatrix = new Matrix4();
  7054. this.projectionMatrixInverse = new Matrix4();
  7055. }
  7056. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  7057. constructor: Camera,
  7058. isCamera: true,
  7059. copy: function ( source, recursive ) {
  7060. Object3D.prototype.copy.call( this, source, recursive );
  7061. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7062. this.projectionMatrix.copy( source.projectionMatrix );
  7063. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7064. return this;
  7065. },
  7066. getWorldDirection: function ( target ) {
  7067. if ( target === undefined ) {
  7068. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  7069. target = new Vector3();
  7070. }
  7071. this.updateWorldMatrix( true, false );
  7072. const e = this.matrixWorld.elements;
  7073. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7074. },
  7075. updateMatrixWorld: function ( force ) {
  7076. Object3D.prototype.updateMatrixWorld.call( this, force );
  7077. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7078. },
  7079. updateWorldMatrix: function ( updateParents, updateChildren ) {
  7080. Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
  7081. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7082. },
  7083. clone: function () {
  7084. return new this.constructor().copy( this );
  7085. }
  7086. } );
  7087. function PerspectiveCamera( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7088. Camera.call( this );
  7089. this.type = 'PerspectiveCamera';
  7090. this.fov = fov;
  7091. this.zoom = 1;
  7092. this.near = near;
  7093. this.far = far;
  7094. this.focus = 10;
  7095. this.aspect = aspect;
  7096. this.view = null;
  7097. this.filmGauge = 35; // width of the film (default in millimeters)
  7098. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7099. this.updateProjectionMatrix();
  7100. }
  7101. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  7102. constructor: PerspectiveCamera,
  7103. isPerspectiveCamera: true,
  7104. copy: function ( source, recursive ) {
  7105. Camera.prototype.copy.call( this, source, recursive );
  7106. this.fov = source.fov;
  7107. this.zoom = source.zoom;
  7108. this.near = source.near;
  7109. this.far = source.far;
  7110. this.focus = source.focus;
  7111. this.aspect = source.aspect;
  7112. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7113. this.filmGauge = source.filmGauge;
  7114. this.filmOffset = source.filmOffset;
  7115. return this;
  7116. },
  7117. /**
  7118. * Sets the FOV by focal length in respect to the current .filmGauge.
  7119. *
  7120. * The default film gauge is 35, so that the focal length can be specified for
  7121. * a 35mm (full frame) camera.
  7122. *
  7123. * Values for focal length and film gauge must have the same unit.
  7124. */
  7125. setFocalLength: function ( focalLength ) {
  7126. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  7127. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7128. this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
  7129. this.updateProjectionMatrix();
  7130. },
  7131. /**
  7132. * Calculates the focal length from the current .fov and .filmGauge.
  7133. */
  7134. getFocalLength: function () {
  7135. const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
  7136. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7137. },
  7138. getEffectiveFOV: function () {
  7139. return MathUtils.RAD2DEG * 2 * Math.atan(
  7140. Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7141. },
  7142. getFilmWidth: function () {
  7143. // film not completely covered in portrait format (aspect < 1)
  7144. return this.filmGauge * Math.min( this.aspect, 1 );
  7145. },
  7146. getFilmHeight: function () {
  7147. // film not completely covered in landscape format (aspect > 1)
  7148. return this.filmGauge / Math.max( this.aspect, 1 );
  7149. },
  7150. /**
  7151. * Sets an offset in a larger frustum. This is useful for multi-window or
  7152. * multi-monitor/multi-machine setups.
  7153. *
  7154. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7155. * the monitors are in grid like this
  7156. *
  7157. * +---+---+---+
  7158. * | A | B | C |
  7159. * +---+---+---+
  7160. * | D | E | F |
  7161. * +---+---+---+
  7162. *
  7163. * then for each monitor you would call it like this
  7164. *
  7165. * const w = 1920;
  7166. * const h = 1080;
  7167. * const fullWidth = w * 3;
  7168. * const fullHeight = h * 2;
  7169. *
  7170. * --A--
  7171. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7172. * --B--
  7173. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7174. * --C--
  7175. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7176. * --D--
  7177. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7178. * --E--
  7179. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7180. * --F--
  7181. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7182. *
  7183. * Note there is no reason monitors have to be the same size or in a grid.
  7184. */
  7185. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  7186. this.aspect = fullWidth / fullHeight;
  7187. if ( this.view === null ) {
  7188. this.view = {
  7189. enabled: true,
  7190. fullWidth: 1,
  7191. fullHeight: 1,
  7192. offsetX: 0,
  7193. offsetY: 0,
  7194. width: 1,
  7195. height: 1
  7196. };
  7197. }
  7198. this.view.enabled = true;
  7199. this.view.fullWidth = fullWidth;
  7200. this.view.fullHeight = fullHeight;
  7201. this.view.offsetX = x;
  7202. this.view.offsetY = y;
  7203. this.view.width = width;
  7204. this.view.height = height;
  7205. this.updateProjectionMatrix();
  7206. },
  7207. clearViewOffset: function () {
  7208. if ( this.view !== null ) {
  7209. this.view.enabled = false;
  7210. }
  7211. this.updateProjectionMatrix();
  7212. },
  7213. updateProjectionMatrix: function () {
  7214. const near = this.near;
  7215. let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7216. let height = 2 * top;
  7217. let width = this.aspect * height;
  7218. let left = - 0.5 * width;
  7219. const view = this.view;
  7220. if ( this.view !== null && this.view.enabled ) {
  7221. const fullWidth = view.fullWidth,
  7222. fullHeight = view.fullHeight;
  7223. left += view.offsetX * width / fullWidth;
  7224. top -= view.offsetY * height / fullHeight;
  7225. width *= view.width / fullWidth;
  7226. height *= view.height / fullHeight;
  7227. }
  7228. const skew = this.filmOffset;
  7229. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7230. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7231. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7232. },
  7233. toJSON: function ( meta ) {
  7234. const data = Object3D.prototype.toJSON.call( this, meta );
  7235. data.object.fov = this.fov;
  7236. data.object.zoom = this.zoom;
  7237. data.object.near = this.near;
  7238. data.object.far = this.far;
  7239. data.object.focus = this.focus;
  7240. data.object.aspect = this.aspect;
  7241. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7242. data.object.filmGauge = this.filmGauge;
  7243. data.object.filmOffset = this.filmOffset;
  7244. return data;
  7245. }
  7246. } );
  7247. const fov = 90, aspect = 1;
  7248. function CubeCamera( near, far, renderTarget ) {
  7249. Object3D.call( this );
  7250. this.type = 'CubeCamera';
  7251. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7252. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7253. return;
  7254. }
  7255. this.renderTarget = renderTarget;
  7256. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7257. cameraPX.layers = this.layers;
  7258. cameraPX.up.set( 0, - 1, 0 );
  7259. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7260. this.add( cameraPX );
  7261. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7262. cameraNX.layers = this.layers;
  7263. cameraNX.up.set( 0, - 1, 0 );
  7264. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7265. this.add( cameraNX );
  7266. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7267. cameraPY.layers = this.layers;
  7268. cameraPY.up.set( 0, 0, 1 );
  7269. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7270. this.add( cameraPY );
  7271. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7272. cameraNY.layers = this.layers;
  7273. cameraNY.up.set( 0, 0, - 1 );
  7274. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7275. this.add( cameraNY );
  7276. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7277. cameraPZ.layers = this.layers;
  7278. cameraPZ.up.set( 0, - 1, 0 );
  7279. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7280. this.add( cameraPZ );
  7281. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7282. cameraNZ.layers = this.layers;
  7283. cameraNZ.up.set( 0, - 1, 0 );
  7284. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7285. this.add( cameraNZ );
  7286. this.update = function ( renderer, scene ) {
  7287. if ( this.parent === null ) this.updateMatrixWorld();
  7288. const currentXrEnabled = renderer.xr.enabled;
  7289. const currentRenderTarget = renderer.getRenderTarget();
  7290. renderer.xr.enabled = false;
  7291. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7292. renderTarget.texture.generateMipmaps = false;
  7293. renderer.setRenderTarget( renderTarget, 0 );
  7294. renderer.render( scene, cameraPX );
  7295. renderer.setRenderTarget( renderTarget, 1 );
  7296. renderer.render( scene, cameraNX );
  7297. renderer.setRenderTarget( renderTarget, 2 );
  7298. renderer.render( scene, cameraPY );
  7299. renderer.setRenderTarget( renderTarget, 3 );
  7300. renderer.render( scene, cameraNY );
  7301. renderer.setRenderTarget( renderTarget, 4 );
  7302. renderer.render( scene, cameraPZ );
  7303. renderTarget.texture.generateMipmaps = generateMipmaps;
  7304. renderer.setRenderTarget( renderTarget, 5 );
  7305. renderer.render( scene, cameraNZ );
  7306. renderer.setRenderTarget( currentRenderTarget );
  7307. renderer.xr.enabled = currentXrEnabled;
  7308. };
  7309. }
  7310. CubeCamera.prototype = Object.create( Object3D.prototype );
  7311. CubeCamera.prototype.constructor = CubeCamera;
  7312. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7313. images = images !== undefined ? images : [];
  7314. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7315. format = format !== undefined ? format : RGBFormat;
  7316. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7317. this.flipY = false;
  7318. // Why CubeTexture._needsFlipEnvMap is necessary:
  7319. //
  7320. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7321. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7322. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7323. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7324. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7325. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7326. this._needsFlipEnvMap = true;
  7327. }
  7328. CubeTexture.prototype = Object.create( Texture.prototype );
  7329. CubeTexture.prototype.constructor = CubeTexture;
  7330. CubeTexture.prototype.isCubeTexture = true;
  7331. Object.defineProperty( CubeTexture.prototype, 'images', {
  7332. get: function () {
  7333. return this.image;
  7334. },
  7335. set: function ( value ) {
  7336. this.image = value;
  7337. }
  7338. } );
  7339. function WebGLCubeRenderTarget( size, options, dummy ) {
  7340. if ( Number.isInteger( options ) ) {
  7341. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  7342. options = dummy;
  7343. }
  7344. WebGLRenderTarget.call( this, size, size, options );
  7345. options = options || {};
  7346. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7347. this.texture._needsFlipEnvMap = false;
  7348. }
  7349. WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
  7350. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  7351. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7352. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
  7353. this.texture.type = texture.type;
  7354. this.texture.format = RGBAFormat; // see #18859
  7355. this.texture.encoding = texture.encoding;
  7356. this.texture.generateMipmaps = texture.generateMipmaps;
  7357. this.texture.minFilter = texture.minFilter;
  7358. this.texture.magFilter = texture.magFilter;
  7359. const shader = {
  7360. uniforms: {
  7361. tEquirect: { value: null },
  7362. },
  7363. vertexShader: /* glsl */`
  7364. varying vec3 vWorldDirection;
  7365. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7366. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7367. }
  7368. void main() {
  7369. vWorldDirection = transformDirection( position, modelMatrix );
  7370. #include <begin_vertex>
  7371. #include <project_vertex>
  7372. }
  7373. `,
  7374. fragmentShader: /* glsl */`
  7375. uniform sampler2D tEquirect;
  7376. varying vec3 vWorldDirection;
  7377. #include <common>
  7378. void main() {
  7379. vec3 direction = normalize( vWorldDirection );
  7380. vec2 sampleUV = equirectUv( direction );
  7381. gl_FragColor = texture2D( tEquirect, sampleUV );
  7382. }
  7383. `
  7384. };
  7385. const geometry = new BoxBufferGeometry( 5, 5, 5 );
  7386. const material = new ShaderMaterial( {
  7387. name: 'CubemapFromEquirect',
  7388. uniforms: cloneUniforms( shader.uniforms ),
  7389. vertexShader: shader.vertexShader,
  7390. fragmentShader: shader.fragmentShader,
  7391. side: BackSide,
  7392. blending: NoBlending
  7393. } );
  7394. material.uniforms.tEquirect.value = texture;
  7395. const mesh = new Mesh( geometry, material );
  7396. const currentMinFilter = texture.minFilter;
  7397. // Avoid blurred poles
  7398. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7399. const camera = new CubeCamera( 1, 10, this );
  7400. camera.update( renderer, mesh );
  7401. texture.minFilter = currentMinFilter;
  7402. mesh.geometry.dispose();
  7403. mesh.material.dispose();
  7404. return this;
  7405. };
  7406. WebGLCubeRenderTarget.prototype.clear = function ( renderer, color, depth, stencil ) {
  7407. const currentRenderTarget = renderer.getRenderTarget();
  7408. for ( let i = 0; i < 6; i ++ ) {
  7409. renderer.setRenderTarget( this, i );
  7410. renderer.clear( color, depth, stencil );
  7411. }
  7412. renderer.setRenderTarget( currentRenderTarget );
  7413. };
  7414. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7415. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7416. this.image = { data: data || null, width: width || 1, height: height || 1 };
  7417. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7418. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7419. this.generateMipmaps = false;
  7420. this.flipY = false;
  7421. this.unpackAlignment = 1;
  7422. this.needsUpdate = true;
  7423. }
  7424. DataTexture.prototype = Object.create( Texture.prototype );
  7425. DataTexture.prototype.constructor = DataTexture;
  7426. DataTexture.prototype.isDataTexture = true;
  7427. const _sphere$1 = /*@__PURE__*/ new Sphere();
  7428. const _vector$5 = /*@__PURE__*/ new Vector3();
  7429. class Frustum {
  7430. constructor( p0, p1, p2, p3, p4, p5 ) {
  7431. this.planes = [
  7432. ( p0 !== undefined ) ? p0 : new Plane(),
  7433. ( p1 !== undefined ) ? p1 : new Plane(),
  7434. ( p2 !== undefined ) ? p2 : new Plane(),
  7435. ( p3 !== undefined ) ? p3 : new Plane(),
  7436. ( p4 !== undefined ) ? p4 : new Plane(),
  7437. ( p5 !== undefined ) ? p5 : new Plane()
  7438. ];
  7439. }
  7440. set( p0, p1, p2, p3, p4, p5 ) {
  7441. const planes = this.planes;
  7442. planes[ 0 ].copy( p0 );
  7443. planes[ 1 ].copy( p1 );
  7444. planes[ 2 ].copy( p2 );
  7445. planes[ 3 ].copy( p3 );
  7446. planes[ 4 ].copy( p4 );
  7447. planes[ 5 ].copy( p5 );
  7448. return this;
  7449. }
  7450. clone() {
  7451. return new this.constructor().copy( this );
  7452. }
  7453. copy( frustum ) {
  7454. const planes = this.planes;
  7455. for ( let i = 0; i < 6; i ++ ) {
  7456. planes[ i ].copy( frustum.planes[ i ] );
  7457. }
  7458. return this;
  7459. }
  7460. setFromProjectionMatrix( m ) {
  7461. const planes = this.planes;
  7462. const me = m.elements;
  7463. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7464. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7465. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7466. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7467. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7468. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7469. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7470. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7471. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7472. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7473. return this;
  7474. }
  7475. intersectsObject( object ) {
  7476. const geometry = object.geometry;
  7477. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7478. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7479. return this.intersectsSphere( _sphere$1 );
  7480. }
  7481. intersectsSprite( sprite ) {
  7482. _sphere$1.center.set( 0, 0, 0 );
  7483. _sphere$1.radius = 0.7071067811865476;
  7484. _sphere$1.applyMatrix4( sprite.matrixWorld );
  7485. return this.intersectsSphere( _sphere$1 );
  7486. }
  7487. intersectsSphere( sphere ) {
  7488. const planes = this.planes;
  7489. const center = sphere.center;
  7490. const negRadius = - sphere.radius;
  7491. for ( let i = 0; i < 6; i ++ ) {
  7492. const distance = planes[ i ].distanceToPoint( center );
  7493. if ( distance < negRadius ) {
  7494. return false;
  7495. }
  7496. }
  7497. return true;
  7498. }
  7499. intersectsBox( box ) {
  7500. const planes = this.planes;
  7501. for ( let i = 0; i < 6; i ++ ) {
  7502. const plane = planes[ i ];
  7503. // corner at max distance
  7504. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7505. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7506. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7507. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  7508. return false;
  7509. }
  7510. }
  7511. return true;
  7512. }
  7513. containsPoint( point ) {
  7514. const planes = this.planes;
  7515. for ( let i = 0; i < 6; i ++ ) {
  7516. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7517. return false;
  7518. }
  7519. }
  7520. return true;
  7521. }
  7522. }
  7523. function WebGLAnimation() {
  7524. let context = null;
  7525. let isAnimating = false;
  7526. let animationLoop = null;
  7527. let requestId = null;
  7528. function onAnimationFrame( time, frame ) {
  7529. animationLoop( time, frame );
  7530. requestId = context.requestAnimationFrame( onAnimationFrame );
  7531. }
  7532. return {
  7533. start: function () {
  7534. if ( isAnimating === true ) return;
  7535. if ( animationLoop === null ) return;
  7536. requestId = context.requestAnimationFrame( onAnimationFrame );
  7537. isAnimating = true;
  7538. },
  7539. stop: function () {
  7540. context.cancelAnimationFrame( requestId );
  7541. isAnimating = false;
  7542. },
  7543. setAnimationLoop: function ( callback ) {
  7544. animationLoop = callback;
  7545. },
  7546. setContext: function ( value ) {
  7547. context = value;
  7548. }
  7549. };
  7550. }
  7551. function WebGLAttributes( gl, capabilities ) {
  7552. const isWebGL2 = capabilities.isWebGL2;
  7553. const buffers = new WeakMap();
  7554. function createBuffer( attribute, bufferType ) {
  7555. const array = attribute.array;
  7556. const usage = attribute.usage;
  7557. const buffer = gl.createBuffer();
  7558. gl.bindBuffer( bufferType, buffer );
  7559. gl.bufferData( bufferType, array, usage );
  7560. attribute.onUploadCallback();
  7561. let type = 5126;
  7562. if ( array instanceof Float32Array ) {
  7563. type = 5126;
  7564. } else if ( array instanceof Float64Array ) {
  7565. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  7566. } else if ( array instanceof Uint16Array ) {
  7567. if ( attribute.isFloat16BufferAttribute ) {
  7568. if ( isWebGL2 ) {
  7569. type = 5131;
  7570. } else {
  7571. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7572. }
  7573. } else {
  7574. type = 5123;
  7575. }
  7576. } else if ( array instanceof Int16Array ) {
  7577. type = 5122;
  7578. } else if ( array instanceof Uint32Array ) {
  7579. type = 5125;
  7580. } else if ( array instanceof Int32Array ) {
  7581. type = 5124;
  7582. } else if ( array instanceof Int8Array ) {
  7583. type = 5120;
  7584. } else if ( array instanceof Uint8Array ) {
  7585. type = 5121;
  7586. }
  7587. return {
  7588. buffer: buffer,
  7589. type: type,
  7590. bytesPerElement: array.BYTES_PER_ELEMENT,
  7591. version: attribute.version
  7592. };
  7593. }
  7594. function updateBuffer( buffer, attribute, bufferType ) {
  7595. const array = attribute.array;
  7596. const updateRange = attribute.updateRange;
  7597. gl.bindBuffer( bufferType, buffer );
  7598. if ( updateRange.count === - 1 ) {
  7599. // Not using update ranges
  7600. gl.bufferSubData( bufferType, 0, array );
  7601. } else {
  7602. if ( isWebGL2 ) {
  7603. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7604. array, updateRange.offset, updateRange.count );
  7605. } else {
  7606. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7607. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7608. }
  7609. updateRange.count = - 1; // reset range
  7610. }
  7611. }
  7612. //
  7613. function get( attribute ) {
  7614. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7615. return buffers.get( attribute );
  7616. }
  7617. function remove( attribute ) {
  7618. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7619. const data = buffers.get( attribute );
  7620. if ( data ) {
  7621. gl.deleteBuffer( data.buffer );
  7622. buffers.delete( attribute );
  7623. }
  7624. }
  7625. function update( attribute, bufferType ) {
  7626. if ( attribute.isGLBufferAttribute ) {
  7627. const cached = buffers.get( attribute );
  7628. if ( ! cached || cached.version < attribute.version ) {
  7629. buffers.set( attribute, {
  7630. buffer: attribute.buffer,
  7631. type: attribute.type,
  7632. bytesPerElement: attribute.elementSize,
  7633. version: attribute.version
  7634. } );
  7635. }
  7636. return;
  7637. }
  7638. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7639. const data = buffers.get( attribute );
  7640. if ( data === undefined ) {
  7641. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7642. } else if ( data.version < attribute.version ) {
  7643. updateBuffer( data.buffer, attribute, bufferType );
  7644. data.version = attribute.version;
  7645. }
  7646. }
  7647. return {
  7648. get: get,
  7649. remove: remove,
  7650. update: update
  7651. };
  7652. }
  7653. class PlaneBufferGeometry extends BufferGeometry {
  7654. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7655. super();
  7656. this.type = 'PlaneBufferGeometry';
  7657. this.parameters = {
  7658. width: width,
  7659. height: height,
  7660. widthSegments: widthSegments,
  7661. heightSegments: heightSegments
  7662. };
  7663. const width_half = width / 2;
  7664. const height_half = height / 2;
  7665. const gridX = Math.floor( widthSegments );
  7666. const gridY = Math.floor( heightSegments );
  7667. const gridX1 = gridX + 1;
  7668. const gridY1 = gridY + 1;
  7669. const segment_width = width / gridX;
  7670. const segment_height = height / gridY;
  7671. //
  7672. const indices = [];
  7673. const vertices = [];
  7674. const normals = [];
  7675. const uvs = [];
  7676. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7677. const y = iy * segment_height - height_half;
  7678. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7679. const x = ix * segment_width - width_half;
  7680. vertices.push( x, - y, 0 );
  7681. normals.push( 0, 0, 1 );
  7682. uvs.push( ix / gridX );
  7683. uvs.push( 1 - ( iy / gridY ) );
  7684. }
  7685. }
  7686. for ( let iy = 0; iy < gridY; iy ++ ) {
  7687. for ( let ix = 0; ix < gridX; ix ++ ) {
  7688. const a = ix + gridX1 * iy;
  7689. const b = ix + gridX1 * ( iy + 1 );
  7690. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7691. const d = ( ix + 1 ) + gridX1 * iy;
  7692. indices.push( a, b, d );
  7693. indices.push( b, c, d );
  7694. }
  7695. }
  7696. this.setIndex( indices );
  7697. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7698. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7699. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7700. }
  7701. }
  7702. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7703. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7704. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7705. 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";
  7706. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7707. var begin_vertex = "vec3 transformed = vec3( position );";
  7708. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7709. 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";
  7710. 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";
  7711. 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";
  7712. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7713. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7714. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7715. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7716. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  7717. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7718. 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";
  7719. 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}";
  7720. 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";
  7721. 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";
  7722. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7723. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7724. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7725. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7726. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7727. 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}";
  7728. 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";
  7729. 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";
  7730. 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";
  7731. 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";
  7732. 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";
  7733. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7734. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7735. 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";
  7736. 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";
  7737. 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}";
  7738. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7739. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7740. 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";
  7741. 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";
  7742. 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";
  7743. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7744. 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)";
  7745. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7746. 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)";
  7747. 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";
  7748. 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}";
  7749. 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";
  7750. 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";
  7751. 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";
  7752. 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";
  7753. 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";
  7754. 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";
  7755. 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";
  7756. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7757. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7758. 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";
  7759. 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";
  7760. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7761. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7762. 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";
  7763. 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";
  7764. 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";
  7765. 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;";
  7766. 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";
  7767. 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";
  7768. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7769. 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";
  7770. 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";
  7771. 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}";
  7772. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7773. 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;";
  7774. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7775. 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";
  7776. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7777. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7778. 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";
  7779. 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";
  7780. 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";
  7781. 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}";
  7782. 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";
  7783. 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";
  7784. 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";
  7785. 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";
  7786. 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";
  7787. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7788. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7789. 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; }";
  7790. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  7791. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  7792. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7793. 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";
  7794. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7795. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7796. 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";
  7797. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7798. 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";
  7799. 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}";
  7800. 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}";
  7801. 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}";
  7802. 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}";
  7803. 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}";
  7804. 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}";
  7805. 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}";
  7806. 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}";
  7807. 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}";
  7808. 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}";
  7809. 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}";
  7810. 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}";
  7811. 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}";
  7812. 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}";
  7813. 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}";
  7814. 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}";
  7815. 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}";
  7816. 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}";
  7817. 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}";
  7818. 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}";
  7819. 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}";
  7820. 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}";
  7821. 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}";
  7822. 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}";
  7823. 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}";
  7824. 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}";
  7825. 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}";
  7826. 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}";
  7827. 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}";
  7828. 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}";
  7829. 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}";
  7830. 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}";
  7831. const ShaderChunk = {
  7832. alphamap_fragment: alphamap_fragment,
  7833. alphamap_pars_fragment: alphamap_pars_fragment,
  7834. alphatest_fragment: alphatest_fragment,
  7835. aomap_fragment: aomap_fragment,
  7836. aomap_pars_fragment: aomap_pars_fragment,
  7837. begin_vertex: begin_vertex,
  7838. beginnormal_vertex: beginnormal_vertex,
  7839. bsdfs: bsdfs,
  7840. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7841. clipping_planes_fragment: clipping_planes_fragment,
  7842. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7843. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7844. clipping_planes_vertex: clipping_planes_vertex,
  7845. color_fragment: color_fragment,
  7846. color_pars_fragment: color_pars_fragment,
  7847. color_pars_vertex: color_pars_vertex,
  7848. color_vertex: color_vertex,
  7849. common: common,
  7850. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7851. defaultnormal_vertex: defaultnormal_vertex,
  7852. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7853. displacementmap_vertex: displacementmap_vertex,
  7854. emissivemap_fragment: emissivemap_fragment,
  7855. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7856. encodings_fragment: encodings_fragment,
  7857. encodings_pars_fragment: encodings_pars_fragment,
  7858. envmap_fragment: envmap_fragment,
  7859. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7860. envmap_pars_fragment: envmap_pars_fragment,
  7861. envmap_pars_vertex: envmap_pars_vertex,
  7862. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7863. envmap_vertex: envmap_vertex,
  7864. fog_vertex: fog_vertex,
  7865. fog_pars_vertex: fog_pars_vertex,
  7866. fog_fragment: fog_fragment,
  7867. fog_pars_fragment: fog_pars_fragment,
  7868. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7869. lightmap_fragment: lightmap_fragment,
  7870. lightmap_pars_fragment: lightmap_pars_fragment,
  7871. lights_lambert_vertex: lights_lambert_vertex,
  7872. lights_pars_begin: lights_pars_begin,
  7873. lights_toon_fragment: lights_toon_fragment,
  7874. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7875. lights_phong_fragment: lights_phong_fragment,
  7876. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7877. lights_physical_fragment: lights_physical_fragment,
  7878. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7879. lights_fragment_begin: lights_fragment_begin,
  7880. lights_fragment_maps: lights_fragment_maps,
  7881. lights_fragment_end: lights_fragment_end,
  7882. logdepthbuf_fragment: logdepthbuf_fragment,
  7883. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7884. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7885. logdepthbuf_vertex: logdepthbuf_vertex,
  7886. map_fragment: map_fragment,
  7887. map_pars_fragment: map_pars_fragment,
  7888. map_particle_fragment: map_particle_fragment,
  7889. map_particle_pars_fragment: map_particle_pars_fragment,
  7890. metalnessmap_fragment: metalnessmap_fragment,
  7891. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7892. morphnormal_vertex: morphnormal_vertex,
  7893. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7894. morphtarget_vertex: morphtarget_vertex,
  7895. normal_fragment_begin: normal_fragment_begin,
  7896. normal_fragment_maps: normal_fragment_maps,
  7897. normalmap_pars_fragment: normalmap_pars_fragment,
  7898. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7899. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7900. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7901. packing: packing,
  7902. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7903. project_vertex: project_vertex,
  7904. dithering_fragment: dithering_fragment,
  7905. dithering_pars_fragment: dithering_pars_fragment,
  7906. roughnessmap_fragment: roughnessmap_fragment,
  7907. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7908. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7909. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7910. shadowmap_vertex: shadowmap_vertex,
  7911. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7912. skinbase_vertex: skinbase_vertex,
  7913. skinning_pars_vertex: skinning_pars_vertex,
  7914. skinning_vertex: skinning_vertex,
  7915. skinnormal_vertex: skinnormal_vertex,
  7916. specularmap_fragment: specularmap_fragment,
  7917. specularmap_pars_fragment: specularmap_pars_fragment,
  7918. tonemapping_fragment: tonemapping_fragment,
  7919. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7920. transmissionmap_fragment: transmissionmap_fragment,
  7921. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  7922. uv_pars_fragment: uv_pars_fragment,
  7923. uv_pars_vertex: uv_pars_vertex,
  7924. uv_vertex: uv_vertex,
  7925. uv2_pars_fragment: uv2_pars_fragment,
  7926. uv2_pars_vertex: uv2_pars_vertex,
  7927. uv2_vertex: uv2_vertex,
  7928. worldpos_vertex: worldpos_vertex,
  7929. background_frag: background_frag,
  7930. background_vert: background_vert,
  7931. cube_frag: cube_frag,
  7932. cube_vert: cube_vert,
  7933. depth_frag: depth_frag,
  7934. depth_vert: depth_vert,
  7935. distanceRGBA_frag: distanceRGBA_frag,
  7936. distanceRGBA_vert: distanceRGBA_vert,
  7937. equirect_frag: equirect_frag,
  7938. equirect_vert: equirect_vert,
  7939. linedashed_frag: linedashed_frag,
  7940. linedashed_vert: linedashed_vert,
  7941. meshbasic_frag: meshbasic_frag,
  7942. meshbasic_vert: meshbasic_vert,
  7943. meshlambert_frag: meshlambert_frag,
  7944. meshlambert_vert: meshlambert_vert,
  7945. meshmatcap_frag: meshmatcap_frag,
  7946. meshmatcap_vert: meshmatcap_vert,
  7947. meshtoon_frag: meshtoon_frag,
  7948. meshtoon_vert: meshtoon_vert,
  7949. meshphong_frag: meshphong_frag,
  7950. meshphong_vert: meshphong_vert,
  7951. meshphysical_frag: meshphysical_frag,
  7952. meshphysical_vert: meshphysical_vert,
  7953. normal_frag: normal_frag,
  7954. normal_vert: normal_vert,
  7955. points_frag: points_frag,
  7956. points_vert: points_vert,
  7957. shadow_frag: shadow_frag,
  7958. shadow_vert: shadow_vert,
  7959. sprite_frag: sprite_frag,
  7960. sprite_vert: sprite_vert
  7961. };
  7962. /**
  7963. * Uniforms library for shared webgl shaders
  7964. */
  7965. const UniformsLib = {
  7966. common: {
  7967. diffuse: { value: new Color( 0xeeeeee ) },
  7968. opacity: { value: 1.0 },
  7969. map: { value: null },
  7970. uvTransform: { value: new Matrix3() },
  7971. uv2Transform: { value: new Matrix3() },
  7972. alphaMap: { value: null },
  7973. },
  7974. specularmap: {
  7975. specularMap: { value: null },
  7976. },
  7977. envmap: {
  7978. envMap: { value: null },
  7979. flipEnvMap: { value: - 1 },
  7980. reflectivity: { value: 1.0 },
  7981. refractionRatio: { value: 0.98 },
  7982. maxMipLevel: { value: 0 }
  7983. },
  7984. aomap: {
  7985. aoMap: { value: null },
  7986. aoMapIntensity: { value: 1 }
  7987. },
  7988. lightmap: {
  7989. lightMap: { value: null },
  7990. lightMapIntensity: { value: 1 }
  7991. },
  7992. emissivemap: {
  7993. emissiveMap: { value: null }
  7994. },
  7995. bumpmap: {
  7996. bumpMap: { value: null },
  7997. bumpScale: { value: 1 }
  7998. },
  7999. normalmap: {
  8000. normalMap: { value: null },
  8001. normalScale: { value: new Vector2( 1, 1 ) }
  8002. },
  8003. displacementmap: {
  8004. displacementMap: { value: null },
  8005. displacementScale: { value: 1 },
  8006. displacementBias: { value: 0 }
  8007. },
  8008. roughnessmap: {
  8009. roughnessMap: { value: null }
  8010. },
  8011. metalnessmap: {
  8012. metalnessMap: { value: null }
  8013. },
  8014. gradientmap: {
  8015. gradientMap: { value: null }
  8016. },
  8017. fog: {
  8018. fogDensity: { value: 0.00025 },
  8019. fogNear: { value: 1 },
  8020. fogFar: { value: 2000 },
  8021. fogColor: { value: new Color( 0xffffff ) }
  8022. },
  8023. lights: {
  8024. ambientLightColor: { value: [] },
  8025. lightProbe: { value: [] },
  8026. directionalLights: { value: [], properties: {
  8027. direction: {},
  8028. color: {}
  8029. } },
  8030. directionalLightShadows: { value: [], properties: {
  8031. shadowBias: {},
  8032. shadowNormalBias: {},
  8033. shadowRadius: {},
  8034. shadowMapSize: {}
  8035. } },
  8036. directionalShadowMap: { value: [] },
  8037. directionalShadowMatrix: { value: [] },
  8038. spotLights: { value: [], properties: {
  8039. color: {},
  8040. position: {},
  8041. direction: {},
  8042. distance: {},
  8043. coneCos: {},
  8044. penumbraCos: {},
  8045. decay: {}
  8046. } },
  8047. spotLightShadows: { value: [], properties: {
  8048. shadowBias: {},
  8049. shadowNormalBias: {},
  8050. shadowRadius: {},
  8051. shadowMapSize: {}
  8052. } },
  8053. spotShadowMap: { value: [] },
  8054. spotShadowMatrix: { value: [] },
  8055. pointLights: { value: [], properties: {
  8056. color: {},
  8057. position: {},
  8058. decay: {},
  8059. distance: {}
  8060. } },
  8061. pointLightShadows: { value: [], properties: {
  8062. shadowBias: {},
  8063. shadowNormalBias: {},
  8064. shadowRadius: {},
  8065. shadowMapSize: {},
  8066. shadowCameraNear: {},
  8067. shadowCameraFar: {}
  8068. } },
  8069. pointShadowMap: { value: [] },
  8070. pointShadowMatrix: { value: [] },
  8071. hemisphereLights: { value: [], properties: {
  8072. direction: {},
  8073. skyColor: {},
  8074. groundColor: {}
  8075. } },
  8076. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8077. rectAreaLights: { value: [], properties: {
  8078. color: {},
  8079. position: {},
  8080. width: {},
  8081. height: {}
  8082. } },
  8083. ltc_1: { value: null },
  8084. ltc_2: { value: null }
  8085. },
  8086. points: {
  8087. diffuse: { value: new Color( 0xeeeeee ) },
  8088. opacity: { value: 1.0 },
  8089. size: { value: 1.0 },
  8090. scale: { value: 1.0 },
  8091. map: { value: null },
  8092. alphaMap: { value: null },
  8093. uvTransform: { value: new Matrix3() }
  8094. },
  8095. sprite: {
  8096. diffuse: { value: new Color( 0xeeeeee ) },
  8097. opacity: { value: 1.0 },
  8098. center: { value: new Vector2( 0.5, 0.5 ) },
  8099. rotation: { value: 0.0 },
  8100. map: { value: null },
  8101. alphaMap: { value: null },
  8102. uvTransform: { value: new Matrix3() }
  8103. }
  8104. };
  8105. const ShaderLib = {
  8106. basic: {
  8107. uniforms: mergeUniforms( [
  8108. UniformsLib.common,
  8109. UniformsLib.specularmap,
  8110. UniformsLib.envmap,
  8111. UniformsLib.aomap,
  8112. UniformsLib.lightmap,
  8113. UniformsLib.fog
  8114. ] ),
  8115. vertexShader: ShaderChunk.meshbasic_vert,
  8116. fragmentShader: ShaderChunk.meshbasic_frag
  8117. },
  8118. lambert: {
  8119. uniforms: mergeUniforms( [
  8120. UniformsLib.common,
  8121. UniformsLib.specularmap,
  8122. UniformsLib.envmap,
  8123. UniformsLib.aomap,
  8124. UniformsLib.lightmap,
  8125. UniformsLib.emissivemap,
  8126. UniformsLib.fog,
  8127. UniformsLib.lights,
  8128. {
  8129. emissive: { value: new Color( 0x000000 ) }
  8130. }
  8131. ] ),
  8132. vertexShader: ShaderChunk.meshlambert_vert,
  8133. fragmentShader: ShaderChunk.meshlambert_frag
  8134. },
  8135. phong: {
  8136. uniforms: mergeUniforms( [
  8137. UniformsLib.common,
  8138. UniformsLib.specularmap,
  8139. UniformsLib.envmap,
  8140. UniformsLib.aomap,
  8141. UniformsLib.lightmap,
  8142. UniformsLib.emissivemap,
  8143. UniformsLib.bumpmap,
  8144. UniformsLib.normalmap,
  8145. UniformsLib.displacementmap,
  8146. UniformsLib.fog,
  8147. UniformsLib.lights,
  8148. {
  8149. emissive: { value: new Color( 0x000000 ) },
  8150. specular: { value: new Color( 0x111111 ) },
  8151. shininess: { value: 30 }
  8152. }
  8153. ] ),
  8154. vertexShader: ShaderChunk.meshphong_vert,
  8155. fragmentShader: ShaderChunk.meshphong_frag
  8156. },
  8157. standard: {
  8158. uniforms: mergeUniforms( [
  8159. UniformsLib.common,
  8160. UniformsLib.envmap,
  8161. UniformsLib.aomap,
  8162. UniformsLib.lightmap,
  8163. UniformsLib.emissivemap,
  8164. UniformsLib.bumpmap,
  8165. UniformsLib.normalmap,
  8166. UniformsLib.displacementmap,
  8167. UniformsLib.roughnessmap,
  8168. UniformsLib.metalnessmap,
  8169. UniformsLib.fog,
  8170. UniformsLib.lights,
  8171. {
  8172. emissive: { value: new Color( 0x000000 ) },
  8173. roughness: { value: 1.0 },
  8174. metalness: { value: 0.0 },
  8175. envMapIntensity: { value: 1 } // temporary
  8176. }
  8177. ] ),
  8178. vertexShader: ShaderChunk.meshphysical_vert,
  8179. fragmentShader: ShaderChunk.meshphysical_frag
  8180. },
  8181. toon: {
  8182. uniforms: mergeUniforms( [
  8183. UniformsLib.common,
  8184. UniformsLib.aomap,
  8185. UniformsLib.lightmap,
  8186. UniformsLib.emissivemap,
  8187. UniformsLib.bumpmap,
  8188. UniformsLib.normalmap,
  8189. UniformsLib.displacementmap,
  8190. UniformsLib.gradientmap,
  8191. UniformsLib.fog,
  8192. UniformsLib.lights,
  8193. {
  8194. emissive: { value: new Color( 0x000000 ) }
  8195. }
  8196. ] ),
  8197. vertexShader: ShaderChunk.meshtoon_vert,
  8198. fragmentShader: ShaderChunk.meshtoon_frag
  8199. },
  8200. matcap: {
  8201. uniforms: mergeUniforms( [
  8202. UniformsLib.common,
  8203. UniformsLib.bumpmap,
  8204. UniformsLib.normalmap,
  8205. UniformsLib.displacementmap,
  8206. UniformsLib.fog,
  8207. {
  8208. matcap: { value: null }
  8209. }
  8210. ] ),
  8211. vertexShader: ShaderChunk.meshmatcap_vert,
  8212. fragmentShader: ShaderChunk.meshmatcap_frag
  8213. },
  8214. points: {
  8215. uniforms: mergeUniforms( [
  8216. UniformsLib.points,
  8217. UniformsLib.fog
  8218. ] ),
  8219. vertexShader: ShaderChunk.points_vert,
  8220. fragmentShader: ShaderChunk.points_frag
  8221. },
  8222. dashed: {
  8223. uniforms: mergeUniforms( [
  8224. UniformsLib.common,
  8225. UniformsLib.fog,
  8226. {
  8227. scale: { value: 1 },
  8228. dashSize: { value: 1 },
  8229. totalSize: { value: 2 }
  8230. }
  8231. ] ),
  8232. vertexShader: ShaderChunk.linedashed_vert,
  8233. fragmentShader: ShaderChunk.linedashed_frag
  8234. },
  8235. depth: {
  8236. uniforms: mergeUniforms( [
  8237. UniformsLib.common,
  8238. UniformsLib.displacementmap
  8239. ] ),
  8240. vertexShader: ShaderChunk.depth_vert,
  8241. fragmentShader: ShaderChunk.depth_frag
  8242. },
  8243. normal: {
  8244. uniforms: mergeUniforms( [
  8245. UniformsLib.common,
  8246. UniformsLib.bumpmap,
  8247. UniformsLib.normalmap,
  8248. UniformsLib.displacementmap,
  8249. {
  8250. opacity: { value: 1.0 }
  8251. }
  8252. ] ),
  8253. vertexShader: ShaderChunk.normal_vert,
  8254. fragmentShader: ShaderChunk.normal_frag
  8255. },
  8256. sprite: {
  8257. uniforms: mergeUniforms( [
  8258. UniformsLib.sprite,
  8259. UniformsLib.fog
  8260. ] ),
  8261. vertexShader: ShaderChunk.sprite_vert,
  8262. fragmentShader: ShaderChunk.sprite_frag
  8263. },
  8264. background: {
  8265. uniforms: {
  8266. uvTransform: { value: new Matrix3() },
  8267. t2D: { value: null },
  8268. },
  8269. vertexShader: ShaderChunk.background_vert,
  8270. fragmentShader: ShaderChunk.background_frag
  8271. },
  8272. /* -------------------------------------------------------------------------
  8273. // Cube map shader
  8274. ------------------------------------------------------------------------- */
  8275. cube: {
  8276. uniforms: mergeUniforms( [
  8277. UniformsLib.envmap,
  8278. {
  8279. opacity: { value: 1.0 }
  8280. }
  8281. ] ),
  8282. vertexShader: ShaderChunk.cube_vert,
  8283. fragmentShader: ShaderChunk.cube_frag
  8284. },
  8285. equirect: {
  8286. uniforms: {
  8287. tEquirect: { value: null },
  8288. },
  8289. vertexShader: ShaderChunk.equirect_vert,
  8290. fragmentShader: ShaderChunk.equirect_frag
  8291. },
  8292. distanceRGBA: {
  8293. uniforms: mergeUniforms( [
  8294. UniformsLib.common,
  8295. UniformsLib.displacementmap,
  8296. {
  8297. referencePosition: { value: new Vector3() },
  8298. nearDistance: { value: 1 },
  8299. farDistance: { value: 1000 }
  8300. }
  8301. ] ),
  8302. vertexShader: ShaderChunk.distanceRGBA_vert,
  8303. fragmentShader: ShaderChunk.distanceRGBA_frag
  8304. },
  8305. shadow: {
  8306. uniforms: mergeUniforms( [
  8307. UniformsLib.lights,
  8308. UniformsLib.fog,
  8309. {
  8310. color: { value: new Color( 0x00000 ) },
  8311. opacity: { value: 1.0 }
  8312. },
  8313. ] ),
  8314. vertexShader: ShaderChunk.shadow_vert,
  8315. fragmentShader: ShaderChunk.shadow_frag
  8316. }
  8317. };
  8318. ShaderLib.physical = {
  8319. uniforms: mergeUniforms( [
  8320. ShaderLib.standard.uniforms,
  8321. {
  8322. clearcoat: { value: 0 },
  8323. clearcoatMap: { value: null },
  8324. clearcoatRoughness: { value: 0 },
  8325. clearcoatRoughnessMap: { value: null },
  8326. clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
  8327. clearcoatNormalMap: { value: null },
  8328. sheen: { value: new Color( 0x000000 ) },
  8329. transmission: { value: 0 },
  8330. transmissionMap: { value: null },
  8331. }
  8332. ] ),
  8333. vertexShader: ShaderChunk.meshphysical_vert,
  8334. fragmentShader: ShaderChunk.meshphysical_frag
  8335. };
  8336. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  8337. const clearColor = new Color( 0x000000 );
  8338. let clearAlpha = 0;
  8339. let planeMesh;
  8340. let boxMesh;
  8341. let currentBackground = null;
  8342. let currentBackgroundVersion = 0;
  8343. let currentTonemapping = null;
  8344. function render( renderList, scene, camera, forceClear ) {
  8345. let background = scene.isScene === true ? scene.background : null;
  8346. if ( background && background.isTexture ) {
  8347. background = cubemaps.get( background );
  8348. }
  8349. // Ignore background in AR
  8350. // TODO: Reconsider this.
  8351. const xr = renderer.xr;
  8352. const session = xr.getSession && xr.getSession();
  8353. if ( session && session.environmentBlendMode === 'additive' ) {
  8354. background = null;
  8355. }
  8356. if ( background === null ) {
  8357. setClear( clearColor, clearAlpha );
  8358. } else if ( background && background.isColor ) {
  8359. setClear( background, 1 );
  8360. forceClear = true;
  8361. }
  8362. if ( renderer.autoClear || forceClear ) {
  8363. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8364. }
  8365. if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {
  8366. if ( boxMesh === undefined ) {
  8367. boxMesh = new Mesh(
  8368. new BoxBufferGeometry( 1, 1, 1 ),
  8369. new ShaderMaterial( {
  8370. name: 'BackgroundCubeMaterial',
  8371. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8372. vertexShader: ShaderLib.cube.vertexShader,
  8373. fragmentShader: ShaderLib.cube.fragmentShader,
  8374. side: BackSide,
  8375. depthTest: false,
  8376. depthWrite: false,
  8377. fog: false
  8378. } )
  8379. );
  8380. boxMesh.geometry.deleteAttribute( 'normal' );
  8381. boxMesh.geometry.deleteAttribute( 'uv' );
  8382. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8383. this.matrixWorld.copyPosition( camera.matrixWorld );
  8384. };
  8385. // enable code injection for non-built-in material
  8386. Object.defineProperty( boxMesh.material, 'envMap', {
  8387. get: function () {
  8388. return this.uniforms.envMap.value;
  8389. }
  8390. } );
  8391. objects.update( boxMesh );
  8392. }
  8393. if ( background.isWebGLCubeRenderTarget ) {
  8394. // TODO Deprecate
  8395. background = background.texture;
  8396. }
  8397. boxMesh.material.uniforms.envMap.value = background;
  8398. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1;
  8399. if ( currentBackground !== background ||
  8400. currentBackgroundVersion !== background.version ||
  8401. currentTonemapping !== renderer.toneMapping ) {
  8402. boxMesh.material.needsUpdate = true;
  8403. currentBackground = background;
  8404. currentBackgroundVersion = background.version;
  8405. currentTonemapping = renderer.toneMapping;
  8406. }
  8407. // push to the pre-sorted opaque render list
  8408. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8409. } else if ( background && background.isTexture ) {
  8410. if ( planeMesh === undefined ) {
  8411. planeMesh = new Mesh(
  8412. new PlaneBufferGeometry( 2, 2 ),
  8413. new ShaderMaterial( {
  8414. name: 'BackgroundMaterial',
  8415. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8416. vertexShader: ShaderLib.background.vertexShader,
  8417. fragmentShader: ShaderLib.background.fragmentShader,
  8418. side: FrontSide,
  8419. depthTest: false,
  8420. depthWrite: false,
  8421. fog: false
  8422. } )
  8423. );
  8424. planeMesh.geometry.deleteAttribute( 'normal' );
  8425. // enable code injection for non-built-in material
  8426. Object.defineProperty( planeMesh.material, 'map', {
  8427. get: function () {
  8428. return this.uniforms.t2D.value;
  8429. }
  8430. } );
  8431. objects.update( planeMesh );
  8432. }
  8433. planeMesh.material.uniforms.t2D.value = background;
  8434. if ( background.matrixAutoUpdate === true ) {
  8435. background.updateMatrix();
  8436. }
  8437. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8438. if ( currentBackground !== background ||
  8439. currentBackgroundVersion !== background.version ||
  8440. currentTonemapping !== renderer.toneMapping ) {
  8441. planeMesh.material.needsUpdate = true;
  8442. currentBackground = background;
  8443. currentBackgroundVersion = background.version;
  8444. currentTonemapping = renderer.toneMapping;
  8445. }
  8446. // push to the pre-sorted opaque render list
  8447. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8448. }
  8449. }
  8450. function setClear( color, alpha ) {
  8451. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8452. }
  8453. return {
  8454. getClearColor: function () {
  8455. return clearColor;
  8456. },
  8457. setClearColor: function ( color, alpha = 1 ) {
  8458. clearColor.set( color );
  8459. clearAlpha = alpha;
  8460. setClear( clearColor, clearAlpha );
  8461. },
  8462. getClearAlpha: function () {
  8463. return clearAlpha;
  8464. },
  8465. setClearAlpha: function ( alpha ) {
  8466. clearAlpha = alpha;
  8467. setClear( clearColor, clearAlpha );
  8468. },
  8469. render: render
  8470. };
  8471. }
  8472. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8473. const maxVertexAttributes = gl.getParameter( 34921 );
  8474. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8475. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8476. const bindingStates = {};
  8477. const defaultState = createBindingState( null );
  8478. let currentState = defaultState;
  8479. function setup( object, material, program, geometry, index ) {
  8480. let updateBuffers = false;
  8481. if ( vaoAvailable ) {
  8482. const state = getBindingState( geometry, program, material );
  8483. if ( currentState !== state ) {
  8484. currentState = state;
  8485. bindVertexArrayObject( currentState.object );
  8486. }
  8487. updateBuffers = needsUpdate( geometry, index );
  8488. if ( updateBuffers ) saveCache( geometry, index );
  8489. } else {
  8490. const wireframe = ( material.wireframe === true );
  8491. if ( currentState.geometry !== geometry.id ||
  8492. currentState.program !== program.id ||
  8493. currentState.wireframe !== wireframe ) {
  8494. currentState.geometry = geometry.id;
  8495. currentState.program = program.id;
  8496. currentState.wireframe = wireframe;
  8497. updateBuffers = true;
  8498. }
  8499. }
  8500. if ( object.isInstancedMesh === true ) {
  8501. updateBuffers = true;
  8502. }
  8503. if ( index !== null ) {
  8504. attributes.update( index, 34963 );
  8505. }
  8506. if ( updateBuffers ) {
  8507. setupVertexAttributes( object, material, program, geometry );
  8508. if ( index !== null ) {
  8509. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8510. }
  8511. }
  8512. }
  8513. function createVertexArrayObject() {
  8514. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8515. return extension.createVertexArrayOES();
  8516. }
  8517. function bindVertexArrayObject( vao ) {
  8518. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8519. return extension.bindVertexArrayOES( vao );
  8520. }
  8521. function deleteVertexArrayObject( vao ) {
  8522. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8523. return extension.deleteVertexArrayOES( vao );
  8524. }
  8525. function getBindingState( geometry, program, material ) {
  8526. const wireframe = ( material.wireframe === true );
  8527. let programMap = bindingStates[ geometry.id ];
  8528. if ( programMap === undefined ) {
  8529. programMap = {};
  8530. bindingStates[ geometry.id ] = programMap;
  8531. }
  8532. let stateMap = programMap[ program.id ];
  8533. if ( stateMap === undefined ) {
  8534. stateMap = {};
  8535. programMap[ program.id ] = stateMap;
  8536. }
  8537. let state = stateMap[ wireframe ];
  8538. if ( state === undefined ) {
  8539. state = createBindingState( createVertexArrayObject() );
  8540. stateMap[ wireframe ] = state;
  8541. }
  8542. return state;
  8543. }
  8544. function createBindingState( vao ) {
  8545. const newAttributes = [];
  8546. const enabledAttributes = [];
  8547. const attributeDivisors = [];
  8548. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8549. newAttributes[ i ] = 0;
  8550. enabledAttributes[ i ] = 0;
  8551. attributeDivisors[ i ] = 0;
  8552. }
  8553. return {
  8554. // for backward compatibility on non-VAO support browser
  8555. geometry: null,
  8556. program: null,
  8557. wireframe: false,
  8558. newAttributes: newAttributes,
  8559. enabledAttributes: enabledAttributes,
  8560. attributeDivisors: attributeDivisors,
  8561. object: vao,
  8562. attributes: {},
  8563. index: null
  8564. };
  8565. }
  8566. function needsUpdate( geometry, index ) {
  8567. const cachedAttributes = currentState.attributes;
  8568. const geometryAttributes = geometry.attributes;
  8569. let attributesNum = 0;
  8570. for ( const key in geometryAttributes ) {
  8571. const cachedAttribute = cachedAttributes[ key ];
  8572. const geometryAttribute = geometryAttributes[ key ];
  8573. if ( cachedAttribute === undefined ) return true;
  8574. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8575. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  8576. attributesNum ++;
  8577. }
  8578. if ( currentState.attributesNum !== attributesNum ) return true;
  8579. if ( currentState.index !== index ) return true;
  8580. return false;
  8581. }
  8582. function saveCache( geometry, index ) {
  8583. const cache = {};
  8584. const attributes = geometry.attributes;
  8585. let attributesNum = 0;
  8586. for ( const key in attributes ) {
  8587. const attribute = attributes[ key ];
  8588. const data = {};
  8589. data.attribute = attribute;
  8590. if ( attribute.data ) {
  8591. data.data = attribute.data;
  8592. }
  8593. cache[ key ] = data;
  8594. attributesNum ++;
  8595. }
  8596. currentState.attributes = cache;
  8597. currentState.attributesNum = attributesNum;
  8598. currentState.index = index;
  8599. }
  8600. function initAttributes() {
  8601. const newAttributes = currentState.newAttributes;
  8602. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8603. newAttributes[ i ] = 0;
  8604. }
  8605. }
  8606. function enableAttribute( attribute ) {
  8607. enableAttributeAndDivisor( attribute, 0 );
  8608. }
  8609. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8610. const newAttributes = currentState.newAttributes;
  8611. const enabledAttributes = currentState.enabledAttributes;
  8612. const attributeDivisors = currentState.attributeDivisors;
  8613. newAttributes[ attribute ] = 1;
  8614. if ( enabledAttributes[ attribute ] === 0 ) {
  8615. gl.enableVertexAttribArray( attribute );
  8616. enabledAttributes[ attribute ] = 1;
  8617. }
  8618. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8619. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8620. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8621. attributeDivisors[ attribute ] = meshPerAttribute;
  8622. }
  8623. }
  8624. function disableUnusedAttributes() {
  8625. const newAttributes = currentState.newAttributes;
  8626. const enabledAttributes = currentState.enabledAttributes;
  8627. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8628. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8629. gl.disableVertexAttribArray( i );
  8630. enabledAttributes[ i ] = 0;
  8631. }
  8632. }
  8633. }
  8634. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8635. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8636. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8637. } else {
  8638. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8639. }
  8640. }
  8641. function setupVertexAttributes( object, material, program, geometry ) {
  8642. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8643. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8644. }
  8645. initAttributes();
  8646. const geometryAttributes = geometry.attributes;
  8647. const programAttributes = program.getAttributes();
  8648. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8649. for ( const name in programAttributes ) {
  8650. const programAttribute = programAttributes[ name ];
  8651. if ( programAttribute >= 0 ) {
  8652. const geometryAttribute = geometryAttributes[ name ];
  8653. if ( geometryAttribute !== undefined ) {
  8654. const normalized = geometryAttribute.normalized;
  8655. const size = geometryAttribute.itemSize;
  8656. const attribute = attributes.get( geometryAttribute );
  8657. // TODO Attribute may not be available on context restore
  8658. if ( attribute === undefined ) continue;
  8659. const buffer = attribute.buffer;
  8660. const type = attribute.type;
  8661. const bytesPerElement = attribute.bytesPerElement;
  8662. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8663. const data = geometryAttribute.data;
  8664. const stride = data.stride;
  8665. const offset = geometryAttribute.offset;
  8666. if ( data && data.isInstancedInterleavedBuffer ) {
  8667. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  8668. if ( geometry._maxInstanceCount === undefined ) {
  8669. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8670. }
  8671. } else {
  8672. enableAttribute( programAttribute );
  8673. }
  8674. gl.bindBuffer( 34962, buffer );
  8675. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  8676. } else {
  8677. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8678. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  8679. if ( geometry._maxInstanceCount === undefined ) {
  8680. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8681. }
  8682. } else {
  8683. enableAttribute( programAttribute );
  8684. }
  8685. gl.bindBuffer( 34962, buffer );
  8686. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  8687. }
  8688. } else if ( name === 'instanceMatrix' ) {
  8689. const attribute = attributes.get( object.instanceMatrix );
  8690. // TODO Attribute may not be available on context restore
  8691. if ( attribute === undefined ) continue;
  8692. const buffer = attribute.buffer;
  8693. const type = attribute.type;
  8694. enableAttributeAndDivisor( programAttribute + 0, 1 );
  8695. enableAttributeAndDivisor( programAttribute + 1, 1 );
  8696. enableAttributeAndDivisor( programAttribute + 2, 1 );
  8697. enableAttributeAndDivisor( programAttribute + 3, 1 );
  8698. gl.bindBuffer( 34962, buffer );
  8699. gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  8700. gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  8701. gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  8702. gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  8703. } else if ( name === 'instanceColor' ) {
  8704. const attribute = attributes.get( object.instanceColor );
  8705. // TODO Attribute may not be available on context restore
  8706. if ( attribute === undefined ) continue;
  8707. const buffer = attribute.buffer;
  8708. const type = attribute.type;
  8709. enableAttributeAndDivisor( programAttribute, 1 );
  8710. gl.bindBuffer( 34962, buffer );
  8711. gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 );
  8712. } else if ( materialDefaultAttributeValues !== undefined ) {
  8713. const value = materialDefaultAttributeValues[ name ];
  8714. if ( value !== undefined ) {
  8715. switch ( value.length ) {
  8716. case 2:
  8717. gl.vertexAttrib2fv( programAttribute, value );
  8718. break;
  8719. case 3:
  8720. gl.vertexAttrib3fv( programAttribute, value );
  8721. break;
  8722. case 4:
  8723. gl.vertexAttrib4fv( programAttribute, value );
  8724. break;
  8725. default:
  8726. gl.vertexAttrib1fv( programAttribute, value );
  8727. }
  8728. }
  8729. }
  8730. }
  8731. }
  8732. disableUnusedAttributes();
  8733. }
  8734. function dispose() {
  8735. reset();
  8736. for ( const geometryId in bindingStates ) {
  8737. const programMap = bindingStates[ geometryId ];
  8738. for ( const programId in programMap ) {
  8739. const stateMap = programMap[ programId ];
  8740. for ( const wireframe in stateMap ) {
  8741. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8742. delete stateMap[ wireframe ];
  8743. }
  8744. delete programMap[ programId ];
  8745. }
  8746. delete bindingStates[ geometryId ];
  8747. }
  8748. }
  8749. function releaseStatesOfGeometry( geometry ) {
  8750. if ( bindingStates[ geometry.id ] === undefined ) return;
  8751. const programMap = bindingStates[ geometry.id ];
  8752. for ( const programId in programMap ) {
  8753. const stateMap = programMap[ programId ];
  8754. for ( const wireframe in stateMap ) {
  8755. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8756. delete stateMap[ wireframe ];
  8757. }
  8758. delete programMap[ programId ];
  8759. }
  8760. delete bindingStates[ geometry.id ];
  8761. }
  8762. function releaseStatesOfProgram( program ) {
  8763. for ( const geometryId in bindingStates ) {
  8764. const programMap = bindingStates[ geometryId ];
  8765. if ( programMap[ program.id ] === undefined ) continue;
  8766. const stateMap = programMap[ program.id ];
  8767. for ( const wireframe in stateMap ) {
  8768. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8769. delete stateMap[ wireframe ];
  8770. }
  8771. delete programMap[ program.id ];
  8772. }
  8773. }
  8774. function reset() {
  8775. resetDefaultState();
  8776. if ( currentState === defaultState ) return;
  8777. currentState = defaultState;
  8778. bindVertexArrayObject( currentState.object );
  8779. }
  8780. // for backward-compatilibity
  8781. function resetDefaultState() {
  8782. defaultState.geometry = null;
  8783. defaultState.program = null;
  8784. defaultState.wireframe = false;
  8785. }
  8786. return {
  8787. setup: setup,
  8788. reset: reset,
  8789. resetDefaultState: resetDefaultState,
  8790. dispose: dispose,
  8791. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8792. releaseStatesOfProgram: releaseStatesOfProgram,
  8793. initAttributes: initAttributes,
  8794. enableAttribute: enableAttribute,
  8795. disableUnusedAttributes: disableUnusedAttributes
  8796. };
  8797. }
  8798. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8799. const isWebGL2 = capabilities.isWebGL2;
  8800. let mode;
  8801. function setMode( value ) {
  8802. mode = value;
  8803. }
  8804. function render( start, count ) {
  8805. gl.drawArrays( mode, start, count );
  8806. info.update( count, mode, 1 );
  8807. }
  8808. function renderInstances( start, count, primcount ) {
  8809. if ( primcount === 0 ) return;
  8810. let extension, methodName;
  8811. if ( isWebGL2 ) {
  8812. extension = gl;
  8813. methodName = 'drawArraysInstanced';
  8814. } else {
  8815. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8816. methodName = 'drawArraysInstancedANGLE';
  8817. if ( extension === null ) {
  8818. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8819. return;
  8820. }
  8821. }
  8822. extension[ methodName ]( mode, start, count, primcount );
  8823. info.update( count, mode, primcount );
  8824. }
  8825. //
  8826. this.setMode = setMode;
  8827. this.render = render;
  8828. this.renderInstances = renderInstances;
  8829. }
  8830. function WebGLCapabilities( gl, extensions, parameters ) {
  8831. let maxAnisotropy;
  8832. function getMaxAnisotropy() {
  8833. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8834. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8835. if ( extension !== null ) {
  8836. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8837. } else {
  8838. maxAnisotropy = 0;
  8839. }
  8840. return maxAnisotropy;
  8841. }
  8842. function getMaxPrecision( precision ) {
  8843. if ( precision === 'highp' ) {
  8844. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8845. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8846. return 'highp';
  8847. }
  8848. precision = 'mediump';
  8849. }
  8850. if ( precision === 'mediump' ) {
  8851. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8852. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8853. return 'mediump';
  8854. }
  8855. }
  8856. return 'lowp';
  8857. }
  8858. /* eslint-disable no-undef */
  8859. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8860. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8861. /* eslint-enable no-undef */
  8862. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8863. const maxPrecision = getMaxPrecision( precision );
  8864. if ( maxPrecision !== precision ) {
  8865. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8866. precision = maxPrecision;
  8867. }
  8868. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8869. const maxTextures = gl.getParameter( 34930 );
  8870. const maxVertexTextures = gl.getParameter( 35660 );
  8871. const maxTextureSize = gl.getParameter( 3379 );
  8872. const maxCubemapSize = gl.getParameter( 34076 );
  8873. const maxAttributes = gl.getParameter( 34921 );
  8874. const maxVertexUniforms = gl.getParameter( 36347 );
  8875. const maxVaryings = gl.getParameter( 36348 );
  8876. const maxFragmentUniforms = gl.getParameter( 36349 );
  8877. const vertexTextures = maxVertexTextures > 0;
  8878. const floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  8879. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8880. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8881. return {
  8882. isWebGL2: isWebGL2,
  8883. getMaxAnisotropy: getMaxAnisotropy,
  8884. getMaxPrecision: getMaxPrecision,
  8885. precision: precision,
  8886. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8887. maxTextures: maxTextures,
  8888. maxVertexTextures: maxVertexTextures,
  8889. maxTextureSize: maxTextureSize,
  8890. maxCubemapSize: maxCubemapSize,
  8891. maxAttributes: maxAttributes,
  8892. maxVertexUniforms: maxVertexUniforms,
  8893. maxVaryings: maxVaryings,
  8894. maxFragmentUniforms: maxFragmentUniforms,
  8895. vertexTextures: vertexTextures,
  8896. floatFragmentTextures: floatFragmentTextures,
  8897. floatVertexTextures: floatVertexTextures,
  8898. maxSamples: maxSamples
  8899. };
  8900. }
  8901. function WebGLClipping( properties ) {
  8902. const scope = this;
  8903. let globalState = null,
  8904. numGlobalPlanes = 0,
  8905. localClippingEnabled = false,
  8906. renderingShadows = false;
  8907. const plane = new Plane(),
  8908. viewNormalMatrix = new Matrix3(),
  8909. uniform = { value: null, needsUpdate: false };
  8910. this.uniform = uniform;
  8911. this.numPlanes = 0;
  8912. this.numIntersection = 0;
  8913. this.init = function ( planes, enableLocalClipping, camera ) {
  8914. const enabled =
  8915. planes.length !== 0 ||
  8916. enableLocalClipping ||
  8917. // enable state of previous frame - the clipping code has to
  8918. // run another frame in order to reset the state:
  8919. numGlobalPlanes !== 0 ||
  8920. localClippingEnabled;
  8921. localClippingEnabled = enableLocalClipping;
  8922. globalState = projectPlanes( planes, camera, 0 );
  8923. numGlobalPlanes = planes.length;
  8924. return enabled;
  8925. };
  8926. this.beginShadows = function () {
  8927. renderingShadows = true;
  8928. projectPlanes( null );
  8929. };
  8930. this.endShadows = function () {
  8931. renderingShadows = false;
  8932. resetGlobalState();
  8933. };
  8934. this.setState = function ( material, camera, useCache ) {
  8935. const planes = material.clippingPlanes,
  8936. clipIntersection = material.clipIntersection,
  8937. clipShadows = material.clipShadows;
  8938. const materialProperties = properties.get( material );
  8939. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8940. // there's no local clipping
  8941. if ( renderingShadows ) {
  8942. // there's no global clipping
  8943. projectPlanes( null );
  8944. } else {
  8945. resetGlobalState();
  8946. }
  8947. } else {
  8948. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8949. lGlobal = nGlobal * 4;
  8950. let dstArray = materialProperties.clippingState || null;
  8951. uniform.value = dstArray; // ensure unique state
  8952. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8953. for ( let i = 0; i !== lGlobal; ++ i ) {
  8954. dstArray[ i ] = globalState[ i ];
  8955. }
  8956. materialProperties.clippingState = dstArray;
  8957. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8958. this.numPlanes += nGlobal;
  8959. }
  8960. };
  8961. function resetGlobalState() {
  8962. if ( uniform.value !== globalState ) {
  8963. uniform.value = globalState;
  8964. uniform.needsUpdate = numGlobalPlanes > 0;
  8965. }
  8966. scope.numPlanes = numGlobalPlanes;
  8967. scope.numIntersection = 0;
  8968. }
  8969. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8970. const nPlanes = planes !== null ? planes.length : 0;
  8971. let dstArray = null;
  8972. if ( nPlanes !== 0 ) {
  8973. dstArray = uniform.value;
  8974. if ( skipTransform !== true || dstArray === null ) {
  8975. const flatSize = dstOffset + nPlanes * 4,
  8976. viewMatrix = camera.matrixWorldInverse;
  8977. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8978. if ( dstArray === null || dstArray.length < flatSize ) {
  8979. dstArray = new Float32Array( flatSize );
  8980. }
  8981. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8982. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8983. plane.normal.toArray( dstArray, i4 );
  8984. dstArray[ i4 + 3 ] = plane.constant;
  8985. }
  8986. }
  8987. uniform.value = dstArray;
  8988. uniform.needsUpdate = true;
  8989. }
  8990. scope.numPlanes = nPlanes;
  8991. scope.numIntersection = 0;
  8992. return dstArray;
  8993. }
  8994. }
  8995. function WebGLCubeMaps( renderer ) {
  8996. let cubemaps = new WeakMap();
  8997. function mapTextureMapping( texture, mapping ) {
  8998. if ( mapping === EquirectangularReflectionMapping ) {
  8999. texture.mapping = CubeReflectionMapping;
  9000. } else if ( mapping === EquirectangularRefractionMapping ) {
  9001. texture.mapping = CubeRefractionMapping;
  9002. }
  9003. return texture;
  9004. }
  9005. function get( texture ) {
  9006. if ( texture && texture.isTexture ) {
  9007. const mapping = texture.mapping;
  9008. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9009. if ( cubemaps.has( texture ) ) {
  9010. const cubemap = cubemaps.get( texture ).texture;
  9011. return mapTextureMapping( cubemap, texture.mapping );
  9012. } else {
  9013. const image = texture.image;
  9014. if ( image && image.height > 0 ) {
  9015. const currentRenderList = renderer.getRenderList();
  9016. const currentRenderTarget = renderer.getRenderTarget();
  9017. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9018. renderTarget.fromEquirectangularTexture( renderer, texture );
  9019. cubemaps.set( texture, renderTarget );
  9020. renderer.setRenderTarget( currentRenderTarget );
  9021. renderer.setRenderList( currentRenderList );
  9022. texture.addEventListener( 'dispose', onTextureDispose );
  9023. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9024. } else {
  9025. // image not yet ready. try the conversion next frame
  9026. return null;
  9027. }
  9028. }
  9029. }
  9030. }
  9031. return texture;
  9032. }
  9033. function onTextureDispose( event ) {
  9034. const texture = event.target;
  9035. texture.removeEventListener( 'dispose', onTextureDispose );
  9036. const cubemap = cubemaps.get( texture );
  9037. if ( cubemap !== undefined ) {
  9038. cubemaps.delete( texture );
  9039. cubemap.dispose();
  9040. }
  9041. }
  9042. function dispose() {
  9043. cubemaps = new WeakMap();
  9044. }
  9045. return {
  9046. get: get,
  9047. dispose: dispose
  9048. };
  9049. }
  9050. function WebGLExtensions( gl ) {
  9051. const extensions = {};
  9052. return {
  9053. has: function ( name ) {
  9054. if ( extensions[ name ] !== undefined ) {
  9055. return extensions[ name ] !== null;
  9056. }
  9057. let extension;
  9058. switch ( name ) {
  9059. case 'WEBGL_depth_texture':
  9060. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9061. break;
  9062. case 'EXT_texture_filter_anisotropic':
  9063. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9064. break;
  9065. case 'WEBGL_compressed_texture_s3tc':
  9066. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9067. break;
  9068. case 'WEBGL_compressed_texture_pvrtc':
  9069. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9070. break;
  9071. default:
  9072. extension = gl.getExtension( name );
  9073. }
  9074. extensions[ name ] = extension;
  9075. return extension !== null;
  9076. },
  9077. get: function ( name ) {
  9078. if ( ! this.has( name ) ) {
  9079. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9080. }
  9081. return extensions[ name ];
  9082. }
  9083. };
  9084. }
  9085. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9086. const geometries = new WeakMap();
  9087. const wireframeAttributes = new WeakMap();
  9088. function onGeometryDispose( event ) {
  9089. const geometry = event.target;
  9090. const buffergeometry = geometries.get( geometry );
  9091. if ( buffergeometry.index !== null ) {
  9092. attributes.remove( buffergeometry.index );
  9093. }
  9094. for ( const name in buffergeometry.attributes ) {
  9095. attributes.remove( buffergeometry.attributes[ name ] );
  9096. }
  9097. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9098. geometries.delete( geometry );
  9099. const attribute = wireframeAttributes.get( buffergeometry );
  9100. if ( attribute ) {
  9101. attributes.remove( attribute );
  9102. wireframeAttributes.delete( buffergeometry );
  9103. }
  9104. bindingStates.releaseStatesOfGeometry( buffergeometry );
  9105. if ( geometry.isInstancedBufferGeometry === true ) {
  9106. delete geometry._maxInstanceCount;
  9107. }
  9108. //
  9109. info.memory.geometries --;
  9110. }
  9111. function get( object, geometry ) {
  9112. let buffergeometry = geometries.get( geometry );
  9113. if ( buffergeometry ) return buffergeometry;
  9114. geometry.addEventListener( 'dispose', onGeometryDispose );
  9115. if ( geometry.isBufferGeometry ) {
  9116. buffergeometry = geometry;
  9117. } else if ( geometry.isGeometry ) {
  9118. if ( geometry._bufferGeometry === undefined ) {
  9119. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9120. }
  9121. buffergeometry = geometry._bufferGeometry;
  9122. }
  9123. geometries.set( geometry, buffergeometry );
  9124. info.memory.geometries ++;
  9125. return buffergeometry;
  9126. }
  9127. function update( geometry ) {
  9128. const geometryAttributes = geometry.attributes;
  9129. // Updating index buffer in VAO now. See WebGLBindingStates.
  9130. for ( const name in geometryAttributes ) {
  9131. attributes.update( geometryAttributes[ name ], 34962 );
  9132. }
  9133. // morph targets
  9134. const morphAttributes = geometry.morphAttributes;
  9135. for ( const name in morphAttributes ) {
  9136. const array = morphAttributes[ name ];
  9137. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9138. attributes.update( array[ i ], 34962 );
  9139. }
  9140. }
  9141. }
  9142. function updateWireframeAttribute( geometry ) {
  9143. const indices = [];
  9144. const geometryIndex = geometry.index;
  9145. const geometryPosition = geometry.attributes.position;
  9146. let version = 0;
  9147. if ( geometryIndex !== null ) {
  9148. const array = geometryIndex.array;
  9149. version = geometryIndex.version;
  9150. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9151. const a = array[ i + 0 ];
  9152. const b = array[ i + 1 ];
  9153. const c = array[ i + 2 ];
  9154. indices.push( a, b, b, c, c, a );
  9155. }
  9156. } else {
  9157. const array = geometryPosition.array;
  9158. version = geometryPosition.version;
  9159. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9160. const a = i + 0;
  9161. const b = i + 1;
  9162. const c = i + 2;
  9163. indices.push( a, b, b, c, c, a );
  9164. }
  9165. }
  9166. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9167. attribute.version = version;
  9168. // Updating index buffer in VAO now. See WebGLBindingStates
  9169. //
  9170. const previousAttribute = wireframeAttributes.get( geometry );
  9171. if ( previousAttribute ) attributes.remove( previousAttribute );
  9172. //
  9173. wireframeAttributes.set( geometry, attribute );
  9174. }
  9175. function getWireframeAttribute( geometry ) {
  9176. const currentAttribute = wireframeAttributes.get( geometry );
  9177. if ( currentAttribute ) {
  9178. const geometryIndex = geometry.index;
  9179. if ( geometryIndex !== null ) {
  9180. // if the attribute is obsolete, create a new one
  9181. if ( currentAttribute.version < geometryIndex.version ) {
  9182. updateWireframeAttribute( geometry );
  9183. }
  9184. }
  9185. } else {
  9186. updateWireframeAttribute( geometry );
  9187. }
  9188. return wireframeAttributes.get( geometry );
  9189. }
  9190. return {
  9191. get: get,
  9192. update: update,
  9193. getWireframeAttribute: getWireframeAttribute
  9194. };
  9195. }
  9196. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9197. const isWebGL2 = capabilities.isWebGL2;
  9198. let mode;
  9199. function setMode( value ) {
  9200. mode = value;
  9201. }
  9202. let type, bytesPerElement;
  9203. function setIndex( value ) {
  9204. type = value.type;
  9205. bytesPerElement = value.bytesPerElement;
  9206. }
  9207. function render( start, count ) {
  9208. gl.drawElements( mode, count, type, start * bytesPerElement );
  9209. info.update( count, mode, 1 );
  9210. }
  9211. function renderInstances( start, count, primcount ) {
  9212. if ( primcount === 0 ) return;
  9213. let extension, methodName;
  9214. if ( isWebGL2 ) {
  9215. extension = gl;
  9216. methodName = 'drawElementsInstanced';
  9217. } else {
  9218. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9219. methodName = 'drawElementsInstancedANGLE';
  9220. if ( extension === null ) {
  9221. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9222. return;
  9223. }
  9224. }
  9225. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9226. info.update( count, mode, primcount );
  9227. }
  9228. //
  9229. this.setMode = setMode;
  9230. this.setIndex = setIndex;
  9231. this.render = render;
  9232. this.renderInstances = renderInstances;
  9233. }
  9234. function WebGLInfo( gl ) {
  9235. const memory = {
  9236. geometries: 0,
  9237. textures: 0
  9238. };
  9239. const render = {
  9240. frame: 0,
  9241. calls: 0,
  9242. triangles: 0,
  9243. points: 0,
  9244. lines: 0
  9245. };
  9246. function update( count, mode, instanceCount ) {
  9247. render.calls ++;
  9248. switch ( mode ) {
  9249. case 4:
  9250. render.triangles += instanceCount * ( count / 3 );
  9251. break;
  9252. case 1:
  9253. render.lines += instanceCount * ( count / 2 );
  9254. break;
  9255. case 3:
  9256. render.lines += instanceCount * ( count - 1 );
  9257. break;
  9258. case 2:
  9259. render.lines += instanceCount * count;
  9260. break;
  9261. case 0:
  9262. render.points += instanceCount * count;
  9263. break;
  9264. default:
  9265. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  9266. break;
  9267. }
  9268. }
  9269. function reset() {
  9270. render.frame ++;
  9271. render.calls = 0;
  9272. render.triangles = 0;
  9273. render.points = 0;
  9274. render.lines = 0;
  9275. }
  9276. return {
  9277. memory: memory,
  9278. render: render,
  9279. programs: null,
  9280. autoReset: true,
  9281. reset: reset,
  9282. update: update
  9283. };
  9284. }
  9285. function numericalSort( a, b ) {
  9286. return a[ 0 ] - b[ 0 ];
  9287. }
  9288. function absNumericalSort( a, b ) {
  9289. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  9290. }
  9291. function WebGLMorphtargets( gl ) {
  9292. const influencesList = {};
  9293. const morphInfluences = new Float32Array( 8 );
  9294. const workInfluences = [];
  9295. for ( let i = 0; i < 8; i ++ ) {
  9296. workInfluences[ i ] = [ i, 0 ];
  9297. }
  9298. function update( object, geometry, material, program ) {
  9299. const objectInfluences = object.morphTargetInfluences;
  9300. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9301. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9302. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9303. let influences = influencesList[ geometry.id ];
  9304. if ( influences === undefined ) {
  9305. // initialise list
  9306. influences = [];
  9307. for ( let i = 0; i < length; i ++ ) {
  9308. influences[ i ] = [ i, 0 ];
  9309. }
  9310. influencesList[ geometry.id ] = influences;
  9311. }
  9312. // Collect influences
  9313. for ( let i = 0; i < length; i ++ ) {
  9314. const influence = influences[ i ];
  9315. influence[ 0 ] = i;
  9316. influence[ 1 ] = objectInfluences[ i ];
  9317. }
  9318. influences.sort( absNumericalSort );
  9319. for ( let i = 0; i < 8; i ++ ) {
  9320. if ( i < length && influences[ i ][ 1 ] ) {
  9321. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  9322. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  9323. } else {
  9324. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  9325. workInfluences[ i ][ 1 ] = 0;
  9326. }
  9327. }
  9328. workInfluences.sort( numericalSort );
  9329. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9330. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9331. let morphInfluencesSum = 0;
  9332. for ( let i = 0; i < 8; i ++ ) {
  9333. const influence = workInfluences[ i ];
  9334. const index = influence[ 0 ];
  9335. const value = influence[ 1 ];
  9336. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  9337. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  9338. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  9339. }
  9340. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  9341. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  9342. }
  9343. morphInfluences[ i ] = value;
  9344. morphInfluencesSum += value;
  9345. } else {
  9346. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  9347. geometry.deleteAttribute( 'morphTarget' + i );
  9348. }
  9349. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  9350. geometry.deleteAttribute( 'morphNormal' + i );
  9351. }
  9352. morphInfluences[ i ] = 0;
  9353. }
  9354. }
  9355. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9356. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9357. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9358. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9359. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  9360. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  9361. }
  9362. return {
  9363. update: update
  9364. };
  9365. }
  9366. function WebGLObjects( gl, geometries, attributes, info ) {
  9367. let updateMap = new WeakMap();
  9368. function update( object ) {
  9369. const frame = info.render.frame;
  9370. const geometry = object.geometry;
  9371. const buffergeometry = geometries.get( object, geometry );
  9372. // Update once per frame
  9373. if ( updateMap.get( buffergeometry ) !== frame ) {
  9374. if ( geometry.isGeometry ) {
  9375. buffergeometry.updateFromObject( object );
  9376. }
  9377. geometries.update( buffergeometry );
  9378. updateMap.set( buffergeometry, frame );
  9379. }
  9380. if ( object.isInstancedMesh ) {
  9381. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  9382. object.addEventListener( 'dispose', onInstancedMeshDispose );
  9383. }
  9384. attributes.update( object.instanceMatrix, 34962 );
  9385. if ( object.instanceColor !== null ) {
  9386. attributes.update( object.instanceColor, 34962 );
  9387. }
  9388. }
  9389. return buffergeometry;
  9390. }
  9391. function dispose() {
  9392. updateMap = new WeakMap();
  9393. }
  9394. function onInstancedMeshDispose( event ) {
  9395. const instancedMesh = event.target;
  9396. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  9397. attributes.remove( instancedMesh.instanceMatrix );
  9398. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  9399. }
  9400. return {
  9401. update: update,
  9402. dispose: dispose
  9403. };
  9404. }
  9405. function DataTexture2DArray( data = null, width = 1, height = 1, depth = 1 ) {
  9406. Texture.call( this, null );
  9407. this.image = { data, width, height, depth };
  9408. this.magFilter = NearestFilter;
  9409. this.minFilter = NearestFilter;
  9410. this.wrapR = ClampToEdgeWrapping;
  9411. this.generateMipmaps = false;
  9412. this.flipY = false;
  9413. this.needsUpdate = true;
  9414. }
  9415. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  9416. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  9417. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9418. function DataTexture3D( data = null, width = 1, height = 1, depth = 1 ) {
  9419. // We're going to add .setXXX() methods for setting properties later.
  9420. // Users can still set in DataTexture3D directly.
  9421. //
  9422. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9423. // texture.anisotropy = 16;
  9424. //
  9425. // See #14839
  9426. Texture.call( this, null );
  9427. this.image = { data, width, height, depth };
  9428. this.magFilter = NearestFilter;
  9429. this.minFilter = NearestFilter;
  9430. this.wrapR = ClampToEdgeWrapping;
  9431. this.generateMipmaps = false;
  9432. this.flipY = false;
  9433. this.needsUpdate = true;
  9434. }
  9435. DataTexture3D.prototype = Object.create( Texture.prototype );
  9436. DataTexture3D.prototype.constructor = DataTexture3D;
  9437. DataTexture3D.prototype.isDataTexture3D = true;
  9438. /**
  9439. * Uniforms of a program.
  9440. * Those form a tree structure with a special top-level container for the root,
  9441. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9442. *
  9443. *
  9444. * Properties of inner nodes including the top-level container:
  9445. *
  9446. * .seq - array of nested uniforms
  9447. * .map - nested uniforms by name
  9448. *
  9449. *
  9450. * Methods of all nodes except the top-level container:
  9451. *
  9452. * .setValue( gl, value, [textures] )
  9453. *
  9454. * uploads a uniform value(s)
  9455. * the 'textures' parameter is needed for sampler uniforms
  9456. *
  9457. *
  9458. * Static methods of the top-level container (textures factorizations):
  9459. *
  9460. * .upload( gl, seq, values, textures )
  9461. *
  9462. * sets uniforms in 'seq' to 'values[id].value'
  9463. *
  9464. * .seqWithValue( seq, values ) : filteredSeq
  9465. *
  9466. * filters 'seq' entries with corresponding entry in values
  9467. *
  9468. *
  9469. * Methods of the top-level container (textures factorizations):
  9470. *
  9471. * .setValue( gl, name, value, textures )
  9472. *
  9473. * sets uniform with name 'name' to 'value'
  9474. *
  9475. * .setOptional( gl, obj, prop )
  9476. *
  9477. * like .set for an optional property of the object
  9478. *
  9479. */
  9480. const emptyTexture = new Texture();
  9481. const emptyTexture2dArray = new DataTexture2DArray();
  9482. const emptyTexture3d = new DataTexture3D();
  9483. const emptyCubeTexture = new CubeTexture();
  9484. // --- Utilities ---
  9485. // Array Caches (provide typed arrays for temporary by size)
  9486. const arrayCacheF32 = [];
  9487. const arrayCacheI32 = [];
  9488. // Float32Array caches used for uploading Matrix uniforms
  9489. const mat4array = new Float32Array( 16 );
  9490. const mat3array = new Float32Array( 9 );
  9491. const mat2array = new Float32Array( 4 );
  9492. // Flattening for arrays of vectors and matrices
  9493. function flatten( array, nBlocks, blockSize ) {
  9494. const firstElem = array[ 0 ];
  9495. if ( firstElem <= 0 || firstElem > 0 ) return array;
  9496. // unoptimized: ! isNaN( firstElem )
  9497. // see http://jacksondunstan.com/articles/983
  9498. const n = nBlocks * blockSize;
  9499. let r = arrayCacheF32[ n ];
  9500. if ( r === undefined ) {
  9501. r = new Float32Array( n );
  9502. arrayCacheF32[ n ] = r;
  9503. }
  9504. if ( nBlocks !== 0 ) {
  9505. firstElem.toArray( r, 0 );
  9506. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  9507. offset += blockSize;
  9508. array[ i ].toArray( r, offset );
  9509. }
  9510. }
  9511. return r;
  9512. }
  9513. function arraysEqual( a, b ) {
  9514. if ( a.length !== b.length ) return false;
  9515. for ( let i = 0, l = a.length; i < l; i ++ ) {
  9516. if ( a[ i ] !== b[ i ] ) return false;
  9517. }
  9518. return true;
  9519. }
  9520. function copyArray( a, b ) {
  9521. for ( let i = 0, l = b.length; i < l; i ++ ) {
  9522. a[ i ] = b[ i ];
  9523. }
  9524. }
  9525. // Texture unit allocation
  9526. function allocTexUnits( textures, n ) {
  9527. let r = arrayCacheI32[ n ];
  9528. if ( r === undefined ) {
  9529. r = new Int32Array( n );
  9530. arrayCacheI32[ n ] = r;
  9531. }
  9532. for ( let i = 0; i !== n; ++ i ) {
  9533. r[ i ] = textures.allocateTextureUnit();
  9534. }
  9535. return r;
  9536. }
  9537. // --- Setters ---
  9538. // Note: Defining these methods externally, because they come in a bunch
  9539. // and this way their names minify.
  9540. // Single scalar
  9541. function setValueV1f( gl, v ) {
  9542. const cache = this.cache;
  9543. if ( cache[ 0 ] === v ) return;
  9544. gl.uniform1f( this.addr, v );
  9545. cache[ 0 ] = v;
  9546. }
  9547. // Single float vector (from flat array or THREE.VectorN)
  9548. function setValueV2f( gl, v ) {
  9549. const cache = this.cache;
  9550. if ( v.x !== undefined ) {
  9551. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  9552. gl.uniform2f( this.addr, v.x, v.y );
  9553. cache[ 0 ] = v.x;
  9554. cache[ 1 ] = v.y;
  9555. }
  9556. } else {
  9557. if ( arraysEqual( cache, v ) ) return;
  9558. gl.uniform2fv( this.addr, v );
  9559. copyArray( cache, v );
  9560. }
  9561. }
  9562. function setValueV3f( gl, v ) {
  9563. const cache = this.cache;
  9564. if ( v.x !== undefined ) {
  9565. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  9566. gl.uniform3f( this.addr, v.x, v.y, v.z );
  9567. cache[ 0 ] = v.x;
  9568. cache[ 1 ] = v.y;
  9569. cache[ 2 ] = v.z;
  9570. }
  9571. } else if ( v.r !== undefined ) {
  9572. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  9573. gl.uniform3f( this.addr, v.r, v.g, v.b );
  9574. cache[ 0 ] = v.r;
  9575. cache[ 1 ] = v.g;
  9576. cache[ 2 ] = v.b;
  9577. }
  9578. } else {
  9579. if ( arraysEqual( cache, v ) ) return;
  9580. gl.uniform3fv( this.addr, v );
  9581. copyArray( cache, v );
  9582. }
  9583. }
  9584. function setValueV4f( gl, v ) {
  9585. const cache = this.cache;
  9586. if ( v.x !== undefined ) {
  9587. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  9588. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  9589. cache[ 0 ] = v.x;
  9590. cache[ 1 ] = v.y;
  9591. cache[ 2 ] = v.z;
  9592. cache[ 3 ] = v.w;
  9593. }
  9594. } else {
  9595. if ( arraysEqual( cache, v ) ) return;
  9596. gl.uniform4fv( this.addr, v );
  9597. copyArray( cache, v );
  9598. }
  9599. }
  9600. // Single matrix (from flat array or MatrixN)
  9601. function setValueM2( gl, v ) {
  9602. const cache = this.cache;
  9603. const elements = v.elements;
  9604. if ( elements === undefined ) {
  9605. if ( arraysEqual( cache, v ) ) return;
  9606. gl.uniformMatrix2fv( this.addr, false, v );
  9607. copyArray( cache, v );
  9608. } else {
  9609. if ( arraysEqual( cache, elements ) ) return;
  9610. mat2array.set( elements );
  9611. gl.uniformMatrix2fv( this.addr, false, mat2array );
  9612. copyArray( cache, elements );
  9613. }
  9614. }
  9615. function setValueM3( gl, v ) {
  9616. const cache = this.cache;
  9617. const elements = v.elements;
  9618. if ( elements === undefined ) {
  9619. if ( arraysEqual( cache, v ) ) return;
  9620. gl.uniformMatrix3fv( this.addr, false, v );
  9621. copyArray( cache, v );
  9622. } else {
  9623. if ( arraysEqual( cache, elements ) ) return;
  9624. mat3array.set( elements );
  9625. gl.uniformMatrix3fv( this.addr, false, mat3array );
  9626. copyArray( cache, elements );
  9627. }
  9628. }
  9629. function setValueM4( gl, v ) {
  9630. const cache = this.cache;
  9631. const elements = v.elements;
  9632. if ( elements === undefined ) {
  9633. if ( arraysEqual( cache, v ) ) return;
  9634. gl.uniformMatrix4fv( this.addr, false, v );
  9635. copyArray( cache, v );
  9636. } else {
  9637. if ( arraysEqual( cache, elements ) ) return;
  9638. mat4array.set( elements );
  9639. gl.uniformMatrix4fv( this.addr, false, mat4array );
  9640. copyArray( cache, elements );
  9641. }
  9642. }
  9643. // Single texture (2D / Cube)
  9644. function setValueT1( gl, v, textures ) {
  9645. const cache = this.cache;
  9646. const unit = textures.allocateTextureUnit();
  9647. if ( cache[ 0 ] !== unit ) {
  9648. gl.uniform1i( this.addr, unit );
  9649. cache[ 0 ] = unit;
  9650. }
  9651. textures.safeSetTexture2D( v || emptyTexture, unit );
  9652. }
  9653. function setValueT2DArray1( gl, v, textures ) {
  9654. const cache = this.cache;
  9655. const unit = textures.allocateTextureUnit();
  9656. if ( cache[ 0 ] !== unit ) {
  9657. gl.uniform1i( this.addr, unit );
  9658. cache[ 0 ] = unit;
  9659. }
  9660. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  9661. }
  9662. function setValueT3D1( gl, v, textures ) {
  9663. const cache = this.cache;
  9664. const unit = textures.allocateTextureUnit();
  9665. if ( cache[ 0 ] !== unit ) {
  9666. gl.uniform1i( this.addr, unit );
  9667. cache[ 0 ] = unit;
  9668. }
  9669. textures.setTexture3D( v || emptyTexture3d, unit );
  9670. }
  9671. function setValueT6( gl, v, textures ) {
  9672. const cache = this.cache;
  9673. const unit = textures.allocateTextureUnit();
  9674. if ( cache[ 0 ] !== unit ) {
  9675. gl.uniform1i( this.addr, unit );
  9676. cache[ 0 ] = unit;
  9677. }
  9678. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  9679. }
  9680. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  9681. function setValueV1i( gl, v ) {
  9682. const cache = this.cache;
  9683. if ( cache[ 0 ] === v ) return;
  9684. gl.uniform1i( this.addr, v );
  9685. cache[ 0 ] = v;
  9686. }
  9687. function setValueV2i( gl, v ) {
  9688. const cache = this.cache;
  9689. if ( arraysEqual( cache, v ) ) return;
  9690. gl.uniform2iv( this.addr, v );
  9691. copyArray( cache, v );
  9692. }
  9693. function setValueV3i( gl, v ) {
  9694. const cache = this.cache;
  9695. if ( arraysEqual( cache, v ) ) return;
  9696. gl.uniform3iv( this.addr, v );
  9697. copyArray( cache, v );
  9698. }
  9699. function setValueV4i( gl, v ) {
  9700. const cache = this.cache;
  9701. if ( arraysEqual( cache, v ) ) return;
  9702. gl.uniform4iv( this.addr, v );
  9703. copyArray( cache, v );
  9704. }
  9705. // uint
  9706. function setValueV1ui( gl, v ) {
  9707. const cache = this.cache;
  9708. if ( cache[ 0 ] === v ) return;
  9709. gl.uniform1ui( this.addr, v );
  9710. cache[ 0 ] = v;
  9711. }
  9712. // Helper to pick the right setter for the singular case
  9713. function getSingularSetter( type ) {
  9714. switch ( type ) {
  9715. case 0x1406: return setValueV1f; // FLOAT
  9716. case 0x8b50: return setValueV2f; // _VEC2
  9717. case 0x8b51: return setValueV3f; // _VEC3
  9718. case 0x8b52: return setValueV4f; // _VEC4
  9719. case 0x8b5a: return setValueM2; // _MAT2
  9720. case 0x8b5b: return setValueM3; // _MAT3
  9721. case 0x8b5c: return setValueM4; // _MAT4
  9722. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  9723. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  9724. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  9725. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  9726. case 0x1405: return setValueV1ui; // UINT
  9727. case 0x8b5e: // SAMPLER_2D
  9728. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9729. case 0x8dca: // INT_SAMPLER_2D
  9730. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9731. case 0x8b62: // SAMPLER_2D_SHADOW
  9732. return setValueT1;
  9733. case 0x8b5f: // SAMPLER_3D
  9734. case 0x8dcb: // INT_SAMPLER_3D
  9735. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  9736. return setValueT3D1;
  9737. case 0x8b60: // SAMPLER_CUBE
  9738. case 0x8dcc: // INT_SAMPLER_CUBE
  9739. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9740. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  9741. return setValueT6;
  9742. case 0x8dc1: // SAMPLER_2D_ARRAY
  9743. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  9744. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  9745. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  9746. return setValueT2DArray1;
  9747. }
  9748. }
  9749. // Array of scalars
  9750. function setValueV1fArray( gl, v ) {
  9751. gl.uniform1fv( this.addr, v );
  9752. }
  9753. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  9754. function setValueV1iArray( gl, v ) {
  9755. gl.uniform1iv( this.addr, v );
  9756. }
  9757. function setValueV2iArray( gl, v ) {
  9758. gl.uniform2iv( this.addr, v );
  9759. }
  9760. function setValueV3iArray( gl, v ) {
  9761. gl.uniform3iv( this.addr, v );
  9762. }
  9763. function setValueV4iArray( gl, v ) {
  9764. gl.uniform4iv( this.addr, v );
  9765. }
  9766. // Array of vectors (flat or from THREE classes)
  9767. function setValueV2fArray( gl, v ) {
  9768. const data = flatten( v, this.size, 2 );
  9769. gl.uniform2fv( this.addr, data );
  9770. }
  9771. function setValueV3fArray( gl, v ) {
  9772. const data = flatten( v, this.size, 3 );
  9773. gl.uniform3fv( this.addr, data );
  9774. }
  9775. function setValueV4fArray( gl, v ) {
  9776. const data = flatten( v, this.size, 4 );
  9777. gl.uniform4fv( this.addr, data );
  9778. }
  9779. // Array of matrices (flat or from THREE clases)
  9780. function setValueM2Array( gl, v ) {
  9781. const data = flatten( v, this.size, 4 );
  9782. gl.uniformMatrix2fv( this.addr, false, data );
  9783. }
  9784. function setValueM3Array( gl, v ) {
  9785. const data = flatten( v, this.size, 9 );
  9786. gl.uniformMatrix3fv( this.addr, false, data );
  9787. }
  9788. function setValueM4Array( gl, v ) {
  9789. const data = flatten( v, this.size, 16 );
  9790. gl.uniformMatrix4fv( this.addr, false, data );
  9791. }
  9792. // Array of textures (2D / Cube)
  9793. function setValueT1Array( gl, v, textures ) {
  9794. const n = v.length;
  9795. const units = allocTexUnits( textures, n );
  9796. gl.uniform1iv( this.addr, units );
  9797. for ( let i = 0; i !== n; ++ i ) {
  9798. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  9799. }
  9800. }
  9801. function setValueT6Array( gl, v, textures ) {
  9802. const n = v.length;
  9803. const units = allocTexUnits( textures, n );
  9804. gl.uniform1iv( this.addr, units );
  9805. for ( let i = 0; i !== n; ++ i ) {
  9806. textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  9807. }
  9808. }
  9809. // Helper to pick the right setter for a pure (bottom-level) array
  9810. function getPureArraySetter( type ) {
  9811. switch ( type ) {
  9812. case 0x1406: return setValueV1fArray; // FLOAT
  9813. case 0x8b50: return setValueV2fArray; // _VEC2
  9814. case 0x8b51: return setValueV3fArray; // _VEC3
  9815. case 0x8b52: return setValueV4fArray; // _VEC4
  9816. case 0x8b5a: return setValueM2Array; // _MAT2
  9817. case 0x8b5b: return setValueM3Array; // _MAT3
  9818. case 0x8b5c: return setValueM4Array; // _MAT4
  9819. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  9820. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  9821. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  9822. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  9823. case 0x8b5e: // SAMPLER_2D
  9824. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9825. case 0x8dca: // INT_SAMPLER_2D
  9826. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9827. case 0x8b62: // SAMPLER_2D_SHADOW
  9828. return setValueT1Array;
  9829. case 0x8b60: // SAMPLER_CUBE
  9830. case 0x8dcc: // INT_SAMPLER_CUBE
  9831. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9832. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  9833. return setValueT6Array;
  9834. }
  9835. }
  9836. // --- Uniform Classes ---
  9837. function SingleUniform( id, activeInfo, addr ) {
  9838. this.id = id;
  9839. this.addr = addr;
  9840. this.cache = [];
  9841. this.setValue = getSingularSetter( activeInfo.type );
  9842. // this.path = activeInfo.name; // DEBUG
  9843. }
  9844. function PureArrayUniform( id, activeInfo, addr ) {
  9845. this.id = id;
  9846. this.addr = addr;
  9847. this.cache = [];
  9848. this.size = activeInfo.size;
  9849. this.setValue = getPureArraySetter( activeInfo.type );
  9850. // this.path = activeInfo.name; // DEBUG
  9851. }
  9852. PureArrayUniform.prototype.updateCache = function ( data ) {
  9853. const cache = this.cache;
  9854. if ( data instanceof Float32Array && cache.length !== data.length ) {
  9855. this.cache = new Float32Array( data.length );
  9856. }
  9857. copyArray( cache, data );
  9858. };
  9859. function StructuredUniform( id ) {
  9860. this.id = id;
  9861. this.seq = [];
  9862. this.map = {};
  9863. }
  9864. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  9865. const seq = this.seq;
  9866. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9867. const u = seq[ i ];
  9868. u.setValue( gl, value[ u.id ], textures );
  9869. }
  9870. };
  9871. // --- Top-level ---
  9872. // Parser - builds up the property tree from the path strings
  9873. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  9874. // extracts
  9875. // - the identifier (member name or array index)
  9876. // - followed by an optional right bracket (found when array index)
  9877. // - followed by an optional left bracket or dot (type of subscript)
  9878. //
  9879. // Note: These portions can be read in a non-overlapping fashion and
  9880. // allow straightforward parsing of the hierarchy that WebGL encodes
  9881. // in the uniform names.
  9882. function addUniform( container, uniformObject ) {
  9883. container.seq.push( uniformObject );
  9884. container.map[ uniformObject.id ] = uniformObject;
  9885. }
  9886. function parseUniform( activeInfo, addr, container ) {
  9887. const path = activeInfo.name,
  9888. pathLength = path.length;
  9889. // reset RegExp object, because of the early exit of a previous run
  9890. RePathPart.lastIndex = 0;
  9891. while ( true ) {
  9892. const match = RePathPart.exec( path ),
  9893. matchEnd = RePathPart.lastIndex;
  9894. let id = match[ 1 ];
  9895. const idIsIndex = match[ 2 ] === ']',
  9896. subscript = match[ 3 ];
  9897. if ( idIsIndex ) id = id | 0; // convert to integer
  9898. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  9899. // bare name or "pure" bottom-level array "[0]" suffix
  9900. addUniform( container, subscript === undefined ?
  9901. new SingleUniform( id, activeInfo, addr ) :
  9902. new PureArrayUniform( id, activeInfo, addr ) );
  9903. break;
  9904. } else {
  9905. // step into inner node / create it in case it doesn't exist
  9906. const map = container.map;
  9907. let next = map[ id ];
  9908. if ( next === undefined ) {
  9909. next = new StructuredUniform( id );
  9910. addUniform( container, next );
  9911. }
  9912. container = next;
  9913. }
  9914. }
  9915. }
  9916. // Root Container
  9917. function WebGLUniforms( gl, program ) {
  9918. this.seq = [];
  9919. this.map = {};
  9920. const n = gl.getProgramParameter( program, 35718 );
  9921. for ( let i = 0; i < n; ++ i ) {
  9922. const info = gl.getActiveUniform( program, i ),
  9923. addr = gl.getUniformLocation( program, info.name );
  9924. parseUniform( info, addr, this );
  9925. }
  9926. }
  9927. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  9928. const u = this.map[ name ];
  9929. if ( u !== undefined ) u.setValue( gl, value, textures );
  9930. };
  9931. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  9932. const v = object[ name ];
  9933. if ( v !== undefined ) this.setValue( gl, name, v );
  9934. };
  9935. // Static interface
  9936. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  9937. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9938. const u = seq[ i ],
  9939. v = values[ u.id ];
  9940. if ( v.needsUpdate !== false ) {
  9941. // note: always updating when .needsUpdate is undefined
  9942. u.setValue( gl, v.value, textures );
  9943. }
  9944. }
  9945. };
  9946. WebGLUniforms.seqWithValue = function ( seq, values ) {
  9947. const r = [];
  9948. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  9949. const u = seq[ i ];
  9950. if ( u.id in values ) r.push( u );
  9951. }
  9952. return r;
  9953. };
  9954. function WebGLShader( gl, type, string ) {
  9955. const shader = gl.createShader( type );
  9956. gl.shaderSource( shader, string );
  9957. gl.compileShader( shader );
  9958. return shader;
  9959. }
  9960. let programIdCount = 0;
  9961. function addLineNumbers( string ) {
  9962. const lines = string.split( '\n' );
  9963. for ( let i = 0; i < lines.length; i ++ ) {
  9964. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  9965. }
  9966. return lines.join( '\n' );
  9967. }
  9968. function getEncodingComponents( encoding ) {
  9969. switch ( encoding ) {
  9970. case LinearEncoding:
  9971. return [ 'Linear', '( value )' ];
  9972. case sRGBEncoding:
  9973. return [ 'sRGB', '( value )' ];
  9974. case RGBEEncoding:
  9975. return [ 'RGBE', '( value )' ];
  9976. case RGBM7Encoding:
  9977. return [ 'RGBM', '( value, 7.0 )' ];
  9978. case RGBM16Encoding:
  9979. return [ 'RGBM', '( value, 16.0 )' ];
  9980. case RGBDEncoding:
  9981. return [ 'RGBD', '( value, 256.0 )' ];
  9982. case GammaEncoding:
  9983. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  9984. case LogLuvEncoding:
  9985. return [ 'LogLuv', '( value )' ];
  9986. default:
  9987. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  9988. return [ 'Linear', '( value )' ];
  9989. }
  9990. }
  9991. function getShaderErrors( gl, shader, type ) {
  9992. const status = gl.getShaderParameter( shader, 35713 );
  9993. const log = gl.getShaderInfoLog( shader ).trim();
  9994. if ( status && log === '' ) return '';
  9995. // --enable-privileged-webgl-extension
  9996. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  9997. const source = gl.getShaderSource( shader );
  9998. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  9999. }
  10000. function getTexelDecodingFunction( functionName, encoding ) {
  10001. const components = getEncodingComponents( encoding );
  10002. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  10003. }
  10004. function getTexelEncodingFunction( functionName, encoding ) {
  10005. const components = getEncodingComponents( encoding );
  10006. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10007. }
  10008. function getToneMappingFunction( functionName, toneMapping ) {
  10009. let toneMappingName;
  10010. switch ( toneMapping ) {
  10011. case LinearToneMapping:
  10012. toneMappingName = 'Linear';
  10013. break;
  10014. case ReinhardToneMapping:
  10015. toneMappingName = 'Reinhard';
  10016. break;
  10017. case CineonToneMapping:
  10018. toneMappingName = 'OptimizedCineon';
  10019. break;
  10020. case ACESFilmicToneMapping:
  10021. toneMappingName = 'ACESFilmic';
  10022. break;
  10023. case CustomToneMapping:
  10024. toneMappingName = 'Custom';
  10025. break;
  10026. default:
  10027. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10028. toneMappingName = 'Linear';
  10029. }
  10030. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10031. }
  10032. function generateExtensions( parameters ) {
  10033. const chunks = [
  10034. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10035. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10036. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10037. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10038. ];
  10039. return chunks.filter( filterEmptyLine ).join( '\n' );
  10040. }
  10041. function generateDefines( defines ) {
  10042. const chunks = [];
  10043. for ( const name in defines ) {
  10044. const value = defines[ name ];
  10045. if ( value === false ) continue;
  10046. chunks.push( '#define ' + name + ' ' + value );
  10047. }
  10048. return chunks.join( '\n' );
  10049. }
  10050. function fetchAttributeLocations( gl, program ) {
  10051. const attributes = {};
  10052. const n = gl.getProgramParameter( program, 35721 );
  10053. for ( let i = 0; i < n; i ++ ) {
  10054. const info = gl.getActiveAttrib( program, i );
  10055. const name = info.name;
  10056. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10057. attributes[ name ] = gl.getAttribLocation( program, name );
  10058. }
  10059. return attributes;
  10060. }
  10061. function filterEmptyLine( string ) {
  10062. return string !== '';
  10063. }
  10064. function replaceLightNums( string, parameters ) {
  10065. return string
  10066. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10067. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10068. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10069. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10070. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10071. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10072. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10073. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10074. }
  10075. function replaceClippingPlaneNums( string, parameters ) {
  10076. return string
  10077. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10078. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10079. }
  10080. // Resolve Includes
  10081. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10082. function resolveIncludes( string ) {
  10083. return string.replace( includePattern, includeReplacer );
  10084. }
  10085. function includeReplacer( match, include ) {
  10086. const string = ShaderChunk[ include ];
  10087. if ( string === undefined ) {
  10088. throw new Error( 'Can not resolve #include <' + include + '>' );
  10089. }
  10090. return resolveIncludes( string );
  10091. }
  10092. // Unroll Loops
  10093. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10094. const 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;
  10095. function unrollLoops( string ) {
  10096. return string
  10097. .replace( unrollLoopPattern, loopReplacer )
  10098. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10099. }
  10100. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10101. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10102. return loopReplacer( match, start, end, snippet );
  10103. }
  10104. function loopReplacer( match, start, end, snippet ) {
  10105. let string = '';
  10106. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10107. string += snippet
  10108. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10109. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10110. }
  10111. return string;
  10112. }
  10113. //
  10114. function generatePrecision( parameters ) {
  10115. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10116. if ( parameters.precision === 'highp' ) {
  10117. precisionstring += '\n#define HIGH_PRECISION';
  10118. } else if ( parameters.precision === 'mediump' ) {
  10119. precisionstring += '\n#define MEDIUM_PRECISION';
  10120. } else if ( parameters.precision === 'lowp' ) {
  10121. precisionstring += '\n#define LOW_PRECISION';
  10122. }
  10123. return precisionstring;
  10124. }
  10125. function generateShadowMapTypeDefine( parameters ) {
  10126. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10127. if ( parameters.shadowMapType === PCFShadowMap ) {
  10128. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10129. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10130. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10131. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10132. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10133. }
  10134. return shadowMapTypeDefine;
  10135. }
  10136. function generateEnvMapTypeDefine( parameters ) {
  10137. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10138. if ( parameters.envMap ) {
  10139. switch ( parameters.envMapMode ) {
  10140. case CubeReflectionMapping:
  10141. case CubeRefractionMapping:
  10142. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10143. break;
  10144. case CubeUVReflectionMapping:
  10145. case CubeUVRefractionMapping:
  10146. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10147. break;
  10148. }
  10149. }
  10150. return envMapTypeDefine;
  10151. }
  10152. function generateEnvMapModeDefine( parameters ) {
  10153. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10154. if ( parameters.envMap ) {
  10155. switch ( parameters.envMapMode ) {
  10156. case CubeRefractionMapping:
  10157. case CubeUVRefractionMapping:
  10158. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10159. break;
  10160. }
  10161. }
  10162. return envMapModeDefine;
  10163. }
  10164. function generateEnvMapBlendingDefine( parameters ) {
  10165. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10166. if ( parameters.envMap ) {
  10167. switch ( parameters.combine ) {
  10168. case MultiplyOperation:
  10169. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10170. break;
  10171. case MixOperation:
  10172. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10173. break;
  10174. case AddOperation:
  10175. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10176. break;
  10177. }
  10178. }
  10179. return envMapBlendingDefine;
  10180. }
  10181. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  10182. const gl = renderer.getContext();
  10183. const defines = parameters.defines;
  10184. let vertexShader = parameters.vertexShader;
  10185. let fragmentShader = parameters.fragmentShader;
  10186. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10187. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10188. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10189. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10190. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10191. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10192. const customDefines = generateDefines( defines );
  10193. const program = gl.createProgram();
  10194. let prefixVertex, prefixFragment;
  10195. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10196. if ( parameters.isRawShaderMaterial ) {
  10197. prefixVertex = [
  10198. customDefines
  10199. ].filter( filterEmptyLine ).join( '\n' );
  10200. if ( prefixVertex.length > 0 ) {
  10201. prefixVertex += '\n';
  10202. }
  10203. prefixFragment = [
  10204. customExtensions,
  10205. customDefines
  10206. ].filter( filterEmptyLine ).join( '\n' );
  10207. if ( prefixFragment.length > 0 ) {
  10208. prefixFragment += '\n';
  10209. }
  10210. } else {
  10211. prefixVertex = [
  10212. generatePrecision( parameters ),
  10213. '#define SHADER_NAME ' + parameters.shaderName,
  10214. customDefines,
  10215. parameters.instancing ? '#define USE_INSTANCING' : '',
  10216. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  10217. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10218. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10219. '#define MAX_BONES ' + parameters.maxBones,
  10220. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10221. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10222. parameters.map ? '#define USE_MAP' : '',
  10223. parameters.envMap ? '#define USE_ENVMAP' : '',
  10224. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10225. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10226. parameters.aoMap ? '#define USE_AOMAP' : '',
  10227. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10228. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10229. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10230. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10231. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10232. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10233. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10234. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10235. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10236. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10237. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10238. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10239. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10240. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10241. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10242. parameters.vertexColors ? '#define USE_COLOR' : '',
  10243. parameters.vertexUvs ? '#define USE_UV' : '',
  10244. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10245. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10246. parameters.skinning ? '#define USE_SKINNING' : '',
  10247. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10248. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10249. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10250. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10251. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10252. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10253. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10254. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10255. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10256. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10257. 'uniform mat4 modelMatrix;',
  10258. 'uniform mat4 modelViewMatrix;',
  10259. 'uniform mat4 projectionMatrix;',
  10260. 'uniform mat4 viewMatrix;',
  10261. 'uniform mat3 normalMatrix;',
  10262. 'uniform vec3 cameraPosition;',
  10263. 'uniform bool isOrthographic;',
  10264. '#ifdef USE_INSTANCING',
  10265. ' attribute mat4 instanceMatrix;',
  10266. '#endif',
  10267. '#ifdef USE_INSTANCING_COLOR',
  10268. ' attribute vec3 instanceColor;',
  10269. '#endif',
  10270. 'attribute vec3 position;',
  10271. 'attribute vec3 normal;',
  10272. 'attribute vec2 uv;',
  10273. '#ifdef USE_TANGENT',
  10274. ' attribute vec4 tangent;',
  10275. '#endif',
  10276. '#ifdef USE_COLOR',
  10277. ' attribute vec3 color;',
  10278. '#endif',
  10279. '#ifdef USE_MORPHTARGETS',
  10280. ' attribute vec3 morphTarget0;',
  10281. ' attribute vec3 morphTarget1;',
  10282. ' attribute vec3 morphTarget2;',
  10283. ' attribute vec3 morphTarget3;',
  10284. ' #ifdef USE_MORPHNORMALS',
  10285. ' attribute vec3 morphNormal0;',
  10286. ' attribute vec3 morphNormal1;',
  10287. ' attribute vec3 morphNormal2;',
  10288. ' attribute vec3 morphNormal3;',
  10289. ' #else',
  10290. ' attribute vec3 morphTarget4;',
  10291. ' attribute vec3 morphTarget5;',
  10292. ' attribute vec3 morphTarget6;',
  10293. ' attribute vec3 morphTarget7;',
  10294. ' #endif',
  10295. '#endif',
  10296. '#ifdef USE_SKINNING',
  10297. ' attribute vec4 skinIndex;',
  10298. ' attribute vec4 skinWeight;',
  10299. '#endif',
  10300. '\n'
  10301. ].filter( filterEmptyLine ).join( '\n' );
  10302. prefixFragment = [
  10303. customExtensions,
  10304. generatePrecision( parameters ),
  10305. '#define SHADER_NAME ' + parameters.shaderName,
  10306. customDefines,
  10307. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  10308. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10309. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10310. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10311. parameters.map ? '#define USE_MAP' : '',
  10312. parameters.matcap ? '#define USE_MATCAP' : '',
  10313. parameters.envMap ? '#define USE_ENVMAP' : '',
  10314. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  10315. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10316. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  10317. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10318. parameters.aoMap ? '#define USE_AOMAP' : '',
  10319. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10320. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10321. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10322. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10323. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10324. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10325. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10326. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10327. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10328. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10329. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10330. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10331. parameters.sheen ? '#define USE_SHEEN' : '',
  10332. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10333. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10334. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  10335. parameters.vertexUvs ? '#define USE_UV' : '',
  10336. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10337. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  10338. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10339. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10340. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10341. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10342. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10343. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  10344. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  10345. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10346. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10347. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  10348. 'uniform mat4 viewMatrix;',
  10349. 'uniform vec3 cameraPosition;',
  10350. 'uniform bool isOrthographic;',
  10351. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  10352. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  10353. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  10354. parameters.dithering ? '#define DITHERING' : '',
  10355. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  10356. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  10357. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  10358. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  10359. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  10360. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  10361. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  10362. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  10363. '\n'
  10364. ].filter( filterEmptyLine ).join( '\n' );
  10365. }
  10366. vertexShader = resolveIncludes( vertexShader );
  10367. vertexShader = replaceLightNums( vertexShader, parameters );
  10368. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  10369. fragmentShader = resolveIncludes( fragmentShader );
  10370. fragmentShader = replaceLightNums( fragmentShader, parameters );
  10371. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  10372. vertexShader = unrollLoops( vertexShader );
  10373. fragmentShader = unrollLoops( fragmentShader );
  10374. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  10375. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10376. versionString = '#version 300 es\n';
  10377. prefixVertex = [
  10378. '#define attribute in',
  10379. '#define varying out',
  10380. '#define texture2D texture'
  10381. ].join( '\n' ) + '\n' + prefixVertex;
  10382. prefixFragment = [
  10383. '#define varying in',
  10384. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  10385. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  10386. '#define gl_FragDepthEXT gl_FragDepth',
  10387. '#define texture2D texture',
  10388. '#define textureCube texture',
  10389. '#define texture2DProj textureProj',
  10390. '#define texture2DLodEXT textureLod',
  10391. '#define texture2DProjLodEXT textureProjLod',
  10392. '#define textureCubeLodEXT textureLod',
  10393. '#define texture2DGradEXT textureGrad',
  10394. '#define texture2DProjGradEXT textureProjGrad',
  10395. '#define textureCubeGradEXT textureGrad'
  10396. ].join( '\n' ) + '\n' + prefixFragment;
  10397. }
  10398. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10399. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  10400. // console.log( '*VERTEX*', vertexGlsl );
  10401. // console.log( '*FRAGMENT*', fragmentGlsl );
  10402. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  10403. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  10404. gl.attachShader( program, glVertexShader );
  10405. gl.attachShader( program, glFragmentShader );
  10406. // Force a particular attribute to index 0.
  10407. if ( parameters.index0AttributeName !== undefined ) {
  10408. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  10409. } else if ( parameters.morphTargets === true ) {
  10410. // programs with morphTargets displace position out of attribute 0
  10411. gl.bindAttribLocation( program, 0, 'position' );
  10412. }
  10413. gl.linkProgram( program );
  10414. // check for link errors
  10415. if ( renderer.debug.checkShaderErrors ) {
  10416. const programLog = gl.getProgramInfoLog( program ).trim();
  10417. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  10418. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  10419. let runnable = true;
  10420. let haveDiagnostics = true;
  10421. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  10422. runnable = false;
  10423. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  10424. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  10425. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  10426. //add:
  10427. if(fragmentErrors){
  10428. console.log(fragmentGlsl.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n") );
  10429. }else {
  10430. console.log(vertexGlsl.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n") );
  10431. }
  10432. } else if ( programLog !== '' ) {
  10433. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  10434. } else if ( vertexLog === '' || fragmentLog === '' ) {
  10435. haveDiagnostics = false;
  10436. }
  10437. if ( haveDiagnostics ) {
  10438. this.diagnostics = {
  10439. runnable: runnable,
  10440. programLog: programLog,
  10441. vertexShader: {
  10442. log: vertexLog,
  10443. prefix: prefixVertex
  10444. },
  10445. fragmentShader: {
  10446. log: fragmentLog,
  10447. prefix: prefixFragment
  10448. }
  10449. };
  10450. }
  10451. }
  10452. // Clean up
  10453. // Crashes in iOS9 and iOS10. #18402
  10454. // gl.detachShader( program, glVertexShader );
  10455. // gl.detachShader( program, glFragmentShader );
  10456. gl.deleteShader( glVertexShader );
  10457. gl.deleteShader( glFragmentShader );
  10458. // set up caching for uniform locations
  10459. let cachedUniforms;
  10460. this.getUniforms = function () {
  10461. if ( cachedUniforms === undefined ) {
  10462. cachedUniforms = new WebGLUniforms( gl, program );
  10463. }
  10464. return cachedUniforms;
  10465. };
  10466. // set up caching for attribute locations
  10467. let cachedAttributes;
  10468. this.getAttributes = function () {
  10469. if ( cachedAttributes === undefined ) {
  10470. cachedAttributes = fetchAttributeLocations( gl, program );
  10471. }
  10472. return cachedAttributes;
  10473. };
  10474. // free resource
  10475. this.destroy = function () {
  10476. bindingStates.releaseStatesOfProgram( this );
  10477. gl.deleteProgram( program );
  10478. this.program = undefined;
  10479. };
  10480. //
  10481. this.name = parameters.shaderName;
  10482. this.id = programIdCount ++;
  10483. this.cacheKey = cacheKey;
  10484. this.usedTimes = 1;
  10485. this.program = program;
  10486. this.vertexShader = glVertexShader;
  10487. this.fragmentShader = glFragmentShader;
  10488. return this;
  10489. }
  10490. function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) {
  10491. const programs = [];
  10492. const isWebGL2 = capabilities.isWebGL2;
  10493. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10494. const floatVertexTextures = capabilities.floatVertexTextures;
  10495. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10496. const vertexTextures = capabilities.vertexTextures;
  10497. let precision = capabilities.precision;
  10498. const shaderIDs = {
  10499. MeshDepthMaterial: 'depth',
  10500. MeshDistanceMaterial: 'distanceRGBA',
  10501. MeshNormalMaterial: 'normal',
  10502. MeshBasicMaterial: 'basic',
  10503. MeshLambertMaterial: 'lambert',
  10504. MeshPhongMaterial: 'phong',
  10505. MeshToonMaterial: 'toon',
  10506. MeshStandardMaterial: 'physical',
  10507. MeshPhysicalMaterial: 'physical',
  10508. MeshMatcapMaterial: 'matcap',
  10509. LineBasicMaterial: 'basic',
  10510. LineDashedMaterial: 'dashed',
  10511. PointsMaterial: 'points',
  10512. ShadowMaterial: 'shadow',
  10513. SpriteMaterial: 'sprite'
  10514. };
  10515. const parameterNames = [
  10516. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  10517. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  10518. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap',
  10519. 'roughnessMap', 'metalnessMap', 'gradientMap',
  10520. 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  10521. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  10522. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals',
  10523. 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha',
  10524. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  10525. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  10526. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  10527. 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering',
  10528. 'sheen', 'transmissionMap'
  10529. ];
  10530. function getMaxBones( object ) {
  10531. const skeleton = object.skeleton;
  10532. const bones = skeleton.bones;
  10533. if ( floatVertexTextures ) {
  10534. return 1024;
  10535. } else {
  10536. // default for when object is not specified
  10537. // ( for example when prebuilding shader to be used with multiple objects )
  10538. //
  10539. // - leave some extra space for other uniforms
  10540. // - limit here is ANGLE's 254 max uniform vectors
  10541. // (up to 54 should be safe)
  10542. const nVertexUniforms = maxVertexUniforms;
  10543. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  10544. const maxBones = Math.min( nVertexMatrices, bones.length );
  10545. if ( maxBones < bones.length ) {
  10546. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  10547. return 0;
  10548. }
  10549. return maxBones;
  10550. }
  10551. }
  10552. function getTextureEncodingFromMap( map ) {
  10553. let encoding;
  10554. if ( map && map.isTexture ) {
  10555. encoding = map.encoding;
  10556. } else if ( map && map.isWebGLRenderTarget ) {
  10557. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  10558. encoding = map.texture.encoding;
  10559. } else {
  10560. encoding = LinearEncoding;
  10561. }
  10562. return encoding;
  10563. }
  10564. function getParameters( material, lights, shadows, scene, object ) {
  10565. const fog = scene.fog;
  10566. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10567. const envMap = cubemaps.get( material.envMap || environment );
  10568. const shaderID = shaderIDs[ material.type ];
  10569. // heuristics to create shader parameters according to lights in the scene
  10570. // (not to blow over maxLights budget)
  10571. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  10572. if ( material.precision !== null ) {
  10573. precision = capabilities.getMaxPrecision( material.precision );
  10574. if ( precision !== material.precision ) {
  10575. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  10576. }
  10577. }
  10578. let vertexShader, fragmentShader;
  10579. if ( shaderID ) {
  10580. const shader = ShaderLib[ shaderID ];
  10581. vertexShader = shader.vertexShader;
  10582. fragmentShader = shader.fragmentShader;
  10583. } else {
  10584. vertexShader = material.vertexShader;
  10585. fragmentShader = material.fragmentShader;
  10586. }
  10587. const currentRenderTarget = renderer.getRenderTarget();
  10588. const parameters = {
  10589. isWebGL2: isWebGL2,
  10590. shaderID: shaderID,
  10591. shaderName: material.type,
  10592. vertexShader: vertexShader,
  10593. fragmentShader: fragmentShader,
  10594. defines: material.defines,
  10595. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10596. glslVersion: material.glslVersion,
  10597. precision: precision,
  10598. instancing: object.isInstancedMesh === true,
  10599. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10600. supportsVertexTextures: vertexTextures,
  10601. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  10602. map: !! material.map,
  10603. mapEncoding: getTextureEncodingFromMap( material.map ),
  10604. matcap: !! material.matcap,
  10605. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  10606. envMap: !! envMap,
  10607. envMapMode: envMap && envMap.mapping,
  10608. envMapEncoding: getTextureEncodingFromMap( envMap ),
  10609. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  10610. lightMap: !! material.lightMap,
  10611. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  10612. aoMap: !! material.aoMap,
  10613. emissiveMap: !! material.emissiveMap,
  10614. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  10615. bumpMap: !! material.bumpMap,
  10616. normalMap: !! material.normalMap,
  10617. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10618. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10619. clearcoatMap: !! material.clearcoatMap,
  10620. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  10621. clearcoatNormalMap: !! material.clearcoatNormalMap,
  10622. displacementMap: !! material.displacementMap,
  10623. roughnessMap: !! material.roughnessMap,
  10624. metalnessMap: !! material.metalnessMap,
  10625. specularMap: !! material.specularMap,
  10626. alphaMap: !! material.alphaMap,
  10627. gradientMap: !! material.gradientMap,
  10628. sheen: !! material.sheen,
  10629. transmissionMap: !! material.transmissionMap,
  10630. combine: material.combine,
  10631. vertexTangents: ( material.normalMap && material.vertexTangents ),
  10632. vertexColors: material.vertexColors,
  10633. 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,
  10634. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap,
  10635. fog: !! fog,
  10636. useFog: material.fog,
  10637. fogExp2: ( fog && fog.isFogExp2 ),
  10638. flatShading: material.flatShading,
  10639. sizeAttenuation: material.sizeAttenuation,
  10640. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10641. skinning: material.skinning && maxBones > 0,
  10642. maxBones: maxBones,
  10643. useVertexTexture: floatVertexTextures,
  10644. morphTargets: material.morphTargets,
  10645. morphNormals: material.morphNormals,
  10646. maxMorphTargets: renderer.maxMorphTargets,
  10647. maxMorphNormals: renderer.maxMorphNormals,
  10648. numDirLights: lights.directional.length,
  10649. numPointLights: lights.point.length,
  10650. numSpotLights: lights.spot.length,
  10651. numRectAreaLights: lights.rectArea.length,
  10652. numHemiLights: lights.hemi.length,
  10653. numDirLightShadows: lights.directionalShadowMap.length,
  10654. numPointLightShadows: lights.pointShadowMap.length,
  10655. numSpotLightShadows: lights.spotShadowMap.length,
  10656. numClippingPlanes: clipping.numPlanes,
  10657. numClipIntersection: clipping.numIntersection,
  10658. dithering: material.dithering,
  10659. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10660. shadowMapType: renderer.shadowMap.type,
  10661. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10662. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10663. premultipliedAlpha: material.premultipliedAlpha,
  10664. alphaTest: material.alphaTest,
  10665. doubleSided: material.side === DoubleSide,
  10666. flipSided: material.side === BackSide,
  10667. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  10668. index0AttributeName: material.index0AttributeName,
  10669. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10670. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10671. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10672. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10673. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  10674. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  10675. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  10676. customProgramCacheKey: material.customProgramCacheKey()
  10677. };
  10678. return parameters;
  10679. }
  10680. function getProgramCacheKey( parameters ) {
  10681. const array = [];
  10682. if ( parameters.shaderID ) {
  10683. array.push( parameters.shaderID );
  10684. } else {
  10685. array.push( parameters.fragmentShader );
  10686. array.push( parameters.vertexShader );
  10687. }
  10688. if ( parameters.defines !== undefined ) {
  10689. for ( const name in parameters.defines ) {
  10690. array.push( name );
  10691. array.push( parameters.defines[ name ] );
  10692. }
  10693. }
  10694. if ( parameters.isRawShaderMaterial === false ) {
  10695. for ( let i = 0; i < parameterNames.length; i ++ ) {
  10696. array.push( parameters[ parameterNames[ i ] ] );
  10697. }
  10698. array.push( renderer.outputEncoding );
  10699. array.push( renderer.gammaFactor );
  10700. }
  10701. array.push( parameters.customProgramCacheKey );
  10702. return array.join();
  10703. }
  10704. function getUniforms( material ) {
  10705. const shaderID = shaderIDs[ material.type ];
  10706. let uniforms;
  10707. if ( shaderID ) {
  10708. const shader = ShaderLib[ shaderID ];
  10709. uniforms = UniformsUtils.clone( shader.uniforms );
  10710. } else {
  10711. uniforms = material.uniforms;
  10712. }
  10713. return uniforms;
  10714. }
  10715. function acquireProgram( parameters, cacheKey ) {
  10716. let program;
  10717. // Check if code has been already compiled
  10718. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  10719. const preexistingProgram = programs[ p ];
  10720. if ( preexistingProgram.cacheKey === cacheKey ) {
  10721. program = preexistingProgram;
  10722. ++ program.usedTimes;
  10723. break;
  10724. }
  10725. }
  10726. if ( program === undefined ) {
  10727. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  10728. programs.push( program );
  10729. }
  10730. return program;
  10731. }
  10732. function releaseProgram( program ) {
  10733. if ( -- program.usedTimes === 0 ) {
  10734. // Remove from unordered set
  10735. const i = programs.indexOf( program );
  10736. programs[ i ] = programs[ programs.length - 1 ];
  10737. programs.pop();
  10738. // Free WebGL resources
  10739. program.destroy();
  10740. }
  10741. }
  10742. return {
  10743. getParameters: getParameters,
  10744. getProgramCacheKey: getProgramCacheKey,
  10745. getUniforms: getUniforms,
  10746. acquireProgram: acquireProgram,
  10747. releaseProgram: releaseProgram,
  10748. // Exposed for resource monitoring & error feedback via renderer.info:
  10749. programs: programs
  10750. };
  10751. }
  10752. function WebGLProperties() {
  10753. let properties = new WeakMap();
  10754. function get( object ) {
  10755. let map = properties.get( object );
  10756. if ( map === undefined ) {
  10757. map = {};
  10758. properties.set( object, map );
  10759. }
  10760. return map;
  10761. }
  10762. function remove( object ) {
  10763. properties.delete( object );
  10764. }
  10765. function update( object, key, value ) {
  10766. properties.get( object )[ key ] = value;
  10767. }
  10768. function dispose() {
  10769. properties = new WeakMap();
  10770. }
  10771. return {
  10772. get: get,
  10773. remove: remove,
  10774. update: update,
  10775. dispose: dispose
  10776. };
  10777. }
  10778. function painterSortStable( a, b ) {
  10779. if ( a.groupOrder !== b.groupOrder ) {
  10780. return a.groupOrder - b.groupOrder;
  10781. } else if ( a.renderOrder !== b.renderOrder ) {
  10782. return a.renderOrder - b.renderOrder;
  10783. } else if ( a.program !== b.program ) {
  10784. return a.program.id - b.program.id;
  10785. } else if ( a.material.id !== b.material.id ) {
  10786. return a.material.id - b.material.id;
  10787. } else if ( a.z !== b.z ) {
  10788. return a.z - b.z;
  10789. } else {
  10790. return a.id - b.id;
  10791. }
  10792. }
  10793. function reversePainterSortStable( a, b ) {
  10794. if ( a.groupOrder !== b.groupOrder ) {
  10795. return a.groupOrder - b.groupOrder;
  10796. } else if ( a.renderOrder !== b.renderOrder ) {
  10797. return a.renderOrder - b.renderOrder;
  10798. } else if ( a.z !== b.z ) {
  10799. return b.z - a.z;
  10800. } else {
  10801. return a.id - b.id;
  10802. }
  10803. }
  10804. function WebGLRenderList( properties ) {
  10805. const renderItems = [];
  10806. let renderItemsIndex = 0;
  10807. const opaque = [];
  10808. const transparent = [];
  10809. const defaultProgram = { id: - 1 };
  10810. function init() {
  10811. renderItemsIndex = 0;
  10812. opaque.length = 0;
  10813. transparent.length = 0;
  10814. }
  10815. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  10816. let renderItem = renderItems[ renderItemsIndex ];
  10817. const materialProperties = properties.get( material );
  10818. if ( renderItem === undefined ) {
  10819. renderItem = {
  10820. id: object.id,
  10821. object: object,
  10822. geometry: geometry,
  10823. material: material,
  10824. program: materialProperties.program || defaultProgram,
  10825. groupOrder: groupOrder,
  10826. renderOrder: object.renderOrder,
  10827. z: z,
  10828. group: group
  10829. };
  10830. renderItems[ renderItemsIndex ] = renderItem;
  10831. } else {
  10832. renderItem.id = object.id;
  10833. renderItem.object = object;
  10834. renderItem.geometry = geometry;
  10835. renderItem.material = material;
  10836. renderItem.program = materialProperties.program || defaultProgram;
  10837. renderItem.groupOrder = groupOrder;
  10838. renderItem.renderOrder = object.renderOrder;
  10839. renderItem.z = z;
  10840. renderItem.group = group;
  10841. }
  10842. renderItemsIndex ++;
  10843. return renderItem;
  10844. }
  10845. function push( object, geometry, material, groupOrder, z, group ) {
  10846. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  10847. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  10848. }
  10849. function unshift( object, geometry, material, groupOrder, z, group ) {
  10850. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  10851. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  10852. }
  10853. function sort( customOpaqueSort, customTransparentSort ) {
  10854. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  10855. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  10856. }
  10857. function finish() {
  10858. // Clear references from inactive renderItems in the list
  10859. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  10860. const renderItem = renderItems[ i ];
  10861. if ( renderItem.id === null ) break;
  10862. renderItem.id = null;
  10863. renderItem.object = null;
  10864. renderItem.geometry = null;
  10865. renderItem.material = null;
  10866. renderItem.program = null;
  10867. renderItem.group = null;
  10868. }
  10869. }
  10870. return {
  10871. opaque: opaque,
  10872. transparent: transparent,
  10873. init: init,
  10874. push: push,
  10875. unshift: unshift,
  10876. finish: finish,
  10877. sort: sort
  10878. };
  10879. }
  10880. function WebGLRenderLists( properties ) {
  10881. let lists = new WeakMap();
  10882. function get( scene, camera ) {
  10883. const cameras = lists.get( scene );
  10884. let list;
  10885. if ( cameras === undefined ) {
  10886. list = new WebGLRenderList( properties );
  10887. lists.set( scene, new WeakMap() );
  10888. lists.get( scene ).set( camera, list );
  10889. } else {
  10890. list = cameras.get( camera );
  10891. if ( list === undefined ) {
  10892. list = new WebGLRenderList( properties );
  10893. cameras.set( camera, list );
  10894. }
  10895. }
  10896. return list;
  10897. }
  10898. function dispose() {
  10899. lists = new WeakMap();
  10900. }
  10901. return {
  10902. get: get,
  10903. dispose: dispose
  10904. };
  10905. }
  10906. function UniformsCache() {
  10907. const lights = {};
  10908. return {
  10909. get: function ( light ) {
  10910. if ( lights[ light.id ] !== undefined ) {
  10911. return lights[ light.id ];
  10912. }
  10913. let uniforms;
  10914. switch ( light.type ) {
  10915. case 'DirectionalLight':
  10916. uniforms = {
  10917. direction: new Vector3(),
  10918. color: new Color()
  10919. };
  10920. break;
  10921. case 'SpotLight':
  10922. uniforms = {
  10923. position: new Vector3(),
  10924. direction: new Vector3(),
  10925. color: new Color(),
  10926. distance: 0,
  10927. coneCos: 0,
  10928. penumbraCos: 0,
  10929. decay: 0
  10930. };
  10931. break;
  10932. case 'PointLight':
  10933. uniforms = {
  10934. position: new Vector3(),
  10935. color: new Color(),
  10936. distance: 0,
  10937. decay: 0
  10938. };
  10939. break;
  10940. case 'HemisphereLight':
  10941. uniforms = {
  10942. direction: new Vector3(),
  10943. skyColor: new Color(),
  10944. groundColor: new Color()
  10945. };
  10946. break;
  10947. case 'RectAreaLight':
  10948. uniforms = {
  10949. color: new Color(),
  10950. position: new Vector3(),
  10951. halfWidth: new Vector3(),
  10952. halfHeight: new Vector3()
  10953. };
  10954. break;
  10955. }
  10956. lights[ light.id ] = uniforms;
  10957. return uniforms;
  10958. }
  10959. };
  10960. }
  10961. function ShadowUniformsCache() {
  10962. const lights = {};
  10963. return {
  10964. get: function ( light ) {
  10965. if ( lights[ light.id ] !== undefined ) {
  10966. return lights[ light.id ];
  10967. }
  10968. let uniforms;
  10969. switch ( light.type ) {
  10970. case 'DirectionalLight':
  10971. uniforms = {
  10972. shadowBias: 0,
  10973. shadowNormalBias: 0,
  10974. shadowRadius: 1,
  10975. shadowMapSize: new Vector2()
  10976. };
  10977. break;
  10978. case 'SpotLight':
  10979. uniforms = {
  10980. shadowBias: 0,
  10981. shadowNormalBias: 0,
  10982. shadowRadius: 1,
  10983. shadowMapSize: new Vector2()
  10984. };
  10985. break;
  10986. case 'PointLight':
  10987. uniforms = {
  10988. shadowBias: 0,
  10989. shadowNormalBias: 0,
  10990. shadowRadius: 1,
  10991. shadowMapSize: new Vector2(),
  10992. shadowCameraNear: 1,
  10993. shadowCameraFar: 1000
  10994. };
  10995. break;
  10996. // TODO (abelnation): set RectAreaLight shadow uniforms
  10997. }
  10998. lights[ light.id ] = uniforms;
  10999. return uniforms;
  11000. }
  11001. };
  11002. }
  11003. let nextVersion = 0;
  11004. function shadowCastingLightsFirst( lightA, lightB ) {
  11005. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  11006. }
  11007. function WebGLLights( extensions, capabilities ) {
  11008. const cache = new UniformsCache();
  11009. const shadowCache = ShadowUniformsCache();
  11010. const state = {
  11011. version: 0,
  11012. hash: {
  11013. directionalLength: - 1,
  11014. pointLength: - 1,
  11015. spotLength: - 1,
  11016. rectAreaLength: - 1,
  11017. hemiLength: - 1,
  11018. numDirectionalShadows: - 1,
  11019. numPointShadows: - 1,
  11020. numSpotShadows: - 1
  11021. },
  11022. ambient: [ 0, 0, 0 ],
  11023. probe: [],
  11024. directional: [],
  11025. directionalShadow: [],
  11026. directionalShadowMap: [],
  11027. directionalShadowMatrix: [],
  11028. spot: [],
  11029. spotShadow: [],
  11030. spotShadowMap: [],
  11031. spotShadowMatrix: [],
  11032. rectArea: [],
  11033. rectAreaLTC1: null,
  11034. rectAreaLTC2: null,
  11035. point: [],
  11036. pointShadow: [],
  11037. pointShadowMap: [],
  11038. pointShadowMatrix: [],
  11039. hemi: []
  11040. };
  11041. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  11042. const vector3 = new Vector3();
  11043. const matrix4 = new Matrix4();
  11044. const matrix42 = new Matrix4();
  11045. function setup( lights ) {
  11046. let r = 0, g = 0, b = 0;
  11047. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  11048. let directionalLength = 0;
  11049. let pointLength = 0;
  11050. let spotLength = 0;
  11051. let rectAreaLength = 0;
  11052. let hemiLength = 0;
  11053. let numDirectionalShadows = 0;
  11054. let numPointShadows = 0;
  11055. let numSpotShadows = 0;
  11056. lights.sort( shadowCastingLightsFirst );
  11057. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11058. const light = lights[ i ];
  11059. const color = light.color;
  11060. const intensity = light.intensity;
  11061. const distance = light.distance;
  11062. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  11063. if ( light.isAmbientLight ) {
  11064. r += color.r * intensity;
  11065. g += color.g * intensity;
  11066. b += color.b * intensity;
  11067. } else if ( light.isLightProbe ) {
  11068. for ( let j = 0; j < 9; j ++ ) {
  11069. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  11070. }
  11071. } else if ( light.isDirectionalLight ) {
  11072. const uniforms = cache.get( light );
  11073. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11074. if ( light.castShadow ) {
  11075. const shadow = light.shadow;
  11076. const shadowUniforms = shadowCache.get( light );
  11077. shadowUniforms.shadowBias = shadow.bias;
  11078. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11079. shadowUniforms.shadowRadius = shadow.radius;
  11080. shadowUniforms.shadowMapSize = shadow.mapSize;
  11081. state.directionalShadow[ directionalLength ] = shadowUniforms;
  11082. state.directionalShadowMap[ directionalLength ] = shadowMap;
  11083. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  11084. numDirectionalShadows ++;
  11085. }
  11086. state.directional[ directionalLength ] = uniforms;
  11087. directionalLength ++;
  11088. } else if ( light.isSpotLight ) {
  11089. const uniforms = cache.get( light );
  11090. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11091. uniforms.color.copy( color ).multiplyScalar( intensity );
  11092. uniforms.distance = distance;
  11093. uniforms.coneCos = Math.cos( light.angle );
  11094. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  11095. uniforms.decay = light.decay;
  11096. if ( light.castShadow ) {
  11097. const shadow = light.shadow;
  11098. const shadowUniforms = shadowCache.get( light );
  11099. shadowUniforms.shadowBias = shadow.bias;
  11100. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11101. shadowUniforms.shadowRadius = shadow.radius;
  11102. shadowUniforms.shadowMapSize = shadow.mapSize;
  11103. state.spotShadow[ spotLength ] = shadowUniforms;
  11104. state.spotShadowMap[ spotLength ] = shadowMap;
  11105. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  11106. numSpotShadows ++;
  11107. }
  11108. state.spot[ spotLength ] = uniforms;
  11109. spotLength ++;
  11110. } else if ( light.isRectAreaLight ) {
  11111. const uniforms = cache.get( light );
  11112. // (a) intensity is the total visible light emitted
  11113. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11114. // (b) intensity is the brightness of the light
  11115. uniforms.color.copy( color ).multiplyScalar( intensity );
  11116. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11117. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11118. state.rectArea[ rectAreaLength ] = uniforms;
  11119. rectAreaLength ++;
  11120. } else if ( light.isPointLight ) {
  11121. const uniforms = cache.get( light );
  11122. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11123. uniforms.distance = light.distance;
  11124. uniforms.decay = light.decay;
  11125. if ( light.castShadow ) {
  11126. const shadow = light.shadow;
  11127. const shadowUniforms = shadowCache.get( light );
  11128. shadowUniforms.shadowBias = shadow.bias;
  11129. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11130. shadowUniforms.shadowRadius = shadow.radius;
  11131. shadowUniforms.shadowMapSize = shadow.mapSize;
  11132. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11133. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11134. state.pointShadow[ pointLength ] = shadowUniforms;
  11135. state.pointShadowMap[ pointLength ] = shadowMap;
  11136. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  11137. numPointShadows ++;
  11138. }
  11139. state.point[ pointLength ] = uniforms;
  11140. pointLength ++;
  11141. } else if ( light.isHemisphereLight ) {
  11142. const uniforms = cache.get( light );
  11143. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  11144. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  11145. state.hemi[ hemiLength ] = uniforms;
  11146. hemiLength ++;
  11147. }
  11148. }
  11149. if ( rectAreaLength > 0 ) {
  11150. if ( capabilities.isWebGL2 ) {
  11151. // WebGL 2
  11152. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11153. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11154. } else {
  11155. // WebGL 1
  11156. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  11157. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11158. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11159. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  11160. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11161. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11162. } else {
  11163. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  11164. }
  11165. }
  11166. }
  11167. state.ambient[ 0 ] = r;
  11168. state.ambient[ 1 ] = g;
  11169. state.ambient[ 2 ] = b;
  11170. const hash = state.hash;
  11171. if ( hash.directionalLength !== directionalLength ||
  11172. hash.pointLength !== pointLength ||
  11173. hash.spotLength !== spotLength ||
  11174. hash.rectAreaLength !== rectAreaLength ||
  11175. hash.hemiLength !== hemiLength ||
  11176. hash.numDirectionalShadows !== numDirectionalShadows ||
  11177. hash.numPointShadows !== numPointShadows ||
  11178. hash.numSpotShadows !== numSpotShadows ) {
  11179. state.directional.length = directionalLength;
  11180. state.spot.length = spotLength;
  11181. state.rectArea.length = rectAreaLength;
  11182. state.point.length = pointLength;
  11183. state.hemi.length = hemiLength;
  11184. state.directionalShadow.length = numDirectionalShadows;
  11185. state.directionalShadowMap.length = numDirectionalShadows;
  11186. state.pointShadow.length = numPointShadows;
  11187. state.pointShadowMap.length = numPointShadows;
  11188. state.spotShadow.length = numSpotShadows;
  11189. state.spotShadowMap.length = numSpotShadows;
  11190. state.directionalShadowMatrix.length = numDirectionalShadows;
  11191. state.pointShadowMatrix.length = numPointShadows;
  11192. state.spotShadowMatrix.length = numSpotShadows;
  11193. hash.directionalLength = directionalLength;
  11194. hash.pointLength = pointLength;
  11195. hash.spotLength = spotLength;
  11196. hash.rectAreaLength = rectAreaLength;
  11197. hash.hemiLength = hemiLength;
  11198. hash.numDirectionalShadows = numDirectionalShadows;
  11199. hash.numPointShadows = numPointShadows;
  11200. hash.numSpotShadows = numSpotShadows;
  11201. state.version = nextVersion ++;
  11202. }
  11203. }
  11204. function setupView( lights, camera ) {
  11205. let directionalLength = 0;
  11206. let pointLength = 0;
  11207. let spotLength = 0;
  11208. let rectAreaLength = 0;
  11209. let hemiLength = 0;
  11210. const viewMatrix = camera.matrixWorldInverse;
  11211. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11212. const light = lights[ i ];
  11213. if ( light.isDirectionalLight ) {
  11214. const uniforms = state.directional[ directionalLength ];
  11215. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11216. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11217. uniforms.direction.sub( vector3 );
  11218. uniforms.direction.transformDirection( viewMatrix );
  11219. directionalLength ++;
  11220. } else if ( light.isSpotLight ) {
  11221. const uniforms = state.spot[ spotLength ];
  11222. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11223. uniforms.position.applyMatrix4( viewMatrix );
  11224. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11225. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11226. uniforms.direction.sub( vector3 );
  11227. uniforms.direction.transformDirection( viewMatrix );
  11228. spotLength ++;
  11229. } else if ( light.isRectAreaLight ) {
  11230. const uniforms = state.rectArea[ rectAreaLength ];
  11231. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11232. uniforms.position.applyMatrix4( viewMatrix );
  11233. // extract local rotation of light to derive width/height half vectors
  11234. matrix42.identity();
  11235. matrix4.copy( light.matrixWorld );
  11236. matrix4.premultiply( viewMatrix );
  11237. matrix42.extractRotation( matrix4 );
  11238. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11239. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11240. uniforms.halfWidth.applyMatrix4( matrix42 );
  11241. uniforms.halfHeight.applyMatrix4( matrix42 );
  11242. rectAreaLength ++;
  11243. } else if ( light.isPointLight ) {
  11244. const uniforms = state.point[ pointLength ];
  11245. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11246. uniforms.position.applyMatrix4( viewMatrix );
  11247. pointLength ++;
  11248. } else if ( light.isHemisphereLight ) {
  11249. const uniforms = state.hemi[ hemiLength ];
  11250. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11251. uniforms.direction.transformDirection( viewMatrix );
  11252. uniforms.direction.normalize();
  11253. hemiLength ++;
  11254. }
  11255. }
  11256. }
  11257. return {
  11258. setup: setup,
  11259. setupView: setupView,
  11260. state: state
  11261. };
  11262. }
  11263. function WebGLRenderState( extensions, capabilities ) {
  11264. const lights = new WebGLLights( extensions, capabilities );
  11265. const lightsArray = [];
  11266. const shadowsArray = [];
  11267. function init() {
  11268. lightsArray.length = 0;
  11269. shadowsArray.length = 0;
  11270. }
  11271. function pushLight( light ) {
  11272. lightsArray.push( light );
  11273. }
  11274. function pushShadow( shadowLight ) {
  11275. shadowsArray.push( shadowLight );
  11276. }
  11277. function setupLights() {
  11278. lights.setup( lightsArray );
  11279. }
  11280. function setupLightsView( camera ) {
  11281. lights.setupView( lightsArray, camera );
  11282. }
  11283. const state = {
  11284. lightsArray: lightsArray,
  11285. shadowsArray: shadowsArray,
  11286. lights: lights
  11287. };
  11288. return {
  11289. init: init,
  11290. state: state,
  11291. setupLights: setupLights,
  11292. setupLightsView: setupLightsView,
  11293. pushLight: pushLight,
  11294. pushShadow: pushShadow
  11295. };
  11296. }
  11297. function WebGLRenderStates( extensions, capabilities ) {
  11298. let renderStates = new WeakMap();
  11299. function get( scene, renderCallDepth = 0 ) {
  11300. let renderState;
  11301. if ( renderStates.has( scene ) === false ) {
  11302. renderState = new WebGLRenderState( extensions, capabilities );
  11303. renderStates.set( scene, [] );
  11304. renderStates.get( scene ).push( renderState );
  11305. } else {
  11306. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  11307. renderState = new WebGLRenderState( extensions, capabilities );
  11308. renderStates.get( scene ).push( renderState );
  11309. } else {
  11310. renderState = renderStates.get( scene )[ renderCallDepth ];
  11311. }
  11312. }
  11313. return renderState;
  11314. }
  11315. function dispose() {
  11316. renderStates = new WeakMap();
  11317. }
  11318. return {
  11319. get: get,
  11320. dispose: dispose
  11321. };
  11322. }
  11323. /**
  11324. * parameters = {
  11325. *
  11326. * opacity: <float>,
  11327. *
  11328. * map: new THREE.Texture( <Image> ),
  11329. *
  11330. * alphaMap: new THREE.Texture( <Image> ),
  11331. *
  11332. * displacementMap: new THREE.Texture( <Image> ),
  11333. * displacementScale: <float>,
  11334. * displacementBias: <float>,
  11335. *
  11336. * wireframe: <boolean>,
  11337. * wireframeLinewidth: <float>
  11338. * }
  11339. */
  11340. function MeshDepthMaterial( parameters ) {
  11341. Material.call( this );
  11342. this.type = 'MeshDepthMaterial';
  11343. this.depthPacking = BasicDepthPacking;
  11344. this.skinning = false;
  11345. this.morphTargets = false;
  11346. this.map = null;
  11347. this.alphaMap = null;
  11348. this.displacementMap = null;
  11349. this.displacementScale = 1;
  11350. this.displacementBias = 0;
  11351. this.wireframe = false;
  11352. this.wireframeLinewidth = 1;
  11353. this.fog = false;
  11354. this.setValues( parameters );
  11355. }
  11356. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  11357. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  11358. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11359. MeshDepthMaterial.prototype.copy = function ( source ) {
  11360. Material.prototype.copy.call( this, source );
  11361. this.depthPacking = source.depthPacking;
  11362. this.skinning = source.skinning;
  11363. this.morphTargets = source.morphTargets;
  11364. this.map = source.map;
  11365. this.alphaMap = source.alphaMap;
  11366. this.displacementMap = source.displacementMap;
  11367. this.displacementScale = source.displacementScale;
  11368. this.displacementBias = source.displacementBias;
  11369. this.wireframe = source.wireframe;
  11370. this.wireframeLinewidth = source.wireframeLinewidth;
  11371. return this;
  11372. };
  11373. /**
  11374. * parameters = {
  11375. *
  11376. * referencePosition: <float>,
  11377. * nearDistance: <float>,
  11378. * farDistance: <float>,
  11379. *
  11380. * skinning: <bool>,
  11381. * morphTargets: <bool>,
  11382. *
  11383. * map: new THREE.Texture( <Image> ),
  11384. *
  11385. * alphaMap: new THREE.Texture( <Image> ),
  11386. *
  11387. * displacementMap: new THREE.Texture( <Image> ),
  11388. * displacementScale: <float>,
  11389. * displacementBias: <float>
  11390. *
  11391. * }
  11392. */
  11393. function MeshDistanceMaterial( parameters ) {
  11394. Material.call( this );
  11395. this.type = 'MeshDistanceMaterial';
  11396. this.referencePosition = new Vector3();
  11397. this.nearDistance = 1;
  11398. this.farDistance = 1000;
  11399. this.skinning = false;
  11400. this.morphTargets = false;
  11401. this.map = null;
  11402. this.alphaMap = null;
  11403. this.displacementMap = null;
  11404. this.displacementScale = 1;
  11405. this.displacementBias = 0;
  11406. this.fog = false;
  11407. this.setValues( parameters );
  11408. }
  11409. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  11410. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  11411. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11412. MeshDistanceMaterial.prototype.copy = function ( source ) {
  11413. Material.prototype.copy.call( this, source );
  11414. this.referencePosition.copy( source.referencePosition );
  11415. this.nearDistance = source.nearDistance;
  11416. this.farDistance = source.farDistance;
  11417. this.skinning = source.skinning;
  11418. this.morphTargets = source.morphTargets;
  11419. this.map = source.map;
  11420. this.alphaMap = source.alphaMap;
  11421. this.displacementMap = source.displacementMap;
  11422. this.displacementScale = source.displacementScale;
  11423. this.displacementBias = source.displacementBias;
  11424. return this;
  11425. };
  11426. 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}";
  11427. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11428. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  11429. let _frustum = new Frustum();
  11430. const _shadowMapSize = new Vector2(),
  11431. _viewportSize = new Vector2(),
  11432. _viewport = new Vector4(),
  11433. _depthMaterials = [],
  11434. _distanceMaterials = [],
  11435. _materialCache = {};
  11436. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  11437. const shadowMaterialVertical = new ShaderMaterial( {
  11438. defines: {
  11439. SAMPLE_RATE: 2.0 / 8.0,
  11440. HALF_SAMPLE_RATE: 1.0 / 8.0
  11441. },
  11442. uniforms: {
  11443. shadow_pass: { value: null },
  11444. resolution: { value: new Vector2() },
  11445. radius: { value: 4.0 }
  11446. },
  11447. vertexShader: vsm_vert,
  11448. fragmentShader: vsm_frag
  11449. } );
  11450. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11451. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11452. const fullScreenTri = new BufferGeometry();
  11453. fullScreenTri.setAttribute(
  11454. 'position',
  11455. new BufferAttribute(
  11456. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  11457. 3
  11458. )
  11459. );
  11460. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  11461. const scope = this;
  11462. this.enabled = false;
  11463. this.autoUpdate = true;
  11464. this.needsUpdate = false;
  11465. this.type = PCFShadowMap;
  11466. this.render = function ( lights, scene, camera ) {
  11467. if ( scope.enabled === false ) return;
  11468. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  11469. if ( lights.length === 0 ) return;
  11470. const currentRenderTarget = _renderer.getRenderTarget();
  11471. const activeCubeFace = _renderer.getActiveCubeFace();
  11472. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11473. const _state = _renderer.state;
  11474. // Set GL state for depth map.
  11475. _state.setBlending( NoBlending );
  11476. _state.buffers.color.setClear( 1, 1, 1, 1 );
  11477. _state.buffers.depth.setTest( true );
  11478. _state.setScissorTest( false );
  11479. // render depth map
  11480. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  11481. const light = lights[ i ];
  11482. const shadow = light.shadow;
  11483. if ( shadow === undefined ) {
  11484. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  11485. continue;
  11486. }
  11487. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  11488. _shadowMapSize.copy( shadow.mapSize );
  11489. const shadowFrameExtents = shadow.getFrameExtents();
  11490. _shadowMapSize.multiply( shadowFrameExtents );
  11491. _viewportSize.copy( shadow.mapSize );
  11492. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  11493. if ( _shadowMapSize.x > maxTextureSize ) {
  11494. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  11495. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11496. shadow.mapSize.x = _viewportSize.x;
  11497. }
  11498. if ( _shadowMapSize.y > maxTextureSize ) {
  11499. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  11500. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11501. shadow.mapSize.y = _viewportSize.y;
  11502. }
  11503. }
  11504. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  11505. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  11506. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11507. shadow.map.texture.name = light.name + '.shadowMap';
  11508. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11509. shadow.camera.updateProjectionMatrix();
  11510. }
  11511. if ( shadow.map === null ) {
  11512. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  11513. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  11514. shadow.map.texture.name = light.name + '.shadowMap';
  11515. shadow.camera.updateProjectionMatrix();
  11516. }
  11517. _renderer.setRenderTarget( shadow.map );
  11518. _renderer.clear();
  11519. const viewportCount = shadow.getViewportCount();
  11520. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  11521. const viewport = shadow.getViewport( vp );
  11522. _viewport.set(
  11523. _viewportSize.x * viewport.x,
  11524. _viewportSize.y * viewport.y,
  11525. _viewportSize.x * viewport.z,
  11526. _viewportSize.y * viewport.w
  11527. );
  11528. _state.viewport( _viewport );
  11529. shadow.updateMatrices( light, vp );
  11530. _frustum = shadow.getFrustum();
  11531. renderObject( scene, camera, shadow.camera, light, this.type );
  11532. }
  11533. // do blur pass for VSM
  11534. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  11535. VSMPass( shadow, camera );
  11536. }
  11537. shadow.needsUpdate = false;
  11538. }
  11539. scope.needsUpdate = false;
  11540. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  11541. };
  11542. function VSMPass( shadow, camera ) {
  11543. const geometry = _objects.update( fullScreenMesh );
  11544. // vertical pass
  11545. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11546. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11547. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11548. _renderer.setRenderTarget( shadow.mapPass );
  11549. _renderer.clear();
  11550. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  11551. // horizontal pass
  11552. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11553. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11554. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11555. _renderer.setRenderTarget( shadow.map );
  11556. _renderer.clear();
  11557. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  11558. }
  11559. function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  11560. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  11561. let material = _depthMaterials[ index ];
  11562. if ( material === undefined ) {
  11563. material = new MeshDepthMaterial( {
  11564. depthPacking: RGBADepthPacking,
  11565. morphTargets: useMorphing,
  11566. skinning: useSkinning
  11567. } );
  11568. _depthMaterials[ index ] = material;
  11569. }
  11570. return material;
  11571. }
  11572. function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  11573. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  11574. let material = _distanceMaterials[ index ];
  11575. if ( material === undefined ) {
  11576. material = new MeshDistanceMaterial( {
  11577. morphTargets: useMorphing,
  11578. skinning: useSkinning
  11579. } );
  11580. _distanceMaterials[ index ] = material;
  11581. }
  11582. return material;
  11583. }
  11584. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  11585. let result = null;
  11586. let getMaterialVariant = getDepthMaterialVariant;
  11587. let customMaterial = object.customDepthMaterial;
  11588. if ( light.isPointLight === true ) {
  11589. getMaterialVariant = getDistanceMaterialVariant;
  11590. customMaterial = object.customDistanceMaterial;
  11591. }
  11592. if ( customMaterial === undefined ) {
  11593. let useMorphing = false;
  11594. if ( material.morphTargets === true ) {
  11595. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11596. }
  11597. let useSkinning = false;
  11598. if ( object.isSkinnedMesh === true ) {
  11599. if ( material.skinning === true ) {
  11600. useSkinning = true;
  11601. } else {
  11602. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  11603. }
  11604. }
  11605. const useInstancing = object.isInstancedMesh === true;
  11606. result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
  11607. } else {
  11608. result = customMaterial;
  11609. }
  11610. if ( _renderer.localClippingEnabled &&
  11611. material.clipShadows === true &&
  11612. material.clippingPlanes.length !== 0 ) {
  11613. // in this case we need a unique material instance reflecting the
  11614. // appropriate state
  11615. const keyA = result.uuid, keyB = material.uuid;
  11616. let materialsForVariant = _materialCache[ keyA ];
  11617. if ( materialsForVariant === undefined ) {
  11618. materialsForVariant = {};
  11619. _materialCache[ keyA ] = materialsForVariant;
  11620. }
  11621. let cachedMaterial = materialsForVariant[ keyB ];
  11622. if ( cachedMaterial === undefined ) {
  11623. cachedMaterial = result.clone();
  11624. materialsForVariant[ keyB ] = cachedMaterial;
  11625. }
  11626. result = cachedMaterial;
  11627. }
  11628. result.visible = material.visible;
  11629. result.wireframe = material.wireframe;
  11630. if ( type === VSMShadowMap ) {
  11631. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  11632. } else {
  11633. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  11634. }
  11635. result.clipShadows = material.clipShadows;
  11636. result.clippingPlanes = material.clippingPlanes;
  11637. result.clipIntersection = material.clipIntersection;
  11638. result.wireframeLinewidth = material.wireframeLinewidth;
  11639. result.linewidth = material.linewidth;
  11640. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  11641. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  11642. result.nearDistance = shadowCameraNear;
  11643. result.farDistance = shadowCameraFar;
  11644. }
  11645. return result;
  11646. }
  11647. function renderObject( object, camera, shadowCamera, light, type ) {
  11648. if ( object.visible === false ) return;
  11649. const visible = object.layers.test( camera.layers );
  11650. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  11651. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  11652. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  11653. const geometry = _objects.update( object );
  11654. const material = object.material;
  11655. if ( Array.isArray( material ) ) {
  11656. const groups = geometry.groups;
  11657. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  11658. const group = groups[ k ];
  11659. const groupMaterial = material[ group.materialIndex ];
  11660. if ( groupMaterial && groupMaterial.visible ) {
  11661. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  11662. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  11663. }
  11664. }
  11665. } else if ( material.visible ) {
  11666. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  11667. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  11668. }
  11669. }
  11670. }
  11671. const children = object.children;
  11672. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11673. renderObject( children[ i ], camera, shadowCamera, light, type );
  11674. }
  11675. }
  11676. }
  11677. function WebGLState( gl, extensions, capabilities ) {
  11678. const isWebGL2 = capabilities.isWebGL2;
  11679. function ColorBuffer() {
  11680. let locked = false;
  11681. const color = new Vector4();
  11682. let currentColorMask = null;
  11683. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  11684. return {
  11685. setMask: function ( colorMask ) {
  11686. if ( currentColorMask !== colorMask && ! locked ) {
  11687. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  11688. currentColorMask = colorMask;
  11689. }
  11690. },
  11691. setLocked: function ( lock ) {
  11692. locked = lock;
  11693. },
  11694. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  11695. if ( premultipliedAlpha === true ) {
  11696. r *= a; g *= a; b *= a;
  11697. }
  11698. color.set( r, g, b, a );
  11699. if ( currentColorClear.equals( color ) === false ) {
  11700. gl.clearColor( r, g, b, a );
  11701. currentColorClear.copy( color );
  11702. }
  11703. },
  11704. reset: function () {
  11705. locked = false;
  11706. currentColorMask = null;
  11707. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  11708. }
  11709. };
  11710. }
  11711. function DepthBuffer() {
  11712. let locked = false;
  11713. let currentDepthMask = null;
  11714. let currentDepthFunc = null;
  11715. let currentDepthClear = null;
  11716. return {
  11717. setTest: function ( depthTest ) {
  11718. if ( depthTest ) {
  11719. enable( 2929 );
  11720. } else {
  11721. disable( 2929 );
  11722. }
  11723. },
  11724. setMask: function ( depthMask ) {
  11725. if ( currentDepthMask !== depthMask && ! locked ) {
  11726. gl.depthMask( depthMask );
  11727. currentDepthMask = depthMask;
  11728. }
  11729. },
  11730. setFunc: function ( depthFunc ) {
  11731. if ( currentDepthFunc !== depthFunc ) {
  11732. if ( depthFunc ) {
  11733. switch ( depthFunc ) {
  11734. case NeverDepth:
  11735. gl.depthFunc( 512 );
  11736. break;
  11737. case AlwaysDepth:
  11738. gl.depthFunc( 519 );
  11739. break;
  11740. case LessDepth:
  11741. gl.depthFunc( 513 );
  11742. break;
  11743. case LessEqualDepth:
  11744. gl.depthFunc( 515 );
  11745. break;
  11746. case EqualDepth:
  11747. gl.depthFunc( 514 );
  11748. break;
  11749. case GreaterEqualDepth:
  11750. gl.depthFunc( 518 );
  11751. break;
  11752. case GreaterDepth:
  11753. gl.depthFunc( 516 );
  11754. break;
  11755. case NotEqualDepth:
  11756. gl.depthFunc( 517 );
  11757. break;
  11758. default:
  11759. gl.depthFunc( 515 );
  11760. }
  11761. } else {
  11762. gl.depthFunc( 515 );
  11763. }
  11764. currentDepthFunc = depthFunc;
  11765. }
  11766. },
  11767. setLocked: function ( lock ) {
  11768. locked = lock;
  11769. },
  11770. setClear: function ( depth ) {
  11771. if ( currentDepthClear !== depth ) {
  11772. gl.clearDepth( depth );
  11773. currentDepthClear = depth;
  11774. }
  11775. },
  11776. reset: function () {
  11777. locked = false;
  11778. currentDepthMask = null;
  11779. currentDepthFunc = null;
  11780. currentDepthClear = null;
  11781. }
  11782. };
  11783. }
  11784. function StencilBuffer() {
  11785. let locked = false;
  11786. let currentStencilMask = null;
  11787. let currentStencilFunc = null;
  11788. let currentStencilRef = null;
  11789. let currentStencilFuncMask = null;
  11790. let currentStencilFail = null;
  11791. let currentStencilZFail = null;
  11792. let currentStencilZPass = null;
  11793. let currentStencilClear = null;
  11794. return {
  11795. setTest: function ( stencilTest ) {
  11796. if ( ! locked ) {
  11797. if ( stencilTest ) {
  11798. enable( 2960 );
  11799. } else {
  11800. disable( 2960 );
  11801. }
  11802. }
  11803. },
  11804. setMask: function ( stencilMask ) {
  11805. if ( currentStencilMask !== stencilMask && ! locked ) {
  11806. gl.stencilMask( stencilMask );
  11807. currentStencilMask = stencilMask;
  11808. }
  11809. },
  11810. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  11811. if ( currentStencilFunc !== stencilFunc ||
  11812. currentStencilRef !== stencilRef ||
  11813. currentStencilFuncMask !== stencilMask ) {
  11814. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  11815. currentStencilFunc = stencilFunc;
  11816. currentStencilRef = stencilRef;
  11817. currentStencilFuncMask = stencilMask;
  11818. }
  11819. },
  11820. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  11821. if ( currentStencilFail !== stencilFail ||
  11822. currentStencilZFail !== stencilZFail ||
  11823. currentStencilZPass !== stencilZPass ) {
  11824. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  11825. currentStencilFail = stencilFail;
  11826. currentStencilZFail = stencilZFail;
  11827. currentStencilZPass = stencilZPass;
  11828. }
  11829. },
  11830. setLocked: function ( lock ) {
  11831. locked = lock;
  11832. },
  11833. setClear: function ( stencil ) {
  11834. if ( currentStencilClear !== stencil ) {
  11835. gl.clearStencil( stencil );
  11836. currentStencilClear = stencil;
  11837. }
  11838. },
  11839. reset: function () {
  11840. locked = false;
  11841. currentStencilMask = null;
  11842. currentStencilFunc = null;
  11843. currentStencilRef = null;
  11844. currentStencilFuncMask = null;
  11845. currentStencilFail = null;
  11846. currentStencilZFail = null;
  11847. currentStencilZPass = null;
  11848. currentStencilClear = null;
  11849. }
  11850. };
  11851. }
  11852. //
  11853. const colorBuffer = new ColorBuffer();
  11854. const depthBuffer = new DepthBuffer();
  11855. const stencilBuffer = new StencilBuffer();
  11856. let enabledCapabilities = {};
  11857. let currentProgram = null;
  11858. let currentBlendingEnabled = null;
  11859. let currentBlending = null;
  11860. let currentBlendEquation = null;
  11861. let currentBlendSrc = null;
  11862. let currentBlendDst = null;
  11863. let currentBlendEquationAlpha = null;
  11864. let currentBlendSrcAlpha = null;
  11865. let currentBlendDstAlpha = null;
  11866. let currentPremultipledAlpha = false;
  11867. let currentFlipSided = null;
  11868. let currentCullFace = null;
  11869. let currentLineWidth = null;
  11870. let currentPolygonOffsetFactor = null;
  11871. let currentPolygonOffsetUnits = null;
  11872. const maxTextures = gl.getParameter( 35661 );
  11873. let lineWidthAvailable = false;
  11874. let version = 0;
  11875. const glVersion = gl.getParameter( 7938 );
  11876. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  11877. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  11878. lineWidthAvailable = ( version >= 1.0 );
  11879. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  11880. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  11881. lineWidthAvailable = ( version >= 2.0 );
  11882. }
  11883. let currentTextureSlot = null;
  11884. let currentBoundTextures = {};
  11885. const currentScissor = new Vector4();
  11886. const currentViewport = new Vector4();
  11887. function createTexture( type, target, count ) {
  11888. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  11889. const texture = gl.createTexture();
  11890. gl.bindTexture( type, texture );
  11891. gl.texParameteri( type, 10241, 9728 );
  11892. gl.texParameteri( type, 10240, 9728 );
  11893. for ( let i = 0; i < count; i ++ ) {
  11894. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  11895. }
  11896. return texture;
  11897. }
  11898. const emptyTextures = {};
  11899. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  11900. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  11901. // init
  11902. colorBuffer.setClear( 0, 0, 0, 1 );
  11903. depthBuffer.setClear( 1 );
  11904. stencilBuffer.setClear( 0 );
  11905. enable( 2929 );
  11906. depthBuffer.setFunc( LessEqualDepth );
  11907. setFlipSided( false );
  11908. setCullFace( CullFaceBack );
  11909. enable( 2884 );
  11910. setBlending( NoBlending );
  11911. //
  11912. function enable( id ) {
  11913. if ( enabledCapabilities[ id ] !== true ) {
  11914. gl.enable( id );
  11915. enabledCapabilities[ id ] = true;
  11916. }
  11917. }
  11918. function disable( id ) {
  11919. if ( enabledCapabilities[ id ] !== false ) {
  11920. gl.disable( id );
  11921. enabledCapabilities[ id ] = false;
  11922. }
  11923. }
  11924. function useProgram( program ) {
  11925. if ( currentProgram !== program ) {
  11926. gl.useProgram( program );
  11927. currentProgram = program;
  11928. return true;
  11929. }
  11930. return false;
  11931. }
  11932. const equationToGL = {
  11933. [ AddEquation ]: 32774,
  11934. [ SubtractEquation ]: 32778,
  11935. [ ReverseSubtractEquation ]: 32779
  11936. };
  11937. if ( isWebGL2 ) {
  11938. equationToGL[ MinEquation ] = 32775;
  11939. equationToGL[ MaxEquation ] = 32776;
  11940. } else {
  11941. const extension = extensions.get( 'EXT_blend_minmax' );
  11942. if ( extension !== null ) {
  11943. equationToGL[ MinEquation ] = extension.MIN_EXT;
  11944. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  11945. }
  11946. }
  11947. const factorToGL = {
  11948. [ ZeroFactor ]: 0,
  11949. [ OneFactor ]: 1,
  11950. [ SrcColorFactor ]: 768,
  11951. [ SrcAlphaFactor ]: 770,
  11952. [ SrcAlphaSaturateFactor ]: 776,
  11953. [ DstColorFactor ]: 774,
  11954. [ DstAlphaFactor ]: 772,
  11955. [ OneMinusSrcColorFactor ]: 769,
  11956. [ OneMinusSrcAlphaFactor ]: 771,
  11957. [ OneMinusDstColorFactor ]: 775,
  11958. [ OneMinusDstAlphaFactor ]: 773
  11959. };
  11960. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  11961. if ( blending === NoBlending ) {
  11962. if ( currentBlendingEnabled ) {
  11963. disable( 3042 );
  11964. currentBlendingEnabled = false;
  11965. }
  11966. return;
  11967. }
  11968. if ( ! currentBlendingEnabled ) {
  11969. enable( 3042 );
  11970. currentBlendingEnabled = true;
  11971. }
  11972. if ( blending !== CustomBlending ) {
  11973. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  11974. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  11975. gl.blendEquation( 32774 );
  11976. currentBlendEquation = AddEquation;
  11977. currentBlendEquationAlpha = AddEquation;
  11978. }
  11979. if ( premultipliedAlpha ) {
  11980. switch ( blending ) {
  11981. case NormalBlending:
  11982. gl.blendFuncSeparate( 1, 771, 1, 771 );
  11983. break;
  11984. case AdditiveBlending:
  11985. gl.blendFunc( 1, 1 );
  11986. break;
  11987. case SubtractiveBlending:
  11988. gl.blendFuncSeparate( 0, 0, 769, 771 );
  11989. break;
  11990. case MultiplyBlending:
  11991. gl.blendFuncSeparate( 0, 768, 0, 770 );
  11992. break;
  11993. default:
  11994. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  11995. break;
  11996. }
  11997. } else {
  11998. switch ( blending ) {
  11999. case NormalBlending:
  12000. gl.blendFuncSeparate( 770, 771, 1, 771 );
  12001. break;
  12002. case AdditiveBlending:
  12003. gl.blendFunc( 770, 1 );
  12004. break;
  12005. case SubtractiveBlending:
  12006. gl.blendFunc( 0, 769 );
  12007. break;
  12008. case MultiplyBlending:
  12009. gl.blendFunc( 0, 768 );
  12010. break;
  12011. default:
  12012. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12013. break;
  12014. }
  12015. }
  12016. currentBlendSrc = null;
  12017. currentBlendDst = null;
  12018. currentBlendSrcAlpha = null;
  12019. currentBlendDstAlpha = null;
  12020. currentBlending = blending;
  12021. currentPremultipledAlpha = premultipliedAlpha;
  12022. }
  12023. return;
  12024. }
  12025. // custom blending
  12026. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12027. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12028. blendDstAlpha = blendDstAlpha || blendDst;
  12029. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  12030. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  12031. currentBlendEquation = blendEquation;
  12032. currentBlendEquationAlpha = blendEquationAlpha;
  12033. }
  12034. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  12035. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  12036. currentBlendSrc = blendSrc;
  12037. currentBlendDst = blendDst;
  12038. currentBlendSrcAlpha = blendSrcAlpha;
  12039. currentBlendDstAlpha = blendDstAlpha;
  12040. }
  12041. currentBlending = blending;
  12042. currentPremultipledAlpha = null;
  12043. }
  12044. function setMaterial( material, frontFaceCW ) {
  12045. material.side === DoubleSide
  12046. ? disable( 2884 )
  12047. : enable( 2884 );
  12048. let flipSided = ( material.side === BackSide );
  12049. if ( frontFaceCW ) flipSided = ! flipSided;
  12050. setFlipSided( flipSided );
  12051. ( material.blending === NormalBlending && material.transparent === false )
  12052. ? setBlending( NoBlending )
  12053. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12054. depthBuffer.setFunc( material.depthFunc );
  12055. depthBuffer.setTest( material.depthTest );
  12056. depthBuffer.setMask( material.depthWrite );
  12057. colorBuffer.setMask( material.colorWrite );
  12058. const stencilWrite = material.stencilWrite;
  12059. stencilBuffer.setTest( stencilWrite );
  12060. if ( stencilWrite ) {
  12061. stencilBuffer.setMask( material.stencilWriteMask );
  12062. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12063. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12064. }
  12065. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12066. }
  12067. //
  12068. function setFlipSided( flipSided ) {
  12069. if ( currentFlipSided !== flipSided ) {
  12070. if ( flipSided ) {
  12071. gl.frontFace( 2304 );
  12072. } else {
  12073. gl.frontFace( 2305 );
  12074. }
  12075. currentFlipSided = flipSided;
  12076. }
  12077. }
  12078. function setCullFace( cullFace ) {
  12079. if ( cullFace !== CullFaceNone ) {
  12080. enable( 2884 );
  12081. if ( cullFace !== currentCullFace ) {
  12082. if ( cullFace === CullFaceBack ) {
  12083. gl.cullFace( 1029 );
  12084. } else if ( cullFace === CullFaceFront ) {
  12085. gl.cullFace( 1028 );
  12086. } else {
  12087. gl.cullFace( 1032 );
  12088. }
  12089. }
  12090. } else {
  12091. disable( 2884 );
  12092. }
  12093. currentCullFace = cullFace;
  12094. }
  12095. function setLineWidth( width ) {
  12096. if ( width !== currentLineWidth ) {
  12097. if ( lineWidthAvailable ) gl.lineWidth( width );
  12098. currentLineWidth = width;
  12099. }
  12100. }
  12101. function setPolygonOffset( polygonOffset, factor, units ) {
  12102. if ( polygonOffset ) {
  12103. enable( 32823 );
  12104. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  12105. gl.polygonOffset( factor, units );
  12106. currentPolygonOffsetFactor = factor;
  12107. currentPolygonOffsetUnits = units;
  12108. }
  12109. } else {
  12110. disable( 32823 );
  12111. }
  12112. }
  12113. function setScissorTest( scissorTest ) {
  12114. if ( scissorTest ) {
  12115. enable( 3089 );
  12116. } else {
  12117. disable( 3089 );
  12118. }
  12119. }
  12120. // texture
  12121. function activeTexture( webglSlot ) {
  12122. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  12123. if ( currentTextureSlot !== webglSlot ) {
  12124. gl.activeTexture( webglSlot );
  12125. currentTextureSlot = webglSlot;
  12126. }
  12127. }
  12128. function bindTexture( webglType, webglTexture ) {
  12129. if ( currentTextureSlot === null ) {
  12130. activeTexture();
  12131. }
  12132. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  12133. if ( boundTexture === undefined ) {
  12134. boundTexture = { type: undefined, texture: undefined };
  12135. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  12136. }
  12137. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  12138. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  12139. boundTexture.type = webglType;
  12140. boundTexture.texture = webglTexture;
  12141. }
  12142. }
  12143. function unbindTexture() {
  12144. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  12145. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  12146. gl.bindTexture( boundTexture.type, null );
  12147. boundTexture.type = undefined;
  12148. boundTexture.texture = undefined;
  12149. }
  12150. }
  12151. function compressedTexImage2D() {
  12152. try {
  12153. gl.compressedTexImage2D.apply( gl, arguments );
  12154. } catch ( error ) {
  12155. console.error( 'THREE.WebGLState:', error );
  12156. }
  12157. }
  12158. function texImage2D() {
  12159. try {
  12160. gl.texImage2D.apply( gl, arguments );
  12161. } catch ( error ) {
  12162. console.error( 'THREE.WebGLState:', error );
  12163. }
  12164. }
  12165. function texImage3D() {
  12166. try {
  12167. gl.texImage3D.apply( gl, arguments );
  12168. } catch ( error ) {
  12169. console.error( 'THREE.WebGLState:', error );
  12170. }
  12171. }
  12172. //
  12173. function scissor( scissor ) {
  12174. if ( currentScissor.equals( scissor ) === false ) {
  12175. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12176. currentScissor.copy( scissor );
  12177. }
  12178. }
  12179. function viewport( viewport ) {
  12180. if ( currentViewport.equals( viewport ) === false ) {
  12181. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12182. currentViewport.copy( viewport );
  12183. }
  12184. }
  12185. //
  12186. function reset() {
  12187. enabledCapabilities = {};
  12188. currentTextureSlot = null;
  12189. currentBoundTextures = {};
  12190. currentProgram = null;
  12191. currentBlendingEnabled = null;
  12192. currentBlending = null;
  12193. currentBlendEquation = null;
  12194. currentBlendSrc = null;
  12195. currentBlendDst = null;
  12196. currentBlendEquationAlpha = null;
  12197. currentBlendSrcAlpha = null;
  12198. currentBlendDstAlpha = null;
  12199. currentPremultipledAlpha = false;
  12200. currentFlipSided = null;
  12201. currentCullFace = null;
  12202. currentLineWidth = null;
  12203. currentPolygonOffsetFactor = null;
  12204. currentPolygonOffsetUnits = null;
  12205. colorBuffer.reset();
  12206. depthBuffer.reset();
  12207. stencilBuffer.reset();
  12208. }
  12209. return {
  12210. buffers: {
  12211. color: colorBuffer,
  12212. depth: depthBuffer,
  12213. stencil: stencilBuffer
  12214. },
  12215. enable: enable,
  12216. disable: disable,
  12217. useProgram: useProgram,
  12218. setBlending: setBlending,
  12219. setMaterial: setMaterial,
  12220. setFlipSided: setFlipSided,
  12221. setCullFace: setCullFace,
  12222. setLineWidth: setLineWidth,
  12223. setPolygonOffset: setPolygonOffset,
  12224. setScissorTest: setScissorTest,
  12225. activeTexture: activeTexture,
  12226. bindTexture: bindTexture,
  12227. unbindTexture: unbindTexture,
  12228. compressedTexImage2D: compressedTexImage2D,
  12229. texImage2D: texImage2D,
  12230. texImage3D: texImage3D,
  12231. scissor: scissor,
  12232. viewport: viewport,
  12233. reset: reset
  12234. };
  12235. }
  12236. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  12237. const isWebGL2 = capabilities.isWebGL2;
  12238. const maxTextures = capabilities.maxTextures;
  12239. const maxCubemapSize = capabilities.maxCubemapSize;
  12240. const maxTextureSize = capabilities.maxTextureSize;
  12241. const maxSamples = capabilities.maxSamples;
  12242. const _videoTextures = new WeakMap();
  12243. let _canvas;
  12244. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12245. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12246. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12247. let useOffscreenCanvas = false;
  12248. try {
  12249. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  12250. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  12251. } catch ( err ) {
  12252. // Ignore any errors
  12253. }
  12254. function createCanvas( width, height ) {
  12255. // Use OffscreenCanvas when available. Specially needed in web workers
  12256. return useOffscreenCanvas ?
  12257. new OffscreenCanvas( width, height ) :
  12258. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  12259. }
  12260. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  12261. let scale = 1;
  12262. // handle case if texture exceeds max size
  12263. if ( image.width > maxSize || image.height > maxSize ) {
  12264. scale = maxSize / Math.max( image.width, image.height );
  12265. }
  12266. // only perform resize if necessary
  12267. if ( scale < 1 || needsPowerOfTwo === true ) {
  12268. // only perform resize for certain image types
  12269. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  12270. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  12271. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  12272. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  12273. const width = floor( scale * image.width );
  12274. const height = floor( scale * image.height );
  12275. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  12276. // cube textures can't reuse the same canvas
  12277. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  12278. canvas.width = width;
  12279. canvas.height = height;
  12280. const context = canvas.getContext( '2d' );
  12281. context.drawImage( image, 0, 0, width, height );
  12282. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  12283. return canvas;
  12284. } else {
  12285. if ( 'data' in image ) {
  12286. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  12287. }
  12288. return image;
  12289. }
  12290. }
  12291. return image;
  12292. }
  12293. function isPowerOfTwo( image ) {
  12294. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  12295. }
  12296. function textureNeedsPowerOfTwo( texture ) {
  12297. if ( isWebGL2 ) return false;
  12298. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  12299. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  12300. }
  12301. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  12302. return texture.generateMipmaps && supportsMips &&
  12303. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12304. }
  12305. function generateMipmap( target, texture, width, height ) {
  12306. _gl.generateMipmap( target );
  12307. const textureProperties = properties.get( texture );
  12308. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  12309. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  12310. }
  12311. function getInternalFormat( internalFormatName, glFormat, glType ) {
  12312. if ( isWebGL2 === false ) return glFormat;
  12313. if ( internalFormatName !== null ) {
  12314. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  12315. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  12316. }
  12317. let internalFormat = glFormat;
  12318. if ( glFormat === 6403 ) {
  12319. if ( glType === 5126 ) internalFormat = 33326;
  12320. if ( glType === 5131 ) internalFormat = 33325;
  12321. if ( glType === 5121 ) internalFormat = 33321;
  12322. }
  12323. if ( glFormat === 6407 ) {
  12324. if ( glType === 5126 ) internalFormat = 34837;
  12325. if ( glType === 5131 ) internalFormat = 34843;
  12326. if ( glType === 5121 ) internalFormat = 32849;
  12327. }
  12328. if ( glFormat === 6408 ) {
  12329. if ( glType === 5126 ) internalFormat = 34836;
  12330. if ( glType === 5131 ) internalFormat = 34842;
  12331. if ( glType === 5121 ) internalFormat = 32856;
  12332. }
  12333. if ( internalFormat === 33325 || internalFormat === 33326 ||
  12334. internalFormat === 34842 || internalFormat === 34836 ) {
  12335. extensions.get( 'EXT_color_buffer_float' );
  12336. }
  12337. return internalFormat;
  12338. }
  12339. // Fallback filters for non-power-of-2 textures
  12340. function filterFallback( f ) {
  12341. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  12342. return 9728;
  12343. }
  12344. return 9729;
  12345. }
  12346. //
  12347. function onTextureDispose( event ) {
  12348. const texture = event.target;
  12349. texture.removeEventListener( 'dispose', onTextureDispose );
  12350. deallocateTexture( texture );
  12351. if ( texture.isVideoTexture ) {
  12352. _videoTextures.delete( texture );
  12353. }
  12354. info.memory.textures --;
  12355. }
  12356. function onRenderTargetDispose( event ) {
  12357. const renderTarget = event.target;
  12358. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12359. deallocateRenderTarget( renderTarget );
  12360. info.memory.textures --;
  12361. }
  12362. //
  12363. function deallocateTexture( texture ) {
  12364. const textureProperties = properties.get( texture );
  12365. if ( textureProperties.__webglInit === undefined ) return;
  12366. _gl.deleteTexture( textureProperties.__webglTexture );
  12367. properties.remove( texture );
  12368. }
  12369. function deallocateRenderTarget( renderTarget ) {
  12370. const renderTargetProperties = properties.get( renderTarget );
  12371. const textureProperties = properties.get( renderTarget.texture );
  12372. if ( ! renderTarget ) return;
  12373. if ( textureProperties.__webglTexture !== undefined ) {
  12374. _gl.deleteTexture( textureProperties.__webglTexture );
  12375. }
  12376. if ( renderTarget.depthTexture ) {
  12377. renderTarget.depthTexture.dispose();
  12378. }
  12379. if ( renderTarget.isWebGLCubeRenderTarget ) {
  12380. for ( let i = 0; i < 6; i ++ ) {
  12381. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  12382. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  12383. }
  12384. } else {
  12385. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  12386. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  12387. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  12388. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  12389. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  12390. }
  12391. properties.remove( renderTarget.texture );
  12392. properties.remove( renderTarget );
  12393. }
  12394. //
  12395. let textureUnits = 0;
  12396. function resetTextureUnits() {
  12397. textureUnits = 0;
  12398. }
  12399. function allocateTextureUnit() {
  12400. const textureUnit = textureUnits;
  12401. if ( textureUnit >= maxTextures ) {
  12402. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  12403. }
  12404. textureUnits += 1;
  12405. return textureUnit;
  12406. }
  12407. //
  12408. function setTexture2D( texture, slot ) {
  12409. const textureProperties = properties.get( texture );
  12410. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  12411. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12412. const image = texture.image;
  12413. if ( image === undefined ) {
  12414. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  12415. } else if ( image.complete === false ) {
  12416. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  12417. } else {
  12418. uploadTexture( textureProperties, texture, slot );
  12419. return;
  12420. }
  12421. }
  12422. state.activeTexture( 33984 + slot );
  12423. state.bindTexture( 3553, textureProperties.__webglTexture );
  12424. }
  12425. function setTexture2DArray( texture, slot ) {
  12426. const textureProperties = properties.get( texture );
  12427. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12428. uploadTexture( textureProperties, texture, slot );
  12429. return;
  12430. }
  12431. state.activeTexture( 33984 + slot );
  12432. state.bindTexture( 35866, textureProperties.__webglTexture );
  12433. }
  12434. function setTexture3D( texture, slot ) {
  12435. const textureProperties = properties.get( texture );
  12436. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12437. uploadTexture( textureProperties, texture, slot );
  12438. return;
  12439. }
  12440. state.activeTexture( 33984 + slot );
  12441. state.bindTexture( 32879, textureProperties.__webglTexture );
  12442. }
  12443. function setTextureCube( texture, slot ) {
  12444. const textureProperties = properties.get( texture );
  12445. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  12446. uploadCubeTexture( textureProperties, texture, slot );
  12447. return;
  12448. }
  12449. state.activeTexture( 33984 + slot );
  12450. state.bindTexture( 34067, textureProperties.__webglTexture );
  12451. }
  12452. const wrappingToGL = {
  12453. [ RepeatWrapping ]: 10497,
  12454. [ ClampToEdgeWrapping ]: 33071,
  12455. [ MirroredRepeatWrapping ]: 33648
  12456. };
  12457. const filterToGL = {
  12458. [ NearestFilter ]: 9728,
  12459. [ NearestMipmapNearestFilter ]: 9984,
  12460. [ NearestMipmapLinearFilter ]: 9986,
  12461. [ LinearFilter ]: 9729,
  12462. [ LinearMipmapNearestFilter ]: 9985,
  12463. [ LinearMipmapLinearFilter ]: 9987
  12464. };
  12465. function setTextureParameters( textureType, texture, supportsMips ) {
  12466. if ( supportsMips ) {
  12467. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  12468. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  12469. if ( textureType === 32879 || textureType === 35866 ) {
  12470. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  12471. }
  12472. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  12473. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  12474. } else {
  12475. _gl.texParameteri( textureType, 10242, 33071 );
  12476. _gl.texParameteri( textureType, 10243, 33071 );
  12477. if ( textureType === 32879 || textureType === 35866 ) {
  12478. _gl.texParameteri( textureType, 32882, 33071 );
  12479. }
  12480. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  12481. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  12482. }
  12483. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  12484. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  12485. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  12486. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  12487. }
  12488. }
  12489. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12490. if ( extension ) {
  12491. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  12492. if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  12493. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  12494. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  12495. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  12496. }
  12497. }
  12498. }
  12499. function initTexture( textureProperties, texture ) {
  12500. if ( textureProperties.__webglInit === undefined ) {
  12501. textureProperties.__webglInit = true;
  12502. texture.addEventListener( 'dispose', onTextureDispose );
  12503. textureProperties.__webglTexture = _gl.createTexture();
  12504. info.memory.textures ++;
  12505. }
  12506. }
  12507. function uploadTexture( textureProperties, texture, slot ) {
  12508. let textureType = 3553;
  12509. if ( texture.isDataTexture2DArray ) textureType = 35866;
  12510. if ( texture.isDataTexture3D ) textureType = 32879;
  12511. initTexture( textureProperties, texture );
  12512. state.activeTexture( 33984 + slot );
  12513. state.bindTexture( textureType, textureProperties.__webglTexture );
  12514. _gl.pixelStorei( 37440, texture.flipY );
  12515. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  12516. _gl.pixelStorei( 3317, texture.unpackAlignment );
  12517. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  12518. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  12519. const supportsMips = isPowerOfTwo( image ) || isWebGL2,
  12520. glFormat = utils.convert( texture.format );
  12521. let glType = utils.convert( texture.type ),
  12522. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12523. setTextureParameters( textureType, texture, supportsMips );
  12524. let mipmap;
  12525. const mipmaps = texture.mipmaps;
  12526. if ( texture.isDepthTexture ) {
  12527. // populate depth texture with dummy data
  12528. glInternalFormat = 6402;
  12529. if ( isWebGL2 ) {
  12530. if ( texture.type === FloatType ) {
  12531. glInternalFormat = 36012;
  12532. } else if ( texture.type === UnsignedIntType ) {
  12533. glInternalFormat = 33190;
  12534. } else if ( texture.type === UnsignedInt248Type$1 ) {
  12535. glInternalFormat = 35056;
  12536. } else {
  12537. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  12538. }
  12539. } else {
  12540. if ( texture.type === FloatType ) {
  12541. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  12542. }
  12543. }
  12544. // validation checks for WebGL 1
  12545. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  12546. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12547. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12548. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12549. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  12550. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  12551. texture.type = UnsignedShortType;
  12552. glType = utils.convert( texture.type );
  12553. }
  12554. }
  12555. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  12556. // Depth stencil textures need the DEPTH_STENCIL internal format
  12557. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12558. glInternalFormat = 34041;
  12559. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12560. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12561. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12562. if ( texture.type !== UnsignedInt248Type$1 ) {
  12563. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  12564. texture.type = UnsignedInt248Type$1;
  12565. glType = utils.convert( texture.type );
  12566. }
  12567. }
  12568. //
  12569. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  12570. } else if ( texture.isDataTexture ) {
  12571. // use manually created mipmaps if available
  12572. // if there are no manual mipmaps
  12573. // set 0 level mipmap and then use GL to generate other mipmap levels
  12574. if ( mipmaps.length > 0 && supportsMips ) {
  12575. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12576. mipmap = mipmaps[ i ];
  12577. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12578. }
  12579. texture.generateMipmaps = false;
  12580. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12581. } else {
  12582. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12583. textureProperties.__maxMipLevel = 0;
  12584. }
  12585. } else if ( texture.isCompressedTexture ) {
  12586. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12587. mipmap = mipmaps[ i ];
  12588. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  12589. if ( glFormat !== null ) {
  12590. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12591. } else {
  12592. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  12593. }
  12594. } else {
  12595. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12596. }
  12597. }
  12598. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12599. } else if ( texture.isDataTexture2DArray ) {
  12600. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  12601. textureProperties.__maxMipLevel = 0;
  12602. } else if ( texture.isDataTexture3D ) {
  12603. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  12604. textureProperties.__maxMipLevel = 0;
  12605. } else {
  12606. // regular Texture (image, video, canvas)
  12607. // use manually created mipmaps if available
  12608. // if there are no manual mipmaps
  12609. // set 0 level mipmap and then use GL to generate other mipmap levels
  12610. if ( mipmaps.length > 0 && supportsMips ) {
  12611. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  12612. mipmap = mipmaps[ i ];
  12613. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  12614. }
  12615. texture.generateMipmaps = false;
  12616. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12617. } else {
  12618. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  12619. textureProperties.__maxMipLevel = 0;
  12620. }
  12621. }
  12622. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12623. generateMipmap( textureType, texture, image.width, image.height );
  12624. }
  12625. textureProperties.__version = texture.version;
  12626. if ( texture.onUpdate ) texture.onUpdate( texture );
  12627. }
  12628. function uploadCubeTexture( textureProperties, texture, slot ) {
  12629. if ( texture.image.length !== 6 ) return;
  12630. initTexture( textureProperties, texture );
  12631. state.activeTexture( 33984 + slot );
  12632. state.bindTexture( 34067, textureProperties.__webglTexture );
  12633. _gl.pixelStorei( 37440, texture.flipY );
  12634. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  12635. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  12636. const cubeImage = [];
  12637. for ( let i = 0; i < 6; i ++ ) {
  12638. if ( ! isCompressed && ! isDataTexture ) {
  12639. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  12640. } else {
  12641. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  12642. }
  12643. }
  12644. const image = cubeImage[ 0 ],
  12645. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  12646. glFormat = utils.convert( texture.format ),
  12647. glType = utils.convert( texture.type ),
  12648. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  12649. setTextureParameters( 34067, texture, supportsMips );
  12650. let mipmaps;
  12651. if ( isCompressed ) {
  12652. for ( let i = 0; i < 6; i ++ ) {
  12653. mipmaps = cubeImage[ i ].mipmaps;
  12654. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12655. const mipmap = mipmaps[ j ];
  12656. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  12657. if ( glFormat !== null ) {
  12658. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12659. } else {
  12660. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  12661. }
  12662. } else {
  12663. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12664. }
  12665. }
  12666. }
  12667. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12668. } else {
  12669. mipmaps = texture.mipmaps;
  12670. for ( let i = 0; i < 6; i ++ ) {
  12671. if ( isDataTexture ) {
  12672. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  12673. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12674. const mipmap = mipmaps[ j ];
  12675. const mipmapImage = mipmap.image[ i ].image;
  12676. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  12677. }
  12678. } else {
  12679. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  12680. for ( let j = 0; j < mipmaps.length; j ++ ) {
  12681. const mipmap = mipmaps[ j ];
  12682. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  12683. }
  12684. }
  12685. }
  12686. textureProperties.__maxMipLevel = mipmaps.length;
  12687. }
  12688. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12689. // We assume images for cube map have the same size.
  12690. generateMipmap( 34067, texture, image.width, image.height );
  12691. }
  12692. textureProperties.__version = texture.version;
  12693. if ( texture.onUpdate ) texture.onUpdate( texture );
  12694. }
  12695. // Render targets
  12696. // Setup storage for target texture and bind it to correct framebuffer
  12697. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  12698. const glFormat = utils.convert( renderTarget.texture.format );
  12699. const glType = utils.convert( renderTarget.texture.type );
  12700. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  12701. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12702. _gl.bindFramebuffer( 36160, framebuffer );
  12703. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  12704. _gl.bindFramebuffer( 36160, null );
  12705. }
  12706. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12707. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  12708. _gl.bindRenderbuffer( 36161, renderbuffer );
  12709. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  12710. let glInternalFormat = 33189;
  12711. if ( isMultisample ) {
  12712. const depthTexture = renderTarget.depthTexture;
  12713. if ( depthTexture && depthTexture.isDepthTexture ) {
  12714. if ( depthTexture.type === FloatType ) {
  12715. glInternalFormat = 36012;
  12716. } else if ( depthTexture.type === UnsignedIntType ) {
  12717. glInternalFormat = 33190;
  12718. }
  12719. }
  12720. const samples = getRenderTargetSamples( renderTarget );
  12721. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12722. } else {
  12723. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  12724. }
  12725. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  12726. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12727. if ( isMultisample ) {
  12728. const samples = getRenderTargetSamples( renderTarget );
  12729. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  12730. } else {
  12731. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  12732. }
  12733. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  12734. } else {
  12735. const glFormat = utils.convert( renderTarget.texture.format );
  12736. const glType = utils.convert( renderTarget.texture.type );
  12737. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  12738. if ( isMultisample ) {
  12739. const samples = getRenderTargetSamples( renderTarget );
  12740. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12741. } else {
  12742. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  12743. }
  12744. }
  12745. _gl.bindRenderbuffer( 36161, null );
  12746. }
  12747. // Setup resources for a Depth Texture for a FBO (needs an extension)
  12748. function setupDepthTexture( framebuffer, renderTarget ) {
  12749. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  12750. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  12751. _gl.bindFramebuffer( 36160, framebuffer );
  12752. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  12753. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  12754. }
  12755. // upload an empty depth texture with framebuffer size
  12756. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  12757. renderTarget.depthTexture.image.width !== renderTarget.width ||
  12758. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  12759. renderTarget.depthTexture.image.width = renderTarget.width;
  12760. renderTarget.depthTexture.image.height = renderTarget.height;
  12761. renderTarget.depthTexture.needsUpdate = true;
  12762. }
  12763. setTexture2D( renderTarget.depthTexture, 0 );
  12764. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  12765. if ( renderTarget.depthTexture.format === DepthFormat ) {
  12766. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  12767. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  12768. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  12769. } else {
  12770. throw new Error( 'Unknown depthTexture format' );
  12771. }
  12772. }
  12773. // Setup GL resources for a non-texture depth buffer
  12774. function setupDepthRenderbuffer( renderTarget ) {
  12775. const renderTargetProperties = properties.get( renderTarget );
  12776. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  12777. if ( renderTarget.depthTexture ) {
  12778. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  12779. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  12780. } else {
  12781. if ( isCube ) {
  12782. renderTargetProperties.__webglDepthbuffer = [];
  12783. for ( let i = 0; i < 6; i ++ ) {
  12784. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  12785. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  12786. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  12787. }
  12788. } else {
  12789. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  12790. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12791. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  12792. }
  12793. }
  12794. _gl.bindFramebuffer( 36160, null );
  12795. }
  12796. // Set up GL resources for the render target
  12797. function setupRenderTarget( renderTarget ) {
  12798. const renderTargetProperties = properties.get( renderTarget );
  12799. const textureProperties = properties.get( renderTarget.texture );
  12800. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  12801. textureProperties.__webglTexture = _gl.createTexture();
  12802. info.memory.textures ++;
  12803. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  12804. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  12805. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  12806. // Handles WebGL2 RGBFormat fallback - #18858
  12807. if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
  12808. renderTarget.texture.format = RGBAFormat;
  12809. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  12810. }
  12811. // Setup framebuffer
  12812. if ( isCube ) {
  12813. renderTargetProperties.__webglFramebuffer = [];
  12814. for ( let i = 0; i < 6; i ++ ) {
  12815. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  12816. }
  12817. } else {
  12818. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12819. if ( isMultisample ) {
  12820. if ( isWebGL2 ) {
  12821. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  12822. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  12823. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  12824. const glFormat = utils.convert( renderTarget.texture.format );
  12825. const glType = utils.convert( renderTarget.texture.type );
  12826. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  12827. const samples = getRenderTargetSamples( renderTarget );
  12828. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  12829. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  12830. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  12831. _gl.bindRenderbuffer( 36161, null );
  12832. if ( renderTarget.depthBuffer ) {
  12833. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  12834. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  12835. }
  12836. _gl.bindFramebuffer( 36160, null );
  12837. } else {
  12838. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  12839. }
  12840. }
  12841. }
  12842. // Setup color buffer
  12843. if ( isCube ) {
  12844. state.bindTexture( 34067, textureProperties.__webglTexture );
  12845. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  12846. for ( let i = 0; i < 6; i ++ ) {
  12847. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  12848. }
  12849. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  12850. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  12851. }
  12852. state.bindTexture( 34067, null );
  12853. } else {
  12854. state.bindTexture( 3553, textureProperties.__webglTexture );
  12855. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  12856. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  12857. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  12858. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  12859. }
  12860. state.bindTexture( 3553, null );
  12861. }
  12862. // Setup depth and stencil buffers
  12863. if ( renderTarget.depthBuffer ) {
  12864. setupDepthRenderbuffer( renderTarget );
  12865. }
  12866. }
  12867. function updateRenderTargetMipmap( renderTarget ) {
  12868. const texture = renderTarget.texture;
  12869. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  12870. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  12871. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  12872. const webglTexture = properties.get( texture ).__webglTexture;
  12873. state.bindTexture( target, webglTexture );
  12874. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  12875. state.bindTexture( target, null );
  12876. }
  12877. }
  12878. function updateMultisampleRenderTarget( renderTarget ) {
  12879. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  12880. if ( isWebGL2 ) {
  12881. const renderTargetProperties = properties.get( renderTarget );
  12882. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  12883. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  12884. const width = renderTarget.width;
  12885. const height = renderTarget.height;
  12886. let mask = 16384;
  12887. if ( renderTarget.depthBuffer ) mask |= 256;
  12888. if ( renderTarget.stencilBuffer ) mask |= 1024;
  12889. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  12890. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  12891. } else {
  12892. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  12893. }
  12894. }
  12895. }
  12896. function getRenderTargetSamples( renderTarget ) {
  12897. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  12898. Math.min( maxSamples, renderTarget.samples ) : 0;
  12899. }
  12900. function updateVideoTexture( texture ) {
  12901. const frame = info.render.frame;
  12902. // Check the last frame we updated the VideoTexture
  12903. if ( _videoTextures.get( texture ) !== frame ) {
  12904. _videoTextures.set( texture, frame );
  12905. texture.update();
  12906. }
  12907. }
  12908. // backwards compatibility
  12909. let warnedTexture2D = false;
  12910. let warnedTextureCube = false;
  12911. function safeSetTexture2D( texture, slot ) {
  12912. if ( texture && texture.isWebGLRenderTarget ) {
  12913. if ( warnedTexture2D === false ) {
  12914. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  12915. warnedTexture2D = true;
  12916. }
  12917. texture = texture.texture;
  12918. }
  12919. setTexture2D( texture, slot );
  12920. }
  12921. function safeSetTextureCube( texture, slot ) {
  12922. if ( texture && texture.isWebGLCubeRenderTarget ) {
  12923. if ( warnedTextureCube === false ) {
  12924. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  12925. warnedTextureCube = true;
  12926. }
  12927. texture = texture.texture;
  12928. }
  12929. setTextureCube( texture, slot );
  12930. }
  12931. //
  12932. this.allocateTextureUnit = allocateTextureUnit;
  12933. this.resetTextureUnits = resetTextureUnits;
  12934. this.setTexture2D = setTexture2D;
  12935. this.setTexture2DArray = setTexture2DArray;
  12936. this.setTexture3D = setTexture3D;
  12937. this.setTextureCube = setTextureCube;
  12938. this.setupRenderTarget = setupRenderTarget;
  12939. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  12940. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  12941. this.safeSetTexture2D = safeSetTexture2D;
  12942. this.safeSetTextureCube = safeSetTextureCube;
  12943. }
  12944. function WebGLUtils( gl, extensions, capabilities ) {
  12945. const isWebGL2 = capabilities.isWebGL2;
  12946. function convert( p ) {
  12947. let extension;
  12948. if ( p === UnsignedByteType ) return 5121;
  12949. if ( p === UnsignedShort4444Type ) return 32819;
  12950. if ( p === UnsignedShort5551Type ) return 32820;
  12951. if ( p === UnsignedShort565Type ) return 33635;
  12952. if ( p === ByteType ) return 5120;
  12953. if ( p === ShortType ) return 5122;
  12954. if ( p === UnsignedShortType ) return 5123;
  12955. if ( p === IntType ) return 5124;
  12956. if ( p === UnsignedIntType ) return 5125;
  12957. if ( p === FloatType ) return 5126;
  12958. if ( p === HalfFloatType ) {
  12959. if ( isWebGL2 ) return 5131;
  12960. extension = extensions.get( 'OES_texture_half_float' );
  12961. if ( extension !== null ) {
  12962. return extension.HALF_FLOAT_OES;
  12963. } else {
  12964. return null;
  12965. }
  12966. }
  12967. if ( p === AlphaFormat ) return 6406;
  12968. if ( p === RGBFormat ) return 6407;
  12969. if ( p === RGBAFormat ) return 6408;
  12970. if ( p === LuminanceFormat ) return 6409;
  12971. if ( p === LuminanceAlphaFormat ) return 6410;
  12972. if ( p === DepthFormat ) return 6402;
  12973. if ( p === DepthStencilFormat ) return 34041;
  12974. if ( p === RedFormat ) return 6403;
  12975. // WebGL2 formats.
  12976. if ( p === RedIntegerFormat ) return 36244;
  12977. if ( p === RGFormat ) return 33319;
  12978. if ( p === RGIntegerFormat ) return 33320;
  12979. if ( p === RGBIntegerFormat ) return 36248;
  12980. if ( p === RGBAIntegerFormat ) return 36249;
  12981. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format$1 ||
  12982. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format$1 ) {
  12983. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  12984. if ( extension !== null ) {
  12985. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  12986. if ( p === RGBA_S3TC_DXT1_Format$1 ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  12987. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  12988. if ( p === RGBA_S3TC_DXT5_Format$1 ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  12989. } else {
  12990. return null;
  12991. }
  12992. }
  12993. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  12994. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  12995. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  12996. if ( extension !== null ) {
  12997. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  12998. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  12999. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13000. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13001. } else {
  13002. return null;
  13003. }
  13004. }
  13005. if ( p === RGB_ETC1_Format ) {
  13006. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13007. if ( extension !== null ) {
  13008. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13009. } else {
  13010. return null;
  13011. }
  13012. }
  13013. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  13014. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  13015. if ( extension !== null ) {
  13016. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  13017. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13018. }
  13019. }
  13020. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  13021. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  13022. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  13023. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  13024. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  13025. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  13026. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  13027. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  13028. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  13029. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  13030. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  13031. if ( extension !== null ) {
  13032. // TODO Complete?
  13033. return p;
  13034. } else {
  13035. return null;
  13036. }
  13037. }
  13038. if ( p === RGBA_BPTC_Format ) {
  13039. extension = extensions.get( 'EXT_texture_compression_bptc' );
  13040. if ( extension !== null ) {
  13041. // TODO Complete?
  13042. return p;
  13043. } else {
  13044. return null;
  13045. }
  13046. }
  13047. if ( p === UnsignedInt248Type$1 ) {
  13048. if ( isWebGL2 ) return 34042;
  13049. extension = extensions.get( 'WEBGL_depth_texture' );
  13050. if ( extension !== null ) {
  13051. return extension.UNSIGNED_INT_24_8_WEBGL;
  13052. } else {
  13053. return null;
  13054. }
  13055. }
  13056. }
  13057. return { convert: convert };
  13058. }
  13059. function ArrayCamera( array = [] ) {
  13060. PerspectiveCamera.call( this );
  13061. this.cameras = array;
  13062. }
  13063. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  13064. constructor: ArrayCamera,
  13065. isArrayCamera: true
  13066. } );
  13067. function Group() {
  13068. Object3D.call( this );
  13069. this.type = 'Group';
  13070. }
  13071. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13072. constructor: Group,
  13073. isGroup: true
  13074. } );
  13075. function WebXRController() {
  13076. this._targetRay = null;
  13077. this._grip = null;
  13078. this._hand = null;
  13079. }
  13080. Object.assign( WebXRController.prototype, {
  13081. constructor: WebXRController,
  13082. getHandSpace: function () {
  13083. if ( this._hand === null ) {
  13084. this._hand = new Group();
  13085. this._hand.matrixAutoUpdate = false;
  13086. this._hand.visible = false;
  13087. this._hand.joints = [];
  13088. this._hand.inputState = { pinching: false };
  13089. if ( window.XRHand ) {
  13090. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13091. // The transform of this joint will be updated with the joint pose on each frame
  13092. const joint = new Group();
  13093. joint.matrixAutoUpdate = false;
  13094. joint.visible = false;
  13095. this._hand.joints.push( joint );
  13096. // ??
  13097. this._hand.add( joint );
  13098. }
  13099. }
  13100. }
  13101. return this._hand;
  13102. },
  13103. getTargetRaySpace: function () {
  13104. if ( this._targetRay === null ) {
  13105. this._targetRay = new Group();
  13106. this._targetRay.matrixAutoUpdate = false;
  13107. this._targetRay.visible = false;
  13108. }
  13109. return this._targetRay;
  13110. },
  13111. getGripSpace: function () {
  13112. if ( this._grip === null ) {
  13113. this._grip = new Group();
  13114. this._grip.matrixAutoUpdate = false;
  13115. this._grip.visible = false;
  13116. }
  13117. return this._grip;
  13118. },
  13119. dispatchEvent: function ( event ) {
  13120. if ( this._targetRay !== null ) {
  13121. this._targetRay.dispatchEvent( event );
  13122. }
  13123. if ( this._grip !== null ) {
  13124. this._grip.dispatchEvent( event );
  13125. }
  13126. if ( this._hand !== null ) {
  13127. this._hand.dispatchEvent( event );
  13128. }
  13129. return this;
  13130. },
  13131. disconnect: function ( inputSource ) {
  13132. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13133. if ( this._targetRay !== null ) {
  13134. this._targetRay.visible = false;
  13135. }
  13136. if ( this._grip !== null ) {
  13137. this._grip.visible = false;
  13138. }
  13139. if ( this._hand !== null ) {
  13140. this._hand.visible = false;
  13141. }
  13142. return this;
  13143. },
  13144. update: function ( inputSource, frame, referenceSpace ) {
  13145. let inputPose = null;
  13146. let gripPose = null;
  13147. let handPose = null;
  13148. const targetRay = this._targetRay;
  13149. const grip = this._grip;
  13150. const hand = this._hand;
  13151. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13152. if ( hand && inputSource.hand ) {
  13153. handPose = true;
  13154. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13155. if ( inputSource.hand[ i ] ) {
  13156. // Update the joints groups with the XRJoint poses
  13157. const jointPose = frame.getJointPose( inputSource.hand[ i ], referenceSpace );
  13158. const joint = hand.joints[ i ];
  13159. if ( jointPose !== null ) {
  13160. joint.matrix.fromArray( jointPose.transform.matrix );
  13161. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13162. joint.jointRadius = jointPose.radius;
  13163. }
  13164. joint.visible = jointPose !== null;
  13165. // Custom events
  13166. // Check pinch
  13167. const indexTip = hand.joints[ window.XRHand.INDEX_PHALANX_TIP ];
  13168. const thumbTip = hand.joints[ window.XRHand.THUMB_PHALANX_TIP ];
  13169. const distance = indexTip.position.distanceTo( thumbTip.position );
  13170. const distanceToPinch = 0.02;
  13171. const threshold = 0.005;
  13172. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13173. hand.inputState.pinching = false;
  13174. this.dispatchEvent( {
  13175. type: 'pinchend',
  13176. handedness: inputSource.handedness,
  13177. target: this
  13178. } );
  13179. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13180. hand.inputState.pinching = true;
  13181. this.dispatchEvent( {
  13182. type: 'pinchstart',
  13183. handedness: inputSource.handedness,
  13184. target: this
  13185. } );
  13186. }
  13187. }
  13188. }
  13189. } else {
  13190. if ( targetRay !== null ) {
  13191. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13192. if ( inputPose !== null ) {
  13193. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13194. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13195. }
  13196. }
  13197. if ( grip !== null && inputSource.gripSpace ) {
  13198. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13199. if ( gripPose !== null ) {
  13200. grip.matrix.fromArray( gripPose.transform.matrix );
  13201. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13202. }
  13203. }
  13204. }
  13205. }
  13206. if ( targetRay !== null ) {
  13207. targetRay.visible = ( inputPose !== null );
  13208. }
  13209. if ( grip !== null ) {
  13210. grip.visible = ( gripPose !== null );
  13211. }
  13212. if ( hand !== null ) {
  13213. hand.visible = ( handPose !== null );
  13214. }
  13215. return this;
  13216. }
  13217. } );
  13218. function WebXRManager( renderer, gl ) {
  13219. const scope = this;
  13220. let session = null;
  13221. let framebufferScaleFactor = 1.0;
  13222. let referenceSpace = null;
  13223. let referenceSpaceType = 'local-floor';
  13224. let pose = null;
  13225. const controllers = [];
  13226. const inputSourcesMap = new Map();
  13227. //
  13228. const cameraL = new PerspectiveCamera();
  13229. cameraL.layers.enable( 1 );
  13230. cameraL.viewport = new Vector4();
  13231. const cameraR = new PerspectiveCamera();
  13232. cameraR.layers.enable( 2 );
  13233. cameraR.viewport = new Vector4();
  13234. const cameras = [ cameraL, cameraR ];
  13235. const cameraVR = new ArrayCamera();
  13236. cameraVR.layers.enable( 1 );
  13237. cameraVR.layers.enable( 2 );
  13238. let _currentDepthNear = null;
  13239. let _currentDepthFar = null;
  13240. //
  13241. this.enabled = false;
  13242. this.isPresenting = false;
  13243. this.getController = function ( index ) {
  13244. let controller = controllers[ index ];
  13245. if ( controller === undefined ) {
  13246. controller = new WebXRController();
  13247. controllers[ index ] = controller;
  13248. }
  13249. return controller.getTargetRaySpace();
  13250. };
  13251. this.getControllerGrip = function ( index ) {
  13252. let controller = controllers[ index ];
  13253. if ( controller === undefined ) {
  13254. controller = new WebXRController();
  13255. controllers[ index ] = controller;
  13256. }
  13257. return controller.getGripSpace();
  13258. };
  13259. this.getHand = function ( index ) {
  13260. let controller = controllers[ index ];
  13261. if ( controller === undefined ) {
  13262. controller = new WebXRController();
  13263. controllers[ index ] = controller;
  13264. }
  13265. return controller.getHandSpace();
  13266. };
  13267. //
  13268. function onSessionEvent( event ) {
  13269. const controller = inputSourcesMap.get( event.inputSource );
  13270. if ( controller ) {
  13271. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  13272. }
  13273. }
  13274. function onSessionEnd() {
  13275. inputSourcesMap.forEach( function ( controller, inputSource ) {
  13276. controller.disconnect( inputSource );
  13277. } );
  13278. inputSourcesMap.clear();
  13279. //
  13280. renderer.setFramebuffer( null );
  13281. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  13282. animation.stop();
  13283. scope.isPresenting = false;
  13284. scope.dispatchEvent( { type: 'sessionend' } );
  13285. }
  13286. function onRequestReferenceSpace( value ) {
  13287. referenceSpace = value;
  13288. animation.setContext( session );
  13289. animation.start();
  13290. scope.isPresenting = true;
  13291. scope.dispatchEvent( { type: 'sessionstart' } );
  13292. }
  13293. this.setFramebufferScaleFactor = function ( value ) {
  13294. framebufferScaleFactor = value;
  13295. if ( scope.isPresenting === true ) {
  13296. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  13297. }
  13298. };
  13299. this.setReferenceSpaceType = function ( value ) {
  13300. referenceSpaceType = value;
  13301. if ( scope.isPresenting === true ) {
  13302. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  13303. }
  13304. };
  13305. this.getReferenceSpace = function () {
  13306. return referenceSpace;
  13307. };
  13308. this.getSession = function () {
  13309. return session;
  13310. };
  13311. this.setSession = function ( value ) {
  13312. session = value;
  13313. if ( session !== null ) {
  13314. session.addEventListener( 'select', onSessionEvent );
  13315. session.addEventListener( 'selectstart', onSessionEvent );
  13316. session.addEventListener( 'selectend', onSessionEvent );
  13317. session.addEventListener( 'squeeze', onSessionEvent );
  13318. session.addEventListener( 'squeezestart', onSessionEvent );
  13319. session.addEventListener( 'squeezeend', onSessionEvent );
  13320. session.addEventListener( 'end', onSessionEnd );
  13321. const attributes = gl.getContextAttributes();
  13322. if ( attributes.xrCompatible !== true ) {
  13323. gl.makeXRCompatible();
  13324. }
  13325. const layerInit = {
  13326. antialias: attributes.antialias,
  13327. alpha: attributes.alpha,
  13328. depth: attributes.depth,
  13329. stencil: attributes.stencil,
  13330. framebufferScaleFactor: framebufferScaleFactor
  13331. };
  13332. // eslint-disable-next-line no-undef
  13333. const baseLayer = new XRWebGLLayer( session, gl, layerInit );
  13334. session.updateRenderState( { baseLayer: baseLayer } );
  13335. session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
  13336. //
  13337. session.addEventListener( 'inputsourceschange', updateInputSources );
  13338. }
  13339. };
  13340. function updateInputSources( event ) {
  13341. const inputSources = session.inputSources;
  13342. // Assign inputSources to available controllers
  13343. for ( let i = 0; i < controllers.length; i ++ ) {
  13344. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  13345. }
  13346. // Notify disconnected
  13347. for ( let i = 0; i < event.removed.length; i ++ ) {
  13348. const inputSource = event.removed[ i ];
  13349. const controller = inputSourcesMap.get( inputSource );
  13350. if ( controller ) {
  13351. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13352. inputSourcesMap.delete( inputSource );
  13353. }
  13354. }
  13355. // Notify connected
  13356. for ( let i = 0; i < event.added.length; i ++ ) {
  13357. const inputSource = event.added[ i ];
  13358. const controller = inputSourcesMap.get( inputSource );
  13359. if ( controller ) {
  13360. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  13361. }
  13362. }
  13363. }
  13364. //
  13365. const cameraLPos = new Vector3();
  13366. const cameraRPos = new Vector3();
  13367. /**
  13368. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13369. * the cameras' projection and world matrices have already been set.
  13370. * And that near and far planes are identical for both cameras.
  13371. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13372. */
  13373. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  13374. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  13375. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  13376. const ipd = cameraLPos.distanceTo( cameraRPos );
  13377. const projL = cameraL.projectionMatrix.elements;
  13378. const projR = cameraR.projectionMatrix.elements;
  13379. // VR systems will have identical far and near planes, and
  13380. // most likely identical top and bottom frustum extents.
  13381. // Use the left camera for these values.
  13382. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  13383. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  13384. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  13385. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  13386. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  13387. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  13388. const left = near * leftFov;
  13389. const right = near * rightFov;
  13390. // Calculate the new camera's position offset from the
  13391. // left camera. xOffset should be roughly half `ipd`.
  13392. const zOffset = ipd / ( - leftFov + rightFov );
  13393. const xOffset = zOffset * - leftFov;
  13394. // TODO: Better way to apply this offset?
  13395. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  13396. camera.translateX( xOffset );
  13397. camera.translateZ( zOffset );
  13398. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  13399. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  13400. // Find the union of the frustum values of the cameras and scale
  13401. // the values so that the near plane's position does not change in world space,
  13402. // although must now be relative to the new union camera.
  13403. const near2 = near + zOffset;
  13404. const far2 = far + zOffset;
  13405. const left2 = left - xOffset;
  13406. const right2 = right + ( ipd - xOffset );
  13407. const top2 = topFov * far / far2 * near2;
  13408. const bottom2 = bottomFov * far / far2 * near2;
  13409. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  13410. }
  13411. function updateCamera( camera, parent ) {
  13412. if ( parent === null ) {
  13413. camera.matrixWorld.copy( camera.matrix );
  13414. } else {
  13415. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  13416. }
  13417. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  13418. }
  13419. this.getCamera = function ( camera ) {
  13420. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13421. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13422. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  13423. // Note that the new renderState won't apply until the next frame. See #18320
  13424. session.updateRenderState( {
  13425. depthNear: cameraVR.near,
  13426. depthFar: cameraVR.far
  13427. } );
  13428. _currentDepthNear = cameraVR.near;
  13429. _currentDepthFar = cameraVR.far;
  13430. }
  13431. const parent = camera.parent;
  13432. const cameras = cameraVR.cameras;
  13433. updateCamera( cameraVR, parent );
  13434. for ( let i = 0; i < cameras.length; i ++ ) {
  13435. updateCamera( cameras[ i ], parent );
  13436. }
  13437. // update camera and its children
  13438. camera.matrixWorld.copy( cameraVR.matrixWorld );
  13439. const children = camera.children;
  13440. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13441. children[ i ].updateMatrixWorld( true );
  13442. }
  13443. // update projection matrix for proper view frustum culling
  13444. if ( cameras.length === 2 ) {
  13445. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  13446. } else {
  13447. // assume single camera setup (AR)
  13448. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  13449. }
  13450. return cameraVR;
  13451. };
  13452. // Animation Loop
  13453. let onAnimationFrameCallback = null;
  13454. function onAnimationFrame( time, frame ) {
  13455. pose = frame.getViewerPose( referenceSpace );
  13456. if ( pose !== null ) {
  13457. const views = pose.views;
  13458. const baseLayer = session.renderState.baseLayer;
  13459. renderer.setFramebuffer( baseLayer.framebuffer );
  13460. let cameraVRNeedsUpdate = false;
  13461. // check if it's necessary to rebuild cameraVR's camera list
  13462. if ( views.length !== cameraVR.cameras.length ) {
  13463. cameraVR.cameras.length = 0;
  13464. cameraVRNeedsUpdate = true;
  13465. }
  13466. for ( let i = 0; i < views.length; i ++ ) {
  13467. const view = views[ i ];
  13468. const viewport = baseLayer.getViewport( view );
  13469. const camera = cameras[ i ];
  13470. camera.matrix.fromArray( view.transform.matrix );
  13471. camera.projectionMatrix.fromArray( view.projectionMatrix );
  13472. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  13473. if ( i === 0 ) {
  13474. cameraVR.matrix.copy( camera.matrix );
  13475. }
  13476. if ( cameraVRNeedsUpdate === true ) {
  13477. cameraVR.cameras.push( camera );
  13478. }
  13479. }
  13480. }
  13481. //
  13482. const inputSources = session.inputSources;
  13483. for ( let i = 0; i < controllers.length; i ++ ) {
  13484. const controller = controllers[ i ];
  13485. const inputSource = inputSources[ i ];
  13486. controller.update( inputSource, frame, referenceSpace );
  13487. }
  13488. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  13489. }
  13490. const animation = new WebGLAnimation();
  13491. animation.setAnimationLoop( onAnimationFrame );
  13492. this.setAnimationLoop = function ( callback ) {
  13493. onAnimationFrameCallback = callback;
  13494. };
  13495. this.dispose = function () {};
  13496. }
  13497. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  13498. function WebGLMaterials( properties ) {
  13499. function refreshFogUniforms( uniforms, fog ) {
  13500. uniforms.fogColor.value.copy( fog.color );
  13501. if ( fog.isFog ) {
  13502. uniforms.fogNear.value = fog.near;
  13503. uniforms.fogFar.value = fog.far;
  13504. } else if ( fog.isFogExp2 ) {
  13505. uniforms.fogDensity.value = fog.density;
  13506. }
  13507. }
  13508. function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) {
  13509. if ( material.isMeshBasicMaterial ) {
  13510. refreshUniformsCommon( uniforms, material );
  13511. } else if ( material.isMeshLambertMaterial ) {
  13512. refreshUniformsCommon( uniforms, material );
  13513. refreshUniformsLambert( uniforms, material );
  13514. } else if ( material.isMeshToonMaterial ) {
  13515. refreshUniformsCommon( uniforms, material );
  13516. refreshUniformsToon( uniforms, material );
  13517. } else if ( material.isMeshPhongMaterial ) {
  13518. refreshUniformsCommon( uniforms, material );
  13519. refreshUniformsPhong( uniforms, material );
  13520. } else if ( material.isMeshStandardMaterial ) {
  13521. refreshUniformsCommon( uniforms, material );
  13522. if ( material.isMeshPhysicalMaterial ) {
  13523. refreshUniformsPhysical( uniforms, material );
  13524. } else {
  13525. refreshUniformsStandard( uniforms, material );
  13526. }
  13527. } else if ( material.isMeshMatcapMaterial ) {
  13528. refreshUniformsCommon( uniforms, material );
  13529. refreshUniformsMatcap( uniforms, material );
  13530. } else if ( material.isMeshDepthMaterial ) {
  13531. refreshUniformsCommon( uniforms, material );
  13532. refreshUniformsDepth( uniforms, material );
  13533. } else if ( material.isMeshDistanceMaterial ) {
  13534. refreshUniformsCommon( uniforms, material );
  13535. refreshUniformsDistance( uniforms, material );
  13536. } else if ( material.isMeshNormalMaterial ) {
  13537. refreshUniformsCommon( uniforms, material );
  13538. refreshUniformsNormal( uniforms, material );
  13539. } else if ( material.isLineBasicMaterial ) {
  13540. refreshUniformsLine( uniforms, material );
  13541. if ( material.isLineDashedMaterial ) {
  13542. refreshUniformsDash( uniforms, material );
  13543. }
  13544. } else if ( material.isPointsMaterial ) {
  13545. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  13546. } else if ( material.isSpriteMaterial ) {
  13547. refreshUniformsSprites( uniforms, material );
  13548. } else if ( material.isShadowMaterial ) {
  13549. uniforms.color.value.copy( material.color );
  13550. uniforms.opacity.value = material.opacity;
  13551. } else if ( material.isShaderMaterial ) {
  13552. material.uniformsNeedUpdate = false; // #15581
  13553. }
  13554. }
  13555. function refreshUniformsCommon( uniforms, material ) {
  13556. uniforms.opacity.value = material.opacity;
  13557. if ( material.color ) {
  13558. uniforms.diffuse.value.copy( material.color );
  13559. }
  13560. if ( material.emissive ) {
  13561. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  13562. }
  13563. if ( material.map ) {
  13564. uniforms.map.value = material.map;
  13565. }
  13566. if ( material.alphaMap ) {
  13567. uniforms.alphaMap.value = material.alphaMap;
  13568. }
  13569. if ( material.specularMap ) {
  13570. uniforms.specularMap.value = material.specularMap;
  13571. }
  13572. const envMap = properties.get( material ).envMap;
  13573. if ( envMap ) {
  13574. uniforms.envMap.value = envMap;
  13575. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1;
  13576. uniforms.reflectivity.value = material.reflectivity;
  13577. uniforms.refractionRatio.value = material.refractionRatio;
  13578. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  13579. if ( maxMipLevel !== undefined ) {
  13580. uniforms.maxMipLevel.value = maxMipLevel;
  13581. }
  13582. }
  13583. if ( material.lightMap ) {
  13584. uniforms.lightMap.value = material.lightMap;
  13585. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13586. }
  13587. if ( material.aoMap ) {
  13588. uniforms.aoMap.value = material.aoMap;
  13589. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13590. }
  13591. // uv repeat and offset setting priorities
  13592. // 1. color map
  13593. // 2. specular map
  13594. // 3. displacementMap map
  13595. // 4. normal map
  13596. // 5. bump map
  13597. // 6. roughnessMap map
  13598. // 7. metalnessMap map
  13599. // 8. alphaMap map
  13600. // 9. emissiveMap map
  13601. // 10. clearcoat map
  13602. // 11. clearcoat normal map
  13603. // 12. clearcoat roughnessMap map
  13604. let uvScaleMap;
  13605. if ( material.map ) {
  13606. uvScaleMap = material.map;
  13607. } else if ( material.specularMap ) {
  13608. uvScaleMap = material.specularMap;
  13609. } else if ( material.displacementMap ) {
  13610. uvScaleMap = material.displacementMap;
  13611. } else if ( material.normalMap ) {
  13612. uvScaleMap = material.normalMap;
  13613. } else if ( material.bumpMap ) {
  13614. uvScaleMap = material.bumpMap;
  13615. } else if ( material.roughnessMap ) {
  13616. uvScaleMap = material.roughnessMap;
  13617. } else if ( material.metalnessMap ) {
  13618. uvScaleMap = material.metalnessMap;
  13619. } else if ( material.alphaMap ) {
  13620. uvScaleMap = material.alphaMap;
  13621. } else if ( material.emissiveMap ) {
  13622. uvScaleMap = material.emissiveMap;
  13623. } else if ( material.clearcoatMap ) {
  13624. uvScaleMap = material.clearcoatMap;
  13625. } else if ( material.clearcoatNormalMap ) {
  13626. uvScaleMap = material.clearcoatNormalMap;
  13627. } else if ( material.clearcoatRoughnessMap ) {
  13628. uvScaleMap = material.clearcoatRoughnessMap;
  13629. }
  13630. if ( uvScaleMap !== undefined ) {
  13631. // backwards compatibility
  13632. if ( uvScaleMap.isWebGLRenderTarget ) {
  13633. uvScaleMap = uvScaleMap.texture;
  13634. }
  13635. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13636. uvScaleMap.updateMatrix();
  13637. }
  13638. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13639. }
  13640. // uv repeat and offset setting priorities for uv2
  13641. // 1. ao map
  13642. // 2. light map
  13643. let uv2ScaleMap;
  13644. if ( material.aoMap ) {
  13645. uv2ScaleMap = material.aoMap;
  13646. } else if ( material.lightMap ) {
  13647. uv2ScaleMap = material.lightMap;
  13648. }
  13649. if ( uv2ScaleMap !== undefined ) {
  13650. // backwards compatibility
  13651. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  13652. uv2ScaleMap = uv2ScaleMap.texture;
  13653. }
  13654. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  13655. uv2ScaleMap.updateMatrix();
  13656. }
  13657. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  13658. }
  13659. }
  13660. function refreshUniformsLine( uniforms, material ) {
  13661. uniforms.diffuse.value.copy( material.color );
  13662. uniforms.opacity.value = material.opacity;
  13663. }
  13664. function refreshUniformsDash( uniforms, material ) {
  13665. uniforms.dashSize.value = material.dashSize;
  13666. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13667. uniforms.scale.value = material.scale;
  13668. }
  13669. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  13670. uniforms.diffuse.value.copy( material.color );
  13671. uniforms.opacity.value = material.opacity;
  13672. uniforms.size.value = material.size * pixelRatio;
  13673. uniforms.scale.value = height * 0.5;
  13674. if ( material.map ) {
  13675. uniforms.map.value = material.map;
  13676. }
  13677. if ( material.alphaMap ) {
  13678. uniforms.alphaMap.value = material.alphaMap;
  13679. }
  13680. // uv repeat and offset setting priorities
  13681. // 1. color map
  13682. // 2. alpha map
  13683. let uvScaleMap;
  13684. if ( material.map ) {
  13685. uvScaleMap = material.map;
  13686. } else if ( material.alphaMap ) {
  13687. uvScaleMap = material.alphaMap;
  13688. }
  13689. if ( uvScaleMap !== undefined ) {
  13690. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13691. uvScaleMap.updateMatrix();
  13692. }
  13693. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13694. }
  13695. }
  13696. function refreshUniformsSprites( uniforms, material ) {
  13697. uniforms.diffuse.value.copy( material.color );
  13698. uniforms.opacity.value = material.opacity;
  13699. uniforms.rotation.value = material.rotation;
  13700. if ( material.map ) {
  13701. uniforms.map.value = material.map;
  13702. }
  13703. if ( material.alphaMap ) {
  13704. uniforms.alphaMap.value = material.alphaMap;
  13705. }
  13706. // uv repeat and offset setting priorities
  13707. // 1. color map
  13708. // 2. alpha map
  13709. let uvScaleMap;
  13710. if ( material.map ) {
  13711. uvScaleMap = material.map;
  13712. } else if ( material.alphaMap ) {
  13713. uvScaleMap = material.alphaMap;
  13714. }
  13715. if ( uvScaleMap !== undefined ) {
  13716. if ( uvScaleMap.matrixAutoUpdate === true ) {
  13717. uvScaleMap.updateMatrix();
  13718. }
  13719. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  13720. }
  13721. }
  13722. function refreshUniformsLambert( uniforms, material ) {
  13723. if ( material.emissiveMap ) {
  13724. uniforms.emissiveMap.value = material.emissiveMap;
  13725. }
  13726. }
  13727. function refreshUniformsPhong( uniforms, material ) {
  13728. uniforms.specular.value.copy( material.specular );
  13729. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13730. if ( material.emissiveMap ) {
  13731. uniforms.emissiveMap.value = material.emissiveMap;
  13732. }
  13733. if ( material.bumpMap ) {
  13734. uniforms.bumpMap.value = material.bumpMap;
  13735. uniforms.bumpScale.value = material.bumpScale;
  13736. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13737. }
  13738. if ( material.normalMap ) {
  13739. uniforms.normalMap.value = material.normalMap;
  13740. uniforms.normalScale.value.copy( material.normalScale );
  13741. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13742. }
  13743. if ( material.displacementMap ) {
  13744. uniforms.displacementMap.value = material.displacementMap;
  13745. uniforms.displacementScale.value = material.displacementScale;
  13746. uniforms.displacementBias.value = material.displacementBias;
  13747. }
  13748. }
  13749. function refreshUniformsToon( uniforms, material ) {
  13750. if ( material.gradientMap ) {
  13751. uniforms.gradientMap.value = material.gradientMap;
  13752. }
  13753. if ( material.emissiveMap ) {
  13754. uniforms.emissiveMap.value = material.emissiveMap;
  13755. }
  13756. if ( material.bumpMap ) {
  13757. uniforms.bumpMap.value = material.bumpMap;
  13758. uniforms.bumpScale.value = material.bumpScale;
  13759. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13760. }
  13761. if ( material.normalMap ) {
  13762. uniforms.normalMap.value = material.normalMap;
  13763. uniforms.normalScale.value.copy( material.normalScale );
  13764. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13765. }
  13766. if ( material.displacementMap ) {
  13767. uniforms.displacementMap.value = material.displacementMap;
  13768. uniforms.displacementScale.value = material.displacementScale;
  13769. uniforms.displacementBias.value = material.displacementBias;
  13770. }
  13771. }
  13772. function refreshUniformsStandard( uniforms, material ) {
  13773. uniforms.roughness.value = material.roughness;
  13774. uniforms.metalness.value = material.metalness;
  13775. if ( material.roughnessMap ) {
  13776. uniforms.roughnessMap.value = material.roughnessMap;
  13777. }
  13778. if ( material.metalnessMap ) {
  13779. uniforms.metalnessMap.value = material.metalnessMap;
  13780. }
  13781. if ( material.emissiveMap ) {
  13782. uniforms.emissiveMap.value = material.emissiveMap;
  13783. }
  13784. if ( material.bumpMap ) {
  13785. uniforms.bumpMap.value = material.bumpMap;
  13786. uniforms.bumpScale.value = material.bumpScale;
  13787. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13788. }
  13789. if ( material.normalMap ) {
  13790. uniforms.normalMap.value = material.normalMap;
  13791. uniforms.normalScale.value.copy( material.normalScale );
  13792. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13793. }
  13794. if ( material.displacementMap ) {
  13795. uniforms.displacementMap.value = material.displacementMap;
  13796. uniforms.displacementScale.value = material.displacementScale;
  13797. uniforms.displacementBias.value = material.displacementBias;
  13798. }
  13799. const envMap = properties.get( material ).envMap;
  13800. if ( envMap ) {
  13801. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13802. uniforms.envMapIntensity.value = material.envMapIntensity;
  13803. }
  13804. }
  13805. function refreshUniformsPhysical( uniforms, material ) {
  13806. refreshUniformsStandard( uniforms, material );
  13807. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  13808. uniforms.clearcoat.value = material.clearcoat;
  13809. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  13810. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  13811. if ( material.clearcoatMap ) {
  13812. uniforms.clearcoatMap.value = material.clearcoatMap;
  13813. }
  13814. if ( material.clearcoatRoughnessMap ) {
  13815. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  13816. }
  13817. if ( material.clearcoatNormalMap ) {
  13818. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  13819. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  13820. if ( material.side === BackSide ) {
  13821. uniforms.clearcoatNormalScale.value.negate();
  13822. }
  13823. }
  13824. uniforms.transmission.value = material.transmission;
  13825. if ( material.transmissionMap ) {
  13826. uniforms.transmissionMap.value = material.transmissionMap;
  13827. }
  13828. }
  13829. function refreshUniformsMatcap( uniforms, material ) {
  13830. if ( material.matcap ) {
  13831. uniforms.matcap.value = material.matcap;
  13832. }
  13833. if ( material.bumpMap ) {
  13834. uniforms.bumpMap.value = material.bumpMap;
  13835. uniforms.bumpScale.value = material.bumpScale;
  13836. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13837. }
  13838. if ( material.normalMap ) {
  13839. uniforms.normalMap.value = material.normalMap;
  13840. uniforms.normalScale.value.copy( material.normalScale );
  13841. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13842. }
  13843. if ( material.displacementMap ) {
  13844. uniforms.displacementMap.value = material.displacementMap;
  13845. uniforms.displacementScale.value = material.displacementScale;
  13846. uniforms.displacementBias.value = material.displacementBias;
  13847. }
  13848. }
  13849. function refreshUniformsDepth( uniforms, material ) {
  13850. if ( material.displacementMap ) {
  13851. uniforms.displacementMap.value = material.displacementMap;
  13852. uniforms.displacementScale.value = material.displacementScale;
  13853. uniforms.displacementBias.value = material.displacementBias;
  13854. }
  13855. }
  13856. function refreshUniformsDistance( uniforms, material ) {
  13857. if ( material.displacementMap ) {
  13858. uniforms.displacementMap.value = material.displacementMap;
  13859. uniforms.displacementScale.value = material.displacementScale;
  13860. uniforms.displacementBias.value = material.displacementBias;
  13861. }
  13862. uniforms.referencePosition.value.copy( material.referencePosition );
  13863. uniforms.nearDistance.value = material.nearDistance;
  13864. uniforms.farDistance.value = material.farDistance;
  13865. }
  13866. function refreshUniformsNormal( uniforms, material ) {
  13867. if ( material.bumpMap ) {
  13868. uniforms.bumpMap.value = material.bumpMap;
  13869. uniforms.bumpScale.value = material.bumpScale;
  13870. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  13871. }
  13872. if ( material.normalMap ) {
  13873. uniforms.normalMap.value = material.normalMap;
  13874. uniforms.normalScale.value.copy( material.normalScale );
  13875. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  13876. }
  13877. if ( material.displacementMap ) {
  13878. uniforms.displacementMap.value = material.displacementMap;
  13879. uniforms.displacementScale.value = material.displacementScale;
  13880. uniforms.displacementBias.value = material.displacementBias;
  13881. }
  13882. }
  13883. return {
  13884. refreshFogUniforms: refreshFogUniforms,
  13885. refreshMaterialUniforms: refreshMaterialUniforms
  13886. };
  13887. }
  13888. function createCanvasElement() {
  13889. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  13890. canvas.style.display = 'block';
  13891. return canvas;
  13892. }
  13893. function WebGLRenderer( parameters ) {
  13894. parameters = parameters || {};
  13895. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  13896. _context = parameters.context !== undefined ? parameters.context : null,
  13897. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  13898. _depth = parameters.depth !== undefined ? parameters.depth : true,
  13899. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  13900. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  13901. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  13902. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  13903. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  13904. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  13905. let currentRenderList = null;
  13906. let currentRenderState = null;
  13907. // render() can be called from within a callback triggered by another render.
  13908. // We track this so that the nested render call gets its state isolated from the parent render call.
  13909. const renderStateStack = [];
  13910. // public properties
  13911. this.domElement = _canvas;
  13912. // Debug configuration container
  13913. this.debug = {
  13914. /**
  13915. * Enables error checking and reporting when shader programs are being compiled
  13916. * @type {boolean}
  13917. */
  13918. checkShaderErrors: true
  13919. };
  13920. // clearing
  13921. this.autoClear = true;
  13922. this.autoClearColor = true;
  13923. this.autoClearDepth = true;
  13924. this.autoClearStencil = true;
  13925. // scene graph
  13926. this.sortObjects = true;
  13927. // user-defined clipping
  13928. this.clippingPlanes = [];
  13929. this.localClippingEnabled = false;
  13930. // physically based shading
  13931. this.gammaFactor = 2.0; // for backwards compatibility
  13932. this.outputEncoding = LinearEncoding;
  13933. // physical lights
  13934. this.physicallyCorrectLights = false;
  13935. // tone mapping
  13936. this.toneMapping = NoToneMapping;
  13937. this.toneMappingExposure = 1.0;
  13938. // morphs
  13939. this.maxMorphTargets = 8;
  13940. this.maxMorphNormals = 4;
  13941. // internal properties
  13942. const _this = this;
  13943. let _isContextLost = false;
  13944. // internal state cache
  13945. let _framebuffer = null;
  13946. let _currentActiveCubeFace = 0;
  13947. let _currentActiveMipmapLevel = 0;
  13948. let _currentRenderTarget = null;
  13949. let _currentFramebuffer = null;
  13950. let _currentMaterialId = - 1;
  13951. let _currentCamera = null;
  13952. const _currentViewport = new Vector4();
  13953. const _currentScissor = new Vector4();
  13954. let _currentScissorTest = null;
  13955. //
  13956. let _width = _canvas.width;
  13957. let _height = _canvas.height;
  13958. let _pixelRatio = 1;
  13959. let _opaqueSort = null;
  13960. let _transparentSort = null;
  13961. const _viewport = new Vector4( 0, 0, _width, _height );
  13962. const _scissor = new Vector4( 0, 0, _width, _height );
  13963. let _scissorTest = false;
  13964. // frustum
  13965. const _frustum = new Frustum();
  13966. // clipping
  13967. let _clippingEnabled = false;
  13968. let _localClippingEnabled = false;
  13969. // camera matrices cache
  13970. const _projScreenMatrix = new Matrix4();
  13971. const _vector3 = new Vector3();
  13972. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  13973. function getTargetPixelRatio() {
  13974. return _currentRenderTarget === null ? _pixelRatio : 1;
  13975. }
  13976. // initialize
  13977. let _gl = _context;
  13978. function getContext( contextNames, contextAttributes ) {
  13979. for ( let i = 0; i < contextNames.length; i ++ ) {
  13980. const contextName = contextNames[ i ];
  13981. const context = _canvas.getContext( contextName, contextAttributes );
  13982. if ( context !== null ) return context;
  13983. }
  13984. return null;
  13985. }
  13986. try {
  13987. const contextAttributes = {
  13988. alpha: _alpha,
  13989. depth: _depth,
  13990. stencil: _stencil,
  13991. antialias: _antialias,
  13992. premultipliedAlpha: _premultipliedAlpha,
  13993. preserveDrawingBuffer: _preserveDrawingBuffer,
  13994. powerPreference: _powerPreference,
  13995. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  13996. };
  13997. // event listeners must be registered before WebGL context is created, see #12753
  13998. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  13999. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  14000. if ( _gl === null ) {
  14001. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  14002. if ( _this.isWebGL1Renderer === true ) {
  14003. contextNames.shift();
  14004. }
  14005. _gl = getContext( contextNames, contextAttributes );
  14006. if ( _gl === null ) {
  14007. if ( getContext( contextNames ) ) {
  14008. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  14009. } else {
  14010. throw new Error( 'Error creating WebGL context.' );
  14011. }
  14012. }
  14013. }
  14014. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14015. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14016. _gl.getShaderPrecisionFormat = function () {
  14017. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14018. };
  14019. }
  14020. } catch ( error ) {
  14021. console.error( 'THREE.WebGLRenderer: ' + error.message );
  14022. throw error;
  14023. }
  14024. let extensions, capabilities, state, info;
  14025. let properties, textures, cubemaps, attributes, geometries, objects;
  14026. let programCache, materials, renderLists, renderStates, clipping;
  14027. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14028. let utils, bindingStates;
  14029. function initGLContext() {
  14030. extensions = new WebGLExtensions( _gl );
  14031. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  14032. if ( capabilities.isWebGL2 === false ) {
  14033. extensions.get( 'WEBGL_depth_texture' );
  14034. extensions.get( 'OES_texture_float' );
  14035. extensions.get( 'OES_texture_half_float' );
  14036. extensions.get( 'OES_texture_half_float_linear' );
  14037. extensions.get( 'OES_standard_derivatives' );
  14038. extensions.get( 'OES_element_index_uint' );
  14039. extensions.get( 'OES_vertex_array_object' );
  14040. extensions.get( 'ANGLE_instanced_arrays' );
  14041. }
  14042. extensions.get( 'OES_texture_float_linear' );
  14043. utils = new WebGLUtils( _gl, extensions, capabilities );
  14044. state = new WebGLState( _gl, extensions, capabilities );
  14045. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14046. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14047. info = new WebGLInfo( _gl );
  14048. properties = new WebGLProperties();
  14049. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  14050. cubemaps = new WebGLCubeMaps( _this );
  14051. attributes = new WebGLAttributes( _gl, capabilities );
  14052. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  14053. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  14054. objects = new WebGLObjects( _gl, geometries, attributes, info );
  14055. morphtargets = new WebGLMorphtargets( _gl );
  14056. clipping = new WebGLClipping( properties );
  14057. programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping );
  14058. materials = new WebGLMaterials( properties );
  14059. renderLists = new WebGLRenderLists( properties );
  14060. renderStates = new WebGLRenderStates( extensions, capabilities );
  14061. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  14062. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  14063. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  14064. info.programs = programCache.programs;
  14065. _this.capabilities = capabilities;
  14066. _this.extensions = extensions;
  14067. _this.properties = properties;
  14068. _this.renderLists = renderLists;
  14069. _this.state = state;
  14070. _this.info = info;
  14071. _this._textures = textures;//add
  14072. }
  14073. initGLContext();
  14074. // xr
  14075. const xr = new WebXRManager( _this, _gl );
  14076. this.xr = xr;
  14077. // shadow map
  14078. const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  14079. this.shadowMap = shadowMap;
  14080. // API
  14081. this.getContext = function () {
  14082. return _gl;
  14083. };
  14084. this.getContextAttributes = function () {
  14085. return _gl.getContextAttributes();
  14086. };
  14087. this.forceContextLoss = function () {
  14088. const extension = extensions.get( 'WEBGL_lose_context' );
  14089. if ( extension ) extension.loseContext();
  14090. };
  14091. this.forceContextRestore = function () {
  14092. const extension = extensions.get( 'WEBGL_lose_context' );
  14093. if ( extension ) extension.restoreContext();
  14094. };
  14095. this.getPixelRatio = function () {
  14096. return _pixelRatio;
  14097. };
  14098. this.setPixelRatio = function ( value ) {
  14099. if ( value === undefined ) return;
  14100. _pixelRatio = value;
  14101. this.setSize( _width, _height, false );
  14102. };
  14103. this.getSize = function ( target ) {
  14104. if ( target === undefined ) {
  14105. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  14106. target = new Vector2();
  14107. }
  14108. return target.set( _width, _height );
  14109. };
  14110. this.setSize = function ( width, height, updateStyle ) {
  14111. if ( xr.isPresenting ) {
  14112. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  14113. return;
  14114. }
  14115. _width = width;
  14116. _height = height;
  14117. _canvas.width = Math.floor( width * _pixelRatio );
  14118. _canvas.height = Math.floor( height * _pixelRatio );
  14119. if ( updateStyle !== false ) {
  14120. _canvas.style.width = width + 'px';
  14121. _canvas.style.height = height + 'px';
  14122. }
  14123. this.setViewport( 0, 0, width, height );
  14124. };
  14125. this.getDrawingBufferSize = function ( target ) {
  14126. if ( target === undefined ) {
  14127. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  14128. target = new Vector2();
  14129. }
  14130. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  14131. };
  14132. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  14133. _width = width;
  14134. _height = height;
  14135. _pixelRatio = pixelRatio;
  14136. _canvas.width = Math.floor( width * pixelRatio );
  14137. _canvas.height = Math.floor( height * pixelRatio );
  14138. this.setViewport( 0, 0, width, height );
  14139. };
  14140. this.getCurrentViewport = function ( target ) {
  14141. if ( target === undefined ) {
  14142. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  14143. target = new Vector4();
  14144. }
  14145. return target.copy( _currentViewport );
  14146. };
  14147. this.getViewport = function ( target ) {
  14148. return target.copy( _viewport );
  14149. };
  14150. this.setViewport = function ( x, y, width, height ) {
  14151. if ( x.isVector4 ) {
  14152. _viewport.set( x.x, x.y, x.z, x.w );
  14153. } else {
  14154. _viewport.set( x, y, width, height );
  14155. }
  14156. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14157. };
  14158. this.getScissor = function ( target ) {
  14159. return target.copy( _scissor );
  14160. };
  14161. this.setScissor = function ( x, y, width, height ) {
  14162. if ( x.isVector4 ) {
  14163. _scissor.set( x.x, x.y, x.z, x.w );
  14164. } else {
  14165. _scissor.set( x, y, width, height );
  14166. }
  14167. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14168. };
  14169. this.getScissorTest = function () {
  14170. return _scissorTest;
  14171. };
  14172. this.setScissorTest = function ( boolean ) {
  14173. state.setScissorTest( _scissorTest = boolean );
  14174. };
  14175. this.setOpaqueSort = function ( method ) {
  14176. _opaqueSort = method;
  14177. };
  14178. this.setTransparentSort = function ( method ) {
  14179. _transparentSort = method;
  14180. };
  14181. // Clearing
  14182. this.getClearColor = function ( target ) {
  14183. if ( target === undefined ) {
  14184. console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' );
  14185. target = new Color();
  14186. }
  14187. return target.copy( background.getClearColor() );
  14188. };
  14189. this.setClearColor = function () {
  14190. background.setClearColor.apply( background, arguments );
  14191. };
  14192. this.getClearAlpha = function () {
  14193. return background.getClearAlpha();
  14194. };
  14195. this.setClearAlpha = function () {
  14196. background.setClearAlpha.apply( background, arguments );
  14197. };
  14198. this.clear = function ( color, depth, stencil ) {
  14199. let bits = 0;
  14200. if ( color === undefined || color ) bits |= 16384;
  14201. if ( depth === undefined || depth ) bits |= 256;
  14202. if ( stencil === undefined || stencil ) bits |= 1024;
  14203. _gl.clear( bits );
  14204. };
  14205. this.clearColor = function () {
  14206. this.clear( true, false, false );
  14207. };
  14208. this.clearDepth = function () {
  14209. this.clear( false, true, false );
  14210. };
  14211. this.clearStencil = function () {
  14212. this.clear( false, false, true );
  14213. };
  14214. //
  14215. this.dispose = function () {
  14216. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14217. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  14218. renderLists.dispose();
  14219. renderStates.dispose();
  14220. properties.dispose();
  14221. cubemaps.dispose();
  14222. objects.dispose();
  14223. bindingStates.dispose();
  14224. xr.dispose();
  14225. animation.stop();
  14226. };
  14227. // Events
  14228. function onContextLost( event ) {
  14229. event.preventDefault();
  14230. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  14231. _isContextLost = true;
  14232. }
  14233. function onContextRestore( /* event */ ) {
  14234. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  14235. _isContextLost = false;
  14236. initGLContext();
  14237. }
  14238. function onMaterialDispose( event ) {
  14239. const material = event.target;
  14240. material.removeEventListener( 'dispose', onMaterialDispose );
  14241. deallocateMaterial( material );
  14242. }
  14243. // Buffer deallocation
  14244. function deallocateMaterial( material ) {
  14245. releaseMaterialProgramReference( material );
  14246. properties.remove( material );
  14247. }
  14248. function releaseMaterialProgramReference( material ) {
  14249. const programInfo = properties.get( material ).program;
  14250. if ( programInfo !== undefined ) {
  14251. programCache.releaseProgram( programInfo );
  14252. }
  14253. }
  14254. // Buffer rendering
  14255. function renderObjectImmediate( object, program ) {
  14256. object.render( function ( object ) {
  14257. _this.renderBufferImmediate( object, program );
  14258. } );
  14259. }
  14260. this.renderBufferImmediate = function ( object, program ) {
  14261. bindingStates.initAttributes();
  14262. const buffers = properties.get( object );
  14263. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  14264. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  14265. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  14266. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  14267. const programAttributes = program.getAttributes();
  14268. if ( object.hasPositions ) {
  14269. _gl.bindBuffer( 34962, buffers.position );
  14270. _gl.bufferData( 34962, object.positionArray, 35048 );
  14271. bindingStates.enableAttribute( programAttributes.position );
  14272. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  14273. }
  14274. if ( object.hasNormals ) {
  14275. _gl.bindBuffer( 34962, buffers.normal );
  14276. _gl.bufferData( 34962, object.normalArray, 35048 );
  14277. bindingStates.enableAttribute( programAttributes.normal );
  14278. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  14279. }
  14280. if ( object.hasUvs ) {
  14281. _gl.bindBuffer( 34962, buffers.uv );
  14282. _gl.bufferData( 34962, object.uvArray, 35048 );
  14283. bindingStates.enableAttribute( programAttributes.uv );
  14284. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  14285. }
  14286. if ( object.hasColors ) {
  14287. _gl.bindBuffer( 34962, buffers.color );
  14288. _gl.bufferData( 34962, object.colorArray, 35048 );
  14289. bindingStates.enableAttribute( programAttributes.color );
  14290. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  14291. }
  14292. bindingStates.disableUnusedAttributes();
  14293. _gl.drawArrays( 4, 0, object.count );
  14294. object.count = 0;
  14295. };
  14296. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  14297. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14298. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  14299. const program = setProgram( camera, scene, material, object );
  14300. state.setMaterial( material, frontFaceCW );
  14301. //
  14302. let index = geometry.index;
  14303. const position = geometry.attributes.position;
  14304. //
  14305. if ( index === null ) {
  14306. if ( position === undefined || position.count === 0 ) return;
  14307. } else if ( index.count === 0 ) {
  14308. return;
  14309. }
  14310. //
  14311. let rangeFactor = 1;
  14312. if ( material.wireframe === true ) {
  14313. index = geometries.getWireframeAttribute( geometry );
  14314. rangeFactor = 2;
  14315. }
  14316. if ( material.morphTargets || material.morphNormals ) {
  14317. morphtargets.update( object, geometry, material, program );
  14318. }
  14319. bindingStates.setup( object, material, program, geometry, index );
  14320. let attribute;
  14321. let renderer = bufferRenderer;
  14322. if ( index !== null ) {
  14323. attribute = attributes.get( index );
  14324. renderer = indexedBufferRenderer;
  14325. renderer.setIndex( attribute );
  14326. }
  14327. //
  14328. const dataCount = ( index !== null ) ? index.count : position.count;
  14329. const rangeStart = geometry.drawRange.start * rangeFactor;
  14330. const rangeCount = geometry.drawRange.count * rangeFactor;
  14331. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14332. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14333. const drawStart = Math.max( rangeStart, groupStart );
  14334. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  14335. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  14336. if ( drawCount === 0 ) return;
  14337. //
  14338. if ( object.isMesh ) {
  14339. if ( material.wireframe === true ) {
  14340. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  14341. renderer.setMode( 1 );
  14342. } else {
  14343. renderer.setMode( 4 );
  14344. }
  14345. } else if ( object.isLine ) {
  14346. let lineWidth = material.linewidth;
  14347. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  14348. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  14349. if ( object.isLineSegments ) {
  14350. renderer.setMode( 1 );
  14351. } else if ( object.isLineLoop ) {
  14352. renderer.setMode( 2 );
  14353. } else {
  14354. renderer.setMode( 3 );
  14355. }
  14356. } else if ( object.isPoints ) {
  14357. renderer.setMode( 0 );
  14358. } else if ( object.isSprite ) {
  14359. renderer.setMode( 4 );
  14360. }
  14361. if ( object.isInstancedMesh ) {
  14362. renderer.renderInstances( drawStart, drawCount, object.count );
  14363. } else if ( geometry.isInstancedBufferGeometry ) {
  14364. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  14365. renderer.renderInstances( drawStart, drawCount, instanceCount );
  14366. } else {
  14367. renderer.render( drawStart, drawCount );
  14368. }
  14369. };
  14370. // Compile
  14371. this.compile = function ( scene, camera ) {
  14372. currentRenderState = renderStates.get( scene );
  14373. currentRenderState.init();
  14374. scene.traverseVisible( function ( object ) {
  14375. if ( object.isLight && object.layers.test( camera.layers ) ) {
  14376. currentRenderState.pushLight( object );
  14377. if ( object.castShadow ) {
  14378. currentRenderState.pushShadow( object );
  14379. }
  14380. }
  14381. } );
  14382. currentRenderState.setupLights();
  14383. const compiled = new WeakMap();
  14384. scene.traverse( function ( object ) {
  14385. const material = object.material;
  14386. if ( material ) {
  14387. if ( Array.isArray( material ) ) {
  14388. for ( let i = 0; i < material.length; i ++ ) {
  14389. const material2 = material[ i ];
  14390. if ( compiled.has( material2 ) === false ) {
  14391. initMaterial( material2, scene, object );
  14392. compiled.set( material2 );
  14393. }
  14394. }
  14395. } else if ( compiled.has( material ) === false ) {
  14396. initMaterial( material, scene, object );
  14397. compiled.set( material );
  14398. }
  14399. }
  14400. } );
  14401. };
  14402. // Animation Loop
  14403. let onAnimationFrameCallback = null;
  14404. function onAnimationFrame( time ) {
  14405. if ( xr.isPresenting ) return;
  14406. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  14407. }
  14408. const animation = new WebGLAnimation();
  14409. animation.setAnimationLoop( onAnimationFrame );
  14410. if ( typeof window !== 'undefined' ) animation.setContext( window );
  14411. this.setAnimationLoop = function ( callback ) {
  14412. onAnimationFrameCallback = callback;
  14413. xr.setAnimationLoop( callback );
  14414. ( callback === null ) ? animation.stop() : animation.start();
  14415. };
  14416. // Rendering
  14417. this.render = function ( scene, camera ) {
  14418. let renderTarget, forceClear;
  14419. if ( arguments[ 2 ] !== undefined ) {
  14420. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  14421. renderTarget = arguments[ 2 ];
  14422. }
  14423. if ( arguments[ 3 ] !== undefined ) {
  14424. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  14425. forceClear = arguments[ 3 ];
  14426. }
  14427. if ( camera !== undefined && camera.isCamera !== true ) {
  14428. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14429. return;
  14430. }
  14431. if ( _isContextLost === true ) return;
  14432. // reset caching for this frame
  14433. bindingStates.resetDefaultState();
  14434. _currentMaterialId = - 1;
  14435. _currentCamera = null;
  14436. // update scene graph
  14437. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14438. // update camera matrices and frustum
  14439. if ( camera.parent === null ) camera.updateMatrixWorld();
  14440. if ( xr.enabled === true && xr.isPresenting === true ) {
  14441. camera = xr.getCamera( camera );
  14442. }
  14443. //
  14444. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  14445. currentRenderState = renderStates.get( scene, renderStateStack.length );
  14446. currentRenderState.init();
  14447. renderStateStack.push( currentRenderState );
  14448. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14449. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  14450. _localClippingEnabled = this.localClippingEnabled;
  14451. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  14452. currentRenderList = renderLists.get( scene, camera );
  14453. currentRenderList.init();
  14454. projectObject( scene, camera, 0, _this.sortObjects );
  14455. currentRenderList.finish();
  14456. if ( _this.sortObjects === true ) {
  14457. currentRenderList.sort( _opaqueSort, _transparentSort );
  14458. }
  14459. //
  14460. if ( _clippingEnabled === true ) clipping.beginShadows();
  14461. const shadowsArray = currentRenderState.state.shadowsArray;
  14462. shadowMap.render( shadowsArray, scene, camera );
  14463. currentRenderState.setupLights();
  14464. currentRenderState.setupLightsView( camera );
  14465. if ( _clippingEnabled === true ) clipping.endShadows();
  14466. //
  14467. if ( this.info.autoReset === true ) this.info.reset();
  14468. if ( renderTarget !== undefined ) {
  14469. this.setRenderTarget( renderTarget );
  14470. }
  14471. //
  14472. background.render( currentRenderList, scene, camera, forceClear );
  14473. // render scene
  14474. const opaqueObjects = currentRenderList.opaque;
  14475. const transparentObjects = currentRenderList.transparent;
  14476. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  14477. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  14478. //
  14479. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  14480. //
  14481. if ( _currentRenderTarget !== null ) {
  14482. // Generate mipmap if we're using any kind of mipmap filtering
  14483. textures.updateRenderTargetMipmap( _currentRenderTarget );
  14484. // resolve multisample renderbuffers to a single-sample texture if necessary
  14485. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  14486. }
  14487. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14488. state.buffers.depth.setTest( true );
  14489. state.buffers.depth.setMask( true );
  14490. state.buffers.color.setMask( true );
  14491. state.setPolygonOffset( false );
  14492. // _gl.finish();
  14493. renderStateStack.pop();
  14494. if ( renderStateStack.length > 0 ) {
  14495. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  14496. } else {
  14497. currentRenderState = null;
  14498. }
  14499. currentRenderList = null;
  14500. };
  14501. function projectObject( object, camera, groupOrder, sortObjects ) {
  14502. if ( object.visible === false ) return;
  14503. const visible = object.layers.test( camera.layers );
  14504. if ( visible ) {
  14505. if ( object.isGroup ) {
  14506. groupOrder = object.renderOrder;
  14507. } else if ( object.isLOD ) {
  14508. if ( object.autoUpdate === true ) object.update( camera );
  14509. } else if ( object.isLight ) {
  14510. currentRenderState.pushLight( object );
  14511. if ( object.castShadow ) {
  14512. currentRenderState.pushShadow( object );
  14513. }
  14514. } else if ( object.isSprite ) {
  14515. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  14516. if ( sortObjects ) {
  14517. _vector3.setFromMatrixPosition( object.matrixWorld )
  14518. .applyMatrix4( _projScreenMatrix );
  14519. }
  14520. const geometry = objects.update( object );
  14521. const material = object.material;
  14522. if ( material.visible ) {
  14523. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  14524. }
  14525. }
  14526. } else if ( object.isImmediateRenderObject ) {
  14527. if ( sortObjects ) {
  14528. _vector3.setFromMatrixPosition( object.matrixWorld )
  14529. .applyMatrix4( _projScreenMatrix );
  14530. }
  14531. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  14532. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  14533. if ( object.isSkinnedMesh ) {
  14534. // update skeleton only once in a frame
  14535. if ( object.skeleton.frame !== info.render.frame ) {
  14536. object.skeleton.update();
  14537. object.skeleton.frame = info.render.frame;
  14538. }
  14539. }
  14540. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  14541. if ( sortObjects ) {
  14542. _vector3.setFromMatrixPosition( object.matrixWorld )
  14543. .applyMatrix4( _projScreenMatrix );
  14544. }
  14545. const geometry = objects.update( object );
  14546. const material = object.material;
  14547. if ( Array.isArray( material ) ) {
  14548. const groups = geometry.groups;
  14549. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14550. const group = groups[ i ];
  14551. const groupMaterial = material[ group.materialIndex ];
  14552. if ( groupMaterial && groupMaterial.visible ) {
  14553. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  14554. }
  14555. }
  14556. } else if ( material.visible ) {
  14557. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  14558. }
  14559. }
  14560. }
  14561. }
  14562. const children = object.children;
  14563. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14564. projectObject( children[ i ], camera, groupOrder, sortObjects );
  14565. }
  14566. }
  14567. function renderObjects( renderList, scene, camera ) {
  14568. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14569. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  14570. const renderItem = renderList[ i ];
  14571. const object = renderItem.object;
  14572. const geometry = renderItem.geometry;
  14573. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14574. const group = renderItem.group;
  14575. if ( camera.isArrayCamera ) {
  14576. const cameras = camera.cameras;
  14577. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  14578. const camera2 = cameras[ j ];
  14579. if ( object.layers.test( camera2.layers ) ) {
  14580. state.viewport( _currentViewport.copy( camera2.viewport ) );
  14581. currentRenderState.setupLightsView( camera2 );
  14582. renderObject( object, scene, camera2, geometry, material, group );
  14583. }
  14584. }
  14585. } else {
  14586. renderObject( object, scene, camera, geometry, material, group );
  14587. }
  14588. }
  14589. }
  14590. function renderObject( object, scene, camera, geometry, material, group ) {
  14591. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  14592. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14593. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  14594. if ( object.isImmediateRenderObject ) {
  14595. const program = setProgram( camera, scene, material, object );
  14596. state.setMaterial( material );
  14597. bindingStates.reset();
  14598. renderObjectImmediate( object, program );
  14599. } else {
  14600. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  14601. }
  14602. object.onAfterRender( _this, scene, camera, geometry, material, group );
  14603. }
  14604. function initMaterial( material, scene, object ) {
  14605. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14606. const materialProperties = properties.get( material );
  14607. const lights = currentRenderState.state.lights;
  14608. const shadowsArray = currentRenderState.state.shadowsArray;
  14609. const lightsStateVersion = lights.state.version;
  14610. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  14611. const programCacheKey = programCache.getProgramCacheKey( parameters );
  14612. let program = materialProperties.program;
  14613. let programChange = true;
  14614. if ( program === undefined ) {
  14615. // new material
  14616. material.addEventListener( 'dispose', onMaterialDispose );
  14617. } else if ( program.cacheKey !== programCacheKey ) {
  14618. // changed glsl or parameters
  14619. releaseMaterialProgramReference( material );
  14620. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  14621. programChange = false;
  14622. } else if ( parameters.shaderID !== undefined ) {
  14623. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  14624. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14625. materialProperties.envMap = cubemaps.get( material.envMap || environment );
  14626. return;
  14627. } else {
  14628. // only rebuild uniform list
  14629. programChange = false;
  14630. }
  14631. if ( programChange ) {
  14632. parameters.uniforms = programCache.getUniforms( material );
  14633. material.onBeforeCompile( parameters, _this );
  14634. program = programCache.acquireProgram( parameters, programCacheKey );
  14635. materialProperties.program = program;
  14636. materialProperties.uniforms = parameters.uniforms;
  14637. materialProperties.outputEncoding = parameters.outputEncoding;
  14638. }
  14639. const uniforms = materialProperties.uniforms;
  14640. if ( ! material.isShaderMaterial &&
  14641. ! material.isRawShaderMaterial ||
  14642. material.clipping === true ) {
  14643. materialProperties.numClippingPlanes = clipping.numPlanes;
  14644. materialProperties.numIntersection = clipping.numIntersection;
  14645. uniforms.clippingPlanes = clipping.uniform;
  14646. }
  14647. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14648. materialProperties.fog = scene.fog;
  14649. materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment );
  14650. // store the light setup it was created for
  14651. materialProperties.needsLights = materialNeedsLights( material );
  14652. materialProperties.lightsStateVersion = lightsStateVersion;
  14653. if ( materialProperties.needsLights ) {
  14654. // wire up the material to this renderer's lighting state
  14655. uniforms.ambientLightColor.value = lights.state.ambient;
  14656. uniforms.lightProbe.value = lights.state.probe;
  14657. uniforms.directionalLights.value = lights.state.directional;
  14658. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14659. uniforms.spotLights.value = lights.state.spot;
  14660. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14661. uniforms.rectAreaLights.value = lights.state.rectArea;
  14662. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14663. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14664. uniforms.pointLights.value = lights.state.point;
  14665. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14666. uniforms.hemisphereLights.value = lights.state.hemi;
  14667. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14668. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14669. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14670. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14671. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14672. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  14673. // TODO (abelnation): add area lights shadow info to uniforms
  14674. }
  14675. const progUniforms = materialProperties.program.getUniforms();
  14676. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  14677. materialProperties.uniformsList = uniformsList;
  14678. }
  14679. function setProgram( camera, scene, material, object ) {
  14680. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14681. textures.resetTextureUnits();
  14682. const fog = scene.fog;
  14683. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14684. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14685. const envMap = cubemaps.get( material.envMap || environment );
  14686. const materialProperties = properties.get( material );
  14687. const lights = currentRenderState.state.lights;
  14688. if ( _clippingEnabled === true ) {
  14689. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  14690. const useCache =
  14691. camera === _currentCamera &&
  14692. material.id === _currentMaterialId;
  14693. // we might want to call this function with some ClippingGroup
  14694. // object instead of the material, once it becomes feasible
  14695. // (#8465, #8379)
  14696. clipping.setState( material, camera, useCache );
  14697. }
  14698. }
  14699. if ( material.version === materialProperties.__version ) {
  14700. if ( material.fog && materialProperties.fog !== fog ) {
  14701. initMaterial( material, scene, object );
  14702. } else if ( materialProperties.environment !== environment ) {
  14703. initMaterial( material, scene, object );
  14704. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  14705. initMaterial( material, scene, object );
  14706. } else if ( materialProperties.numClippingPlanes !== undefined &&
  14707. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  14708. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  14709. initMaterial( material, scene, object );
  14710. } else if ( materialProperties.outputEncoding !== encoding ) {
  14711. initMaterial( material, scene, object );
  14712. } else if ( materialProperties.envMap !== envMap ) {
  14713. initMaterial( material, scene, object );
  14714. }
  14715. } else {
  14716. initMaterial( material, scene, object );
  14717. materialProperties.__version = material.version;
  14718. }
  14719. let refreshProgram = false;
  14720. let refreshMaterial = false;
  14721. let refreshLights = false;
  14722. const program = materialProperties.program,
  14723. p_uniforms = program.getUniforms(),
  14724. m_uniforms = materialProperties.uniforms;
  14725. if ( state.useProgram( program.program ) ) {
  14726. refreshProgram = true;
  14727. refreshMaterial = true;
  14728. refreshLights = true;
  14729. }
  14730. if ( material.id !== _currentMaterialId ) {
  14731. _currentMaterialId = material.id;
  14732. refreshMaterial = true;
  14733. }
  14734. if ( refreshProgram || _currentCamera !== camera ) {
  14735. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  14736. if ( capabilities.logarithmicDepthBuffer ) {
  14737. p_uniforms.setValue( _gl, 'logDepthBufFC',
  14738. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  14739. }
  14740. if ( _currentCamera !== camera ) {
  14741. _currentCamera = camera;
  14742. // lighting uniforms depend on the camera so enforce an update
  14743. // now, in case this material supports lights - or later, when
  14744. // the next material that does gets activated:
  14745. refreshMaterial = true; // set to true on material change
  14746. refreshLights = true; // remains set until update done
  14747. }
  14748. // load material specific uniforms
  14749. // (shader material also gets them for the sake of genericity)
  14750. if ( material.isShaderMaterial ||
  14751. material.isMeshPhongMaterial ||
  14752. material.isMeshToonMaterial ||
  14753. material.isMeshStandardMaterial ||
  14754. material.envMap ) {
  14755. const uCamPos = p_uniforms.map.cameraPosition;
  14756. if ( uCamPos !== undefined ) {
  14757. uCamPos.setValue( _gl,
  14758. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  14759. }
  14760. }
  14761. if ( material.isMeshPhongMaterial ||
  14762. material.isMeshToonMaterial ||
  14763. material.isMeshLambertMaterial ||
  14764. material.isMeshBasicMaterial ||
  14765. material.isMeshStandardMaterial ||
  14766. material.isShaderMaterial ) {
  14767. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  14768. }
  14769. if ( material.isMeshPhongMaterial ||
  14770. material.isMeshToonMaterial ||
  14771. material.isMeshLambertMaterial ||
  14772. material.isMeshBasicMaterial ||
  14773. material.isMeshStandardMaterial ||
  14774. material.isShaderMaterial ||
  14775. material.isShadowMaterial ||
  14776. material.skinning ) {
  14777. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  14778. }
  14779. }
  14780. // skinning uniforms must be set even if material didn't change
  14781. // auto-setting of texture unit for bone texture must go before other textures
  14782. // otherwise textures used for skinning can take over texture units reserved for other material textures
  14783. if ( material.skinning ) {
  14784. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  14785. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  14786. const skeleton = object.skeleton;
  14787. if ( skeleton ) {
  14788. const bones = skeleton.bones;
  14789. if ( capabilities.floatVertexTextures ) {
  14790. if ( skeleton.boneTexture === null ) {
  14791. // layout (1 matrix = 4 pixels)
  14792. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14793. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14794. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14795. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14796. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14797. let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  14798. size = MathUtils.ceilPowerOfTwo( size );
  14799. size = Math.max( size, 4 );
  14800. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  14801. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  14802. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  14803. skeleton.boneMatrices = boneMatrices;
  14804. skeleton.boneTexture = boneTexture;
  14805. skeleton.boneTextureSize = size;
  14806. }
  14807. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  14808. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  14809. } else {
  14810. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  14811. }
  14812. }
  14813. }
  14814. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  14815. materialProperties.receiveShadow = object.receiveShadow;
  14816. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  14817. }
  14818. if ( refreshMaterial ) {
  14819. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  14820. if ( materialProperties.needsLights ) {
  14821. // the current material requires lighting info
  14822. // note: all lighting uniforms are always set correctly
  14823. // they simply reference the renderer's state for their
  14824. // values
  14825. //
  14826. // use the current material's .needsUpdate flags to set
  14827. // the GL state when required
  14828. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  14829. }
  14830. // refresh uniforms common to several materials
  14831. if ( fog && material.fog ) {
  14832. materials.refreshFogUniforms( m_uniforms, fog );
  14833. }
  14834. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height );
  14835. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  14836. }
  14837. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  14838. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  14839. material.uniformsNeedUpdate = false;
  14840. }
  14841. if ( material.isSpriteMaterial ) {
  14842. p_uniforms.setValue( _gl, 'center', object.center );
  14843. }
  14844. // common matrices
  14845. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  14846. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  14847. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  14848. return program;
  14849. }
  14850. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  14851. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  14852. uniforms.ambientLightColor.needsUpdate = value;
  14853. uniforms.lightProbe.needsUpdate = value;
  14854. uniforms.directionalLights.needsUpdate = value;
  14855. uniforms.directionalLightShadows.needsUpdate = value;
  14856. uniforms.pointLights.needsUpdate = value;
  14857. uniforms.pointLightShadows.needsUpdate = value;
  14858. uniforms.spotLights.needsUpdate = value;
  14859. uniforms.spotLightShadows.needsUpdate = value;
  14860. uniforms.rectAreaLights.needsUpdate = value;
  14861. uniforms.hemisphereLights.needsUpdate = value;
  14862. }
  14863. function materialNeedsLights( material ) {
  14864. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  14865. material.isMeshStandardMaterial || material.isShadowMaterial ||
  14866. ( material.isShaderMaterial && material.lights === true );
  14867. }
  14868. //
  14869. this.setFramebuffer = function ( value ) {
  14870. if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value );
  14871. _framebuffer = value;
  14872. };
  14873. this.getActiveCubeFace = function () {
  14874. return _currentActiveCubeFace;
  14875. };
  14876. this.getActiveMipmapLevel = function () {
  14877. return _currentActiveMipmapLevel;
  14878. };
  14879. this.getRenderList = function () {
  14880. return currentRenderList;
  14881. };
  14882. this.setRenderList = function ( renderList ) {
  14883. currentRenderList = renderList;
  14884. };
  14885. this.getRenderTarget = function () {
  14886. return _currentRenderTarget;
  14887. };
  14888. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  14889. _currentRenderTarget = renderTarget;
  14890. _currentActiveCubeFace = activeCubeFace;
  14891. _currentActiveMipmapLevel = activeMipmapLevel;
  14892. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  14893. textures.setupRenderTarget( renderTarget );
  14894. }
  14895. let framebuffer = _framebuffer;
  14896. let isCube = false;
  14897. if ( renderTarget ) {
  14898. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  14899. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14900. framebuffer = __webglFramebuffer[ activeCubeFace ];
  14901. isCube = true;
  14902. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  14903. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  14904. } else {
  14905. framebuffer = __webglFramebuffer;
  14906. }
  14907. _currentViewport.copy( renderTarget.viewport );
  14908. _currentScissor.copy( renderTarget.scissor );
  14909. _currentScissorTest = renderTarget.scissorTest;
  14910. } else {
  14911. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  14912. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  14913. _currentScissorTest = _scissorTest;
  14914. }
  14915. if ( _currentFramebuffer !== framebuffer ) {
  14916. _gl.bindFramebuffer( 36160, framebuffer );
  14917. _currentFramebuffer = framebuffer;
  14918. }
  14919. state.viewport( _currentViewport );
  14920. state.scissor( _currentScissor );
  14921. state.setScissorTest( _currentScissorTest );
  14922. if ( isCube ) {
  14923. const textureProperties = properties.get( renderTarget.texture );
  14924. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  14925. }
  14926. };
  14927. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  14928. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  14929. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  14930. return;
  14931. }
  14932. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  14933. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  14934. framebuffer = framebuffer[ activeCubeFaceIndex ];
  14935. }
  14936. if ( framebuffer ) {
  14937. let restore = false;
  14938. if ( framebuffer !== _currentFramebuffer ) {
  14939. _gl.bindFramebuffer( 36160, framebuffer );
  14940. restore = true;
  14941. }
  14942. try {
  14943. const texture = renderTarget.texture;
  14944. const textureFormat = texture.format;
  14945. const textureType = texture.type;
  14946. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  14947. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  14948. return;
  14949. }
  14950. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  14951. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  14952. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  14953. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  14954. return;
  14955. }
  14956. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  14957. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  14958. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  14959. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  14960. }
  14961. } else {
  14962. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  14963. }
  14964. } finally {
  14965. if ( restore ) {
  14966. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  14967. }
  14968. }
  14969. }
  14970. };
  14971. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  14972. const levelScale = Math.pow( 2, - level );
  14973. const width = Math.floor( texture.image.width * levelScale );
  14974. const height = Math.floor( texture.image.height * levelScale );
  14975. const glFormat = utils.convert( texture.format );
  14976. textures.setTexture2D( texture, 0 );
  14977. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  14978. state.unbindTexture();
  14979. };
  14980. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  14981. const width = srcTexture.image.width;
  14982. const height = srcTexture.image.height;
  14983. const glFormat = utils.convert( dstTexture.format );
  14984. const glType = utils.convert( dstTexture.type );
  14985. textures.setTexture2D( dstTexture, 0 );
  14986. // As another texture upload may have changed pixelStorei
  14987. // parameters, make sure they are correct for the dstTexture
  14988. _gl.pixelStorei( 37440, dstTexture.flipY );
  14989. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  14990. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  14991. if ( srcTexture.isDataTexture ) {
  14992. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  14993. } else {
  14994. if ( srcTexture.isCompressedTexture ) {
  14995. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  14996. } else {
  14997. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  14998. }
  14999. }
  15000. // Generate mipmaps only when copying level 0
  15001. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  15002. state.unbindTexture();
  15003. };
  15004. this.initTexture = function ( texture ) {
  15005. textures.setTexture2D( texture, 0 );
  15006. state.unbindTexture();
  15007. };
  15008. this.resetState = function () {
  15009. state.reset();
  15010. bindingStates.reset();
  15011. };
  15012. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15013. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15014. }
  15015. }
  15016. function WebGL1Renderer( parameters ) {
  15017. WebGLRenderer.call( this, parameters );
  15018. }
  15019. WebGL1Renderer.prototype = Object.assign( Object.create( WebGLRenderer.prototype ), {
  15020. constructor: WebGL1Renderer,
  15021. isWebGL1Renderer: true
  15022. } );
  15023. class FogExp2 {
  15024. constructor( color, density ) {
  15025. Object.defineProperty( this, 'isFogExp2', { value: true } );
  15026. this.name = '';
  15027. this.color = new Color( color );
  15028. this.density = ( density !== undefined ) ? density : 0.00025;
  15029. }
  15030. clone() {
  15031. return new FogExp2( this.color, this.density );
  15032. }
  15033. toJSON( /* meta */ ) {
  15034. return {
  15035. type: 'FogExp2',
  15036. color: this.color.getHex(),
  15037. density: this.density
  15038. };
  15039. }
  15040. }
  15041. class Fog {
  15042. constructor( color, near, far ) {
  15043. Object.defineProperty( this, 'isFog', { value: true } );
  15044. this.name = '';
  15045. this.color = new Color( color );
  15046. this.near = ( near !== undefined ) ? near : 1;
  15047. this.far = ( far !== undefined ) ? far : 1000;
  15048. }
  15049. clone() {
  15050. return new Fog( this.color, this.near, this.far );
  15051. }
  15052. toJSON( /* meta */ ) {
  15053. return {
  15054. type: 'Fog',
  15055. color: this.color.getHex(),
  15056. near: this.near,
  15057. far: this.far
  15058. };
  15059. }
  15060. }
  15061. class Scene extends Object3D {
  15062. constructor() {
  15063. super();
  15064. Object.defineProperty( this, 'isScene', { value: true } );
  15065. this.type = 'Scene';
  15066. this.background = null;
  15067. this.environment = null;
  15068. this.fog = null;
  15069. this.overrideMaterial = null;
  15070. this.autoUpdate = true; // checked by the renderer
  15071. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15072. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15073. }
  15074. }
  15075. copy( source, recursive ) {
  15076. super.copy( source, recursive );
  15077. if ( source.background !== null ) this.background = source.background.clone();
  15078. if ( source.environment !== null ) this.environment = source.environment.clone();
  15079. if ( source.fog !== null ) this.fog = source.fog.clone();
  15080. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  15081. this.autoUpdate = source.autoUpdate;
  15082. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15083. return this;
  15084. }
  15085. toJSON( meta ) {
  15086. const data = super.toJSON( meta );
  15087. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  15088. if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
  15089. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  15090. return data;
  15091. }
  15092. }
  15093. function InterleavedBuffer( array, stride ) {
  15094. this.array = array;
  15095. this.stride = stride;
  15096. this.count = array !== undefined ? array.length / stride : 0;
  15097. this.usage = StaticDrawUsage;
  15098. this.updateRange = { offset: 0, count: - 1 };
  15099. this.version = 0;
  15100. this.uuid = MathUtils.generateUUID();
  15101. }
  15102. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  15103. set: function ( value ) {
  15104. if ( value === true ) this.version ++;
  15105. }
  15106. } );
  15107. Object.assign( InterleavedBuffer.prototype, {
  15108. isInterleavedBuffer: true,
  15109. onUploadCallback: function () {},
  15110. setUsage: function ( value ) {
  15111. this.usage = value;
  15112. return this;
  15113. },
  15114. copy: function ( source ) {
  15115. this.array = new source.array.constructor( source.array );
  15116. this.count = source.count;
  15117. this.stride = source.stride;
  15118. this.usage = source.usage;
  15119. return this;
  15120. },
  15121. copyAt: function ( index1, attribute, index2 ) {
  15122. index1 *= this.stride;
  15123. index2 *= attribute.stride;
  15124. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  15125. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  15126. }
  15127. return this;
  15128. },
  15129. set: function ( value, offset = 0 ) {
  15130. this.array.set( value, offset );
  15131. return this;
  15132. },
  15133. clone: function ( data ) {
  15134. if ( data.arrayBuffers === undefined ) {
  15135. data.arrayBuffers = {};
  15136. }
  15137. if ( this.array.buffer._uuid === undefined ) {
  15138. this.array.buffer._uuid = MathUtils.generateUUID();
  15139. }
  15140. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15141. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  15142. }
  15143. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  15144. const ib = new InterleavedBuffer( array, this.stride );
  15145. ib.setUsage( this.usage );
  15146. return ib;
  15147. },
  15148. onUpload: function ( callback ) {
  15149. this.onUploadCallback = callback;
  15150. return this;
  15151. },
  15152. toJSON: function ( data ) {
  15153. if ( data.arrayBuffers === undefined ) {
  15154. data.arrayBuffers = {};
  15155. }
  15156. // generate UUID for array buffer if necessary
  15157. if ( this.array.buffer._uuid === undefined ) {
  15158. this.array.buffer._uuid = MathUtils.generateUUID();
  15159. }
  15160. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15161. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  15162. }
  15163. //
  15164. return {
  15165. uuid: this.uuid,
  15166. buffer: this.array.buffer._uuid,
  15167. type: this.array.constructor.name,
  15168. stride: this.stride
  15169. };
  15170. }
  15171. } );
  15172. const _vector$6 = new Vector3();
  15173. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  15174. this.name = '';
  15175. this.data = interleavedBuffer;
  15176. this.itemSize = itemSize;
  15177. this.offset = offset;
  15178. this.normalized = normalized === true;
  15179. }
  15180. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  15181. count: {
  15182. get: function () {
  15183. return this.data.count;
  15184. }
  15185. },
  15186. array: {
  15187. get: function () {
  15188. return this.data.array;
  15189. }
  15190. },
  15191. needsUpdate: {
  15192. set: function ( value ) {
  15193. this.data.needsUpdate = value;
  15194. }
  15195. }
  15196. } );
  15197. Object.assign( InterleavedBufferAttribute.prototype, {
  15198. isInterleavedBufferAttribute: true,
  15199. applyMatrix4: function ( m ) {
  15200. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  15201. _vector$6.x = this.getX( i );
  15202. _vector$6.y = this.getY( i );
  15203. _vector$6.z = this.getZ( i );
  15204. _vector$6.applyMatrix4( m );
  15205. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15206. }
  15207. return this;
  15208. },
  15209. setX: function ( index, x ) {
  15210. this.data.array[ index * this.data.stride + this.offset ] = x;
  15211. return this;
  15212. },
  15213. setY: function ( index, y ) {
  15214. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15215. return this;
  15216. },
  15217. setZ: function ( index, z ) {
  15218. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15219. return this;
  15220. },
  15221. setW: function ( index, w ) {
  15222. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15223. return this;
  15224. },
  15225. getX: function ( index ) {
  15226. return this.data.array[ index * this.data.stride + this.offset ];
  15227. },
  15228. getY: function ( index ) {
  15229. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  15230. },
  15231. getZ: function ( index ) {
  15232. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  15233. },
  15234. getW: function ( index ) {
  15235. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  15236. },
  15237. setXY: function ( index, x, y ) {
  15238. index = index * this.data.stride + this.offset;
  15239. this.data.array[ index + 0 ] = x;
  15240. this.data.array[ index + 1 ] = y;
  15241. return this;
  15242. },
  15243. setXYZ: function ( index, x, y, z ) {
  15244. index = index * this.data.stride + this.offset;
  15245. this.data.array[ index + 0 ] = x;
  15246. this.data.array[ index + 1 ] = y;
  15247. this.data.array[ index + 2 ] = z;
  15248. return this;
  15249. },
  15250. setXYZW: function ( index, x, y, z, w ) {
  15251. index = index * this.data.stride + this.offset;
  15252. this.data.array[ index + 0 ] = x;
  15253. this.data.array[ index + 1 ] = y;
  15254. this.data.array[ index + 2 ] = z;
  15255. this.data.array[ index + 3 ] = w;
  15256. return this;
  15257. },
  15258. clone: function ( data ) {
  15259. if ( data === undefined ) {
  15260. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  15261. const array = [];
  15262. for ( let i = 0; i < this.count; i ++ ) {
  15263. const index = i * this.data.stride + this.offset;
  15264. for ( let j = 0; j < this.itemSize; j ++ ) {
  15265. array.push( this.data.array[ index + j ] );
  15266. }
  15267. }
  15268. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15269. } else {
  15270. if ( data.interleavedBuffers === undefined ) {
  15271. data.interleavedBuffers = {};
  15272. }
  15273. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15274. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15275. }
  15276. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15277. }
  15278. },
  15279. toJSON: function ( data ) {
  15280. if ( data === undefined ) {
  15281. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  15282. const array = [];
  15283. for ( let i = 0; i < this.count; i ++ ) {
  15284. const index = i * this.data.stride + this.offset;
  15285. for ( let j = 0; j < this.itemSize; j ++ ) {
  15286. array.push( this.data.array[ index + j ] );
  15287. }
  15288. }
  15289. // deinterleave data and save it as an ordinary buffer attribute for now
  15290. return {
  15291. itemSize: this.itemSize,
  15292. type: this.array.constructor.name,
  15293. array: array,
  15294. normalized: this.normalized
  15295. };
  15296. } else {
  15297. // save as true interlaved attribtue
  15298. if ( data.interleavedBuffers === undefined ) {
  15299. data.interleavedBuffers = {};
  15300. }
  15301. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15302. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15303. }
  15304. return {
  15305. isInterleavedBufferAttribute: true,
  15306. itemSize: this.itemSize,
  15307. data: this.data.uuid,
  15308. offset: this.offset,
  15309. normalized: this.normalized
  15310. };
  15311. }
  15312. }
  15313. } );
  15314. /**
  15315. * parameters = {
  15316. * color: <hex>,
  15317. * map: new THREE.Texture( <Image> ),
  15318. * alphaMap: new THREE.Texture( <Image> ),
  15319. * rotation: <float>,
  15320. * sizeAttenuation: <bool>
  15321. * }
  15322. */
  15323. function SpriteMaterial( parameters ) {
  15324. Material.call( this );
  15325. this.type = 'SpriteMaterial';
  15326. this.color = new Color( 0xffffff );
  15327. this.map = null;
  15328. this.alphaMap = null;
  15329. this.rotation = 0;
  15330. this.sizeAttenuation = true;
  15331. this.transparent = true;
  15332. this.setValues( parameters );
  15333. }
  15334. SpriteMaterial.prototype = Object.create( Material.prototype );
  15335. SpriteMaterial.prototype.constructor = SpriteMaterial;
  15336. SpriteMaterial.prototype.isSpriteMaterial = true;
  15337. SpriteMaterial.prototype.copy = function ( source ) {
  15338. Material.prototype.copy.call( this, source );
  15339. this.color.copy( source.color );
  15340. this.map = source.map;
  15341. this.alphaMap = source.alphaMap;
  15342. this.rotation = source.rotation;
  15343. this.sizeAttenuation = source.sizeAttenuation;
  15344. return this;
  15345. };
  15346. let _geometry;
  15347. const _intersectPoint = new Vector3();
  15348. const _worldScale = new Vector3();
  15349. const _mvPosition = new Vector3();
  15350. const _alignedPosition = new Vector2();
  15351. const _rotatedPosition = new Vector2();
  15352. const _viewWorldMatrix = new Matrix4();
  15353. const _vA$1 = new Vector3();
  15354. const _vB$1 = new Vector3();
  15355. const _vC$1 = new Vector3();
  15356. const _uvA$1 = new Vector2();
  15357. const _uvB$1 = new Vector2();
  15358. const _uvC$1 = new Vector2();
  15359. function Sprite$1( material ) {
  15360. Object3D.call( this );
  15361. this.type = 'Sprite';
  15362. if ( _geometry === undefined ) {
  15363. _geometry = new BufferGeometry();
  15364. const float32Array = new Float32Array( [
  15365. - 0.5, - 0.5, 0, 0, 0,
  15366. 0.5, - 0.5, 0, 1, 0,
  15367. 0.5, 0.5, 0, 1, 1,
  15368. - 0.5, 0.5, 0, 0, 1
  15369. ] );
  15370. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  15371. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  15372. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  15373. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  15374. }
  15375. this.geometry = _geometry;
  15376. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  15377. this.center = new Vector2( 0.5, 0.5 );
  15378. }
  15379. Sprite$1.prototype = Object.assign( Object.create( Object3D.prototype ), {
  15380. constructor: Sprite$1,
  15381. isSprite: true,
  15382. raycast: function ( raycaster, intersects ) {
  15383. if ( raycaster.camera === null ) {
  15384. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  15385. }
  15386. _worldScale.setFromMatrixScale( this.matrixWorld );
  15387. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  15388. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  15389. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  15390. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  15391. _worldScale.multiplyScalar( - _mvPosition.z );
  15392. }
  15393. const rotation = this.material.rotation;
  15394. let sin, cos;
  15395. if ( rotation !== 0 ) {
  15396. cos = Math.cos( rotation );
  15397. sin = Math.sin( rotation );
  15398. }
  15399. const center = this.center;
  15400. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15401. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15402. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15403. _uvA$1.set( 0, 0 );
  15404. _uvB$1.set( 1, 0 );
  15405. _uvC$1.set( 1, 1 );
  15406. // check first triangle
  15407. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  15408. if ( intersect === null ) {
  15409. // check second triangle
  15410. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  15411. _uvB$1.set( 0, 1 );
  15412. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  15413. if ( intersect === null ) {
  15414. return;
  15415. }
  15416. }
  15417. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  15418. if ( distance < raycaster.near || distance > raycaster.far ) return;
  15419. intersects.push( {
  15420. distance: distance,
  15421. point: _intersectPoint.clone(),
  15422. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
  15423. face: null,
  15424. object: this
  15425. } );
  15426. },
  15427. copy: function ( source ) {
  15428. Object3D.prototype.copy.call( this, source );
  15429. if ( source.center !== undefined ) this.center.copy( source.center );
  15430. this.material = source.material;
  15431. return this;
  15432. }
  15433. } );
  15434. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  15435. // compute position in camera space
  15436. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  15437. // to check if rotation is not zero
  15438. if ( sin !== undefined ) {
  15439. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  15440. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  15441. } else {
  15442. _rotatedPosition.copy( _alignedPosition );
  15443. }
  15444. vertexPosition.copy( mvPosition );
  15445. vertexPosition.x += _rotatedPosition.x;
  15446. vertexPosition.y += _rotatedPosition.y;
  15447. // transform to world space
  15448. vertexPosition.applyMatrix4( _viewWorldMatrix );
  15449. }
  15450. const _v1$4 = new Vector3();
  15451. const _v2$2 = new Vector3();
  15452. function LOD() {
  15453. Object3D.call( this );
  15454. this._currentLevel = 0;
  15455. this.type = 'LOD';
  15456. Object.defineProperties( this, {
  15457. levels: {
  15458. enumerable: true,
  15459. value: []
  15460. }
  15461. } );
  15462. this.autoUpdate = true;
  15463. }
  15464. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  15465. constructor: LOD,
  15466. isLOD: true,
  15467. copy: function ( source ) {
  15468. Object3D.prototype.copy.call( this, source, false );
  15469. const levels = source.levels;
  15470. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  15471. const level = levels[ i ];
  15472. this.addLevel( level.object.clone(), level.distance );
  15473. }
  15474. this.autoUpdate = source.autoUpdate;
  15475. return this;
  15476. },
  15477. addLevel: function ( object, distance = 0 ) {
  15478. distance = Math.abs( distance );
  15479. const levels = this.levels;
  15480. let l;
  15481. for ( l = 0; l < levels.length; l ++ ) {
  15482. if ( distance < levels[ l ].distance ) {
  15483. break;
  15484. }
  15485. }
  15486. levels.splice( l, 0, { distance: distance, object: object } );
  15487. this.add( object );
  15488. return this;
  15489. },
  15490. getCurrentLevel: function () {
  15491. return this._currentLevel;
  15492. },
  15493. getObjectForDistance: function ( distance ) {
  15494. const levels = this.levels;
  15495. if ( levels.length > 0 ) {
  15496. let i, l;
  15497. for ( i = 1, l = levels.length; i < l; i ++ ) {
  15498. if ( distance < levels[ i ].distance ) {
  15499. break;
  15500. }
  15501. }
  15502. return levels[ i - 1 ].object;
  15503. }
  15504. return null;
  15505. },
  15506. raycast: function ( raycaster, intersects ) {
  15507. const levels = this.levels;
  15508. if ( levels.length > 0 ) {
  15509. _v1$4.setFromMatrixPosition( this.matrixWorld );
  15510. const distance = raycaster.ray.origin.distanceTo( _v1$4 );
  15511. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  15512. }
  15513. },
  15514. update: function ( camera ) {
  15515. const levels = this.levels;
  15516. if ( levels.length > 1 ) {
  15517. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  15518. _v2$2.setFromMatrixPosition( this.matrixWorld );
  15519. const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
  15520. levels[ 0 ].object.visible = true;
  15521. let i, l;
  15522. for ( i = 1, l = levels.length; i < l; i ++ ) {
  15523. if ( distance >= levels[ i ].distance ) {
  15524. levels[ i - 1 ].object.visible = false;
  15525. levels[ i ].object.visible = true;
  15526. } else {
  15527. break;
  15528. }
  15529. }
  15530. this._currentLevel = i - 1;
  15531. for ( ; i < l; i ++ ) {
  15532. levels[ i ].object.visible = false;
  15533. }
  15534. }
  15535. },
  15536. toJSON: function ( meta ) {
  15537. const data = Object3D.prototype.toJSON.call( this, meta );
  15538. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  15539. data.object.levels = [];
  15540. const levels = this.levels;
  15541. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  15542. const level = levels[ i ];
  15543. data.object.levels.push( {
  15544. object: level.object.uuid,
  15545. distance: level.distance
  15546. } );
  15547. }
  15548. return data;
  15549. }
  15550. } );
  15551. const _basePosition = new Vector3();
  15552. const _skinIndex = new Vector4();
  15553. const _skinWeight = new Vector4();
  15554. const _vector$7 = new Vector3();
  15555. const _matrix$1 = new Matrix4();
  15556. function SkinnedMesh( geometry, material ) {
  15557. if ( geometry && geometry.isGeometry ) {
  15558. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  15559. }
  15560. Mesh.call( this, geometry, material );
  15561. this.type = 'SkinnedMesh';
  15562. this.bindMode = 'attached';
  15563. this.bindMatrix = new Matrix4();
  15564. this.bindMatrixInverse = new Matrix4();
  15565. }
  15566. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  15567. constructor: SkinnedMesh,
  15568. isSkinnedMesh: true,
  15569. copy: function ( source ) {
  15570. Mesh.prototype.copy.call( this, source );
  15571. this.bindMode = source.bindMode;
  15572. this.bindMatrix.copy( source.bindMatrix );
  15573. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  15574. this.skeleton = source.skeleton;
  15575. return this;
  15576. },
  15577. bind: function ( skeleton, bindMatrix ) {
  15578. this.skeleton = skeleton;
  15579. if ( bindMatrix === undefined ) {
  15580. this.updateMatrixWorld( true );
  15581. this.skeleton.calculateInverses();
  15582. bindMatrix = this.matrixWorld;
  15583. }
  15584. this.bindMatrix.copy( bindMatrix );
  15585. this.bindMatrixInverse.copy( bindMatrix ).invert();
  15586. },
  15587. pose: function () {
  15588. this.skeleton.pose();
  15589. },
  15590. normalizeSkinWeights: function () {
  15591. const vector = new Vector4();
  15592. const skinWeight = this.geometry.attributes.skinWeight;
  15593. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  15594. vector.x = skinWeight.getX( i );
  15595. vector.y = skinWeight.getY( i );
  15596. vector.z = skinWeight.getZ( i );
  15597. vector.w = skinWeight.getW( i );
  15598. const scale = 1.0 / vector.manhattanLength();
  15599. if ( scale !== Infinity ) {
  15600. vector.multiplyScalar( scale );
  15601. } else {
  15602. vector.set( 1, 0, 0, 0 ); // do something reasonable
  15603. }
  15604. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  15605. }
  15606. },
  15607. updateMatrixWorld: function ( force ) {
  15608. Mesh.prototype.updateMatrixWorld.call( this, force );
  15609. if ( this.bindMode === 'attached' ) {
  15610. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  15611. } else if ( this.bindMode === 'detached' ) {
  15612. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  15613. } else {
  15614. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  15615. }
  15616. },
  15617. boneTransform: function ( index, target ) {
  15618. const skeleton = this.skeleton;
  15619. const geometry = this.geometry;
  15620. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  15621. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  15622. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  15623. target.set( 0, 0, 0 );
  15624. for ( let i = 0; i < 4; i ++ ) {
  15625. const weight = _skinWeight.getComponent( i );
  15626. if ( weight !== 0 ) {
  15627. const boneIndex = _skinIndex.getComponent( i );
  15628. _matrix$1.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  15629. target.addScaledVector( _vector$7.copy( _basePosition ).applyMatrix4( _matrix$1 ), weight );
  15630. }
  15631. }
  15632. return target.applyMatrix4( this.bindMatrixInverse );
  15633. }
  15634. } );
  15635. function Bone() {
  15636. Object3D.call( this );
  15637. this.type = 'Bone';
  15638. }
  15639. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  15640. constructor: Bone,
  15641. isBone: true
  15642. } );
  15643. const _offsetMatrix = new Matrix4();
  15644. const _identityMatrix = new Matrix4();
  15645. function Skeleton( bones = [], boneInverses = [] ) {
  15646. this.uuid = MathUtils.generateUUID();
  15647. this.bones = bones.slice( 0 );
  15648. this.boneInverses = boneInverses;
  15649. this.boneMatrices = null;
  15650. this.boneTexture = null;
  15651. this.boneTextureSize = 0;
  15652. this.frame = - 1;
  15653. this.init();
  15654. }
  15655. Object.assign( Skeleton.prototype, {
  15656. init: function () {
  15657. const bones = this.bones;
  15658. const boneInverses = this.boneInverses;
  15659. this.boneMatrices = new Float32Array( bones.length * 16 );
  15660. // calculate inverse bone matrices if necessary
  15661. if ( boneInverses.length === 0 ) {
  15662. this.calculateInverses();
  15663. } else {
  15664. // handle special case
  15665. if ( bones.length !== boneInverses.length ) {
  15666. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  15667. this.boneInverses = [];
  15668. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15669. this.boneInverses.push( new Matrix4() );
  15670. }
  15671. }
  15672. }
  15673. },
  15674. calculateInverses: function () {
  15675. this.boneInverses.length = 0;
  15676. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15677. const inverse = new Matrix4();
  15678. if ( this.bones[ i ] ) {
  15679. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  15680. }
  15681. this.boneInverses.push( inverse );
  15682. }
  15683. },
  15684. pose: function () {
  15685. // recover the bind-time world matrices
  15686. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15687. const bone = this.bones[ i ];
  15688. if ( bone ) {
  15689. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  15690. }
  15691. }
  15692. // compute the local matrices, positions, rotations and scales
  15693. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15694. const bone = this.bones[ i ];
  15695. if ( bone ) {
  15696. if ( bone.parent && bone.parent.isBone ) {
  15697. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  15698. bone.matrix.multiply( bone.matrixWorld );
  15699. } else {
  15700. bone.matrix.copy( bone.matrixWorld );
  15701. }
  15702. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  15703. }
  15704. }
  15705. },
  15706. update: function () {
  15707. const bones = this.bones;
  15708. const boneInverses = this.boneInverses;
  15709. const boneMatrices = this.boneMatrices;
  15710. const boneTexture = this.boneTexture;
  15711. // flatten bone matrices to array
  15712. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  15713. // compute the offset between the current and the original transform
  15714. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  15715. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  15716. _offsetMatrix.toArray( boneMatrices, i * 16 );
  15717. }
  15718. if ( boneTexture !== null ) {
  15719. boneTexture.needsUpdate = true;
  15720. }
  15721. },
  15722. clone: function () {
  15723. return new Skeleton( this.bones, this.boneInverses );
  15724. },
  15725. getBoneByName: function ( name ) {
  15726. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  15727. const bone = this.bones[ i ];
  15728. if ( bone.name === name ) {
  15729. return bone;
  15730. }
  15731. }
  15732. return undefined;
  15733. },
  15734. dispose: function ( ) {
  15735. if ( this.boneTexture !== null ) {
  15736. this.boneTexture.dispose();
  15737. this.boneTexture = null;
  15738. }
  15739. },
  15740. fromJSON: function ( json, bones ) {
  15741. this.uuid = json.uuid;
  15742. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  15743. const uuid = json.bones[ i ];
  15744. let bone = bones[ uuid ];
  15745. if ( bone === undefined ) {
  15746. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  15747. bone = new Bone();
  15748. }
  15749. this.bones.push( bone );
  15750. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  15751. }
  15752. this.init();
  15753. return this;
  15754. },
  15755. toJSON: function () {
  15756. const data = {
  15757. metadata: {
  15758. version: 4.5,
  15759. type: 'Skeleton',
  15760. generator: 'Skeleton.toJSON'
  15761. },
  15762. bones: [],
  15763. boneInverses: []
  15764. };
  15765. data.uuid = this.uuid;
  15766. const bones = this.bones;
  15767. const boneInverses = this.boneInverses;
  15768. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  15769. const bone = bones[ i ];
  15770. data.bones.push( bone.uuid );
  15771. const boneInverse = boneInverses[ i ];
  15772. data.boneInverses.push( boneInverse.toArray() );
  15773. }
  15774. return data;
  15775. }
  15776. } );
  15777. const _instanceLocalMatrix = new Matrix4();
  15778. const _instanceWorldMatrix = new Matrix4();
  15779. const _instanceIntersects = [];
  15780. const _mesh = new Mesh();
  15781. function InstancedMesh( geometry, material, count ) {
  15782. Mesh.call( this, geometry, material );
  15783. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  15784. this.instanceColor = null;
  15785. this.count = count;
  15786. this.frustumCulled = false;
  15787. }
  15788. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  15789. constructor: InstancedMesh,
  15790. isInstancedMesh: true,
  15791. copy: function ( source ) {
  15792. Mesh.prototype.copy.call( this, source );
  15793. this.instanceMatrix.copy( source.instanceMatrix );
  15794. this.count = source.count;
  15795. return this;
  15796. },
  15797. getColorAt: function ( index, color ) {
  15798. color.fromArray( this.instanceColor.array, index * 3 );
  15799. },
  15800. getMatrixAt: function ( index, matrix ) {
  15801. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  15802. },
  15803. raycast: function ( raycaster, intersects ) {
  15804. const matrixWorld = this.matrixWorld;
  15805. const raycastTimes = this.count;
  15806. _mesh.geometry = this.geometry;
  15807. _mesh.material = this.material;
  15808. if ( _mesh.material === undefined ) return;
  15809. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  15810. // calculate the world matrix for each instance
  15811. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  15812. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  15813. // the mesh represents this single instance
  15814. _mesh.matrixWorld = _instanceWorldMatrix;
  15815. _mesh.raycast( raycaster, _instanceIntersects );
  15816. // process the result of raycast
  15817. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  15818. const intersect = _instanceIntersects[ i ];
  15819. intersect.instanceId = instanceId;
  15820. intersect.object = this;
  15821. intersects.push( intersect );
  15822. }
  15823. _instanceIntersects.length = 0;
  15824. }
  15825. },
  15826. setColorAt: function ( index, color ) {
  15827. if ( this.instanceColor === null ) {
  15828. this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 );
  15829. }
  15830. color.toArray( this.instanceColor.array, index * 3 );
  15831. },
  15832. setMatrixAt: function ( index, matrix ) {
  15833. matrix.toArray( this.instanceMatrix.array, index * 16 );
  15834. },
  15835. updateMorphTargets: function () {
  15836. },
  15837. dispose: function () {
  15838. this.dispatchEvent( { type: 'dispose' } );
  15839. }
  15840. } );
  15841. /**
  15842. * parameters = {
  15843. * color: <hex>,
  15844. * opacity: <float>,
  15845. *
  15846. * linewidth: <float>,
  15847. * linecap: "round",
  15848. * linejoin: "round"
  15849. * }
  15850. */
  15851. function LineBasicMaterial( parameters ) {
  15852. Material.call( this );
  15853. this.type = 'LineBasicMaterial';
  15854. this.color = new Color( 0xffffff );
  15855. this.linewidth = 1;
  15856. this.linecap = 'round';
  15857. this.linejoin = 'round';
  15858. this.morphTargets = false;
  15859. this.setValues( parameters );
  15860. }
  15861. LineBasicMaterial.prototype = Object.create( Material.prototype );
  15862. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  15863. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  15864. LineBasicMaterial.prototype.copy = function ( source ) {
  15865. Material.prototype.copy.call( this, source );
  15866. this.color.copy( source.color );
  15867. this.linewidth = source.linewidth;
  15868. this.linecap = source.linecap;
  15869. this.linejoin = source.linejoin;
  15870. this.morphTargets = source.morphTargets;
  15871. return this;
  15872. };
  15873. const _start = new Vector3();
  15874. const _end = new Vector3();
  15875. const _inverseMatrix$1 = new Matrix4();
  15876. const _ray$1 = new Ray();
  15877. const _sphere$2 = new Sphere();
  15878. function Line( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  15879. Object3D.call( this );
  15880. this.type = 'Line';
  15881. this.geometry = geometry;
  15882. this.material = material;
  15883. this.updateMorphTargets();
  15884. }
  15885. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  15886. constructor: Line,
  15887. isLine: true,
  15888. copy: function ( source ) {
  15889. Object3D.prototype.copy.call( this, source );
  15890. this.material = source.material;
  15891. this.geometry = source.geometry;
  15892. return this;
  15893. },
  15894. computeLineDistances: function () {
  15895. const geometry = this.geometry;
  15896. if ( geometry.isBufferGeometry ) {
  15897. // we assume non-indexed geometry
  15898. if ( geometry.index === null ) {
  15899. const positionAttribute = geometry.attributes.position;
  15900. const lineDistances = [ 0 ];
  15901. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  15902. _start.fromBufferAttribute( positionAttribute, i - 1 );
  15903. _end.fromBufferAttribute( positionAttribute, i );
  15904. lineDistances[ i ] = lineDistances[ i - 1 ];
  15905. lineDistances[ i ] += _start.distanceTo( _end );
  15906. }
  15907. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  15908. } else {
  15909. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  15910. }
  15911. } else if ( geometry.isGeometry ) {
  15912. const vertices = geometry.vertices;
  15913. const lineDistances = geometry.lineDistances;
  15914. lineDistances[ 0 ] = 0;
  15915. for ( let i = 1, l = vertices.length; i < l; i ++ ) {
  15916. lineDistances[ i ] = lineDistances[ i - 1 ];
  15917. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  15918. }
  15919. }
  15920. return this;
  15921. },
  15922. raycast: function ( raycaster, intersects ) {
  15923. const geometry = this.geometry;
  15924. const matrixWorld = this.matrixWorld;
  15925. const threshold = raycaster.params.Line.threshold;
  15926. // Checking boundingSphere distance to ray
  15927. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15928. _sphere$2.copy( geometry.boundingSphere );
  15929. _sphere$2.applyMatrix4( matrixWorld );
  15930. _sphere$2.radius += threshold;
  15931. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  15932. //
  15933. _inverseMatrix$1.copy( matrixWorld ).invert();
  15934. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  15935. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  15936. const localThresholdSq = localThreshold * localThreshold;
  15937. const vStart = new Vector3();
  15938. const vEnd = new Vector3();
  15939. const interSegment = new Vector3();
  15940. const interRay = new Vector3();
  15941. const step = this.isLineSegments ? 2 : 1;
  15942. if ( geometry.isBufferGeometry ) {
  15943. const index = geometry.index;
  15944. const attributes = geometry.attributes;
  15945. const positionAttribute = attributes.position;
  15946. if ( index !== null ) {
  15947. const indices = index.array;
  15948. for ( let i = 0, l = indices.length - 1; i < l; i += step ) {
  15949. const a = indices[ i ];
  15950. const b = indices[ i + 1 ];
  15951. vStart.fromBufferAttribute( positionAttribute, a );
  15952. vEnd.fromBufferAttribute( positionAttribute, b );
  15953. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  15954. if ( distSq > localThresholdSq ) continue;
  15955. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  15956. const distance = raycaster.ray.origin.distanceTo( interRay );
  15957. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  15958. intersects.push( {
  15959. distance: distance,
  15960. // What do we want? intersection point on the ray or on the segment??
  15961. // point: raycaster.ray.at( distance ),
  15962. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  15963. index: i,
  15964. face: null,
  15965. faceIndex: null,
  15966. object: this
  15967. } );
  15968. }
  15969. } else {
  15970. for ( let i = 0, l = positionAttribute.count - 1; i < l; i += step ) {
  15971. vStart.fromBufferAttribute( positionAttribute, i );
  15972. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  15973. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  15974. if ( distSq > localThresholdSq ) continue;
  15975. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  15976. const distance = raycaster.ray.origin.distanceTo( interRay );
  15977. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  15978. intersects.push( {
  15979. distance: distance,
  15980. // What do we want? intersection point on the ray or on the segment??
  15981. // point: raycaster.ray.at( distance ),
  15982. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  15983. index: i,
  15984. face: null,
  15985. faceIndex: null,
  15986. object: this
  15987. } );
  15988. }
  15989. }
  15990. } else if ( geometry.isGeometry ) {
  15991. const vertices = geometry.vertices;
  15992. const nbVertices = vertices.length;
  15993. for ( let i = 0; i < nbVertices - 1; i += step ) {
  15994. const distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  15995. if ( distSq > localThresholdSq ) continue;
  15996. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  15997. const distance = raycaster.ray.origin.distanceTo( interRay );
  15998. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  15999. intersects.push( {
  16000. distance: distance,
  16001. // What do we want? intersection point on the ray or on the segment??
  16002. // point: raycaster.ray.at( distance ),
  16003. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16004. index: i,
  16005. face: null,
  16006. faceIndex: null,
  16007. object: this
  16008. } );
  16009. }
  16010. }
  16011. },
  16012. updateMorphTargets: function () {
  16013. const geometry = this.geometry;
  16014. if ( geometry.isBufferGeometry ) {
  16015. const morphAttributes = geometry.morphAttributes;
  16016. const keys = Object.keys( morphAttributes );
  16017. if ( keys.length > 0 ) {
  16018. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16019. if ( morphAttribute !== undefined ) {
  16020. this.morphTargetInfluences = [];
  16021. this.morphTargetDictionary = {};
  16022. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16023. const name = morphAttribute[ m ].name || String( m );
  16024. this.morphTargetInfluences.push( 0 );
  16025. this.morphTargetDictionary[ name ] = m;
  16026. }
  16027. }
  16028. }
  16029. } else {
  16030. const morphTargets = geometry.morphTargets;
  16031. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16032. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16033. }
  16034. }
  16035. }
  16036. } );
  16037. const _start$1 = new Vector3();
  16038. const _end$1 = new Vector3();
  16039. function LineSegments( geometry, material ) {
  16040. Line.call( this, geometry, material );
  16041. this.type = 'LineSegments';
  16042. }
  16043. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  16044. constructor: LineSegments,
  16045. isLineSegments: true,
  16046. computeLineDistances: function () {
  16047. const geometry = this.geometry;
  16048. if ( geometry.isBufferGeometry ) {
  16049. // we assume non-indexed geometry
  16050. if ( geometry.index === null ) {
  16051. const positionAttribute = geometry.attributes.position;
  16052. const lineDistances = [];
  16053. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  16054. _start$1.fromBufferAttribute( positionAttribute, i );
  16055. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  16056. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16057. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16058. }
  16059. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16060. } else {
  16061. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16062. }
  16063. } else if ( geometry.isGeometry ) {
  16064. const vertices = geometry.vertices;
  16065. const lineDistances = geometry.lineDistances;
  16066. for ( let i = 0, l = vertices.length; i < l; i += 2 ) {
  16067. _start$1.copy( vertices[ i ] );
  16068. _end$1.copy( vertices[ i + 1 ] );
  16069. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16070. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16071. }
  16072. }
  16073. return this;
  16074. }
  16075. } );
  16076. function LineLoop( geometry, material ) {
  16077. Line.call( this, geometry, material );
  16078. this.type = 'LineLoop';
  16079. }
  16080. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  16081. constructor: LineLoop,
  16082. isLineLoop: true,
  16083. } );
  16084. /**
  16085. * parameters = {
  16086. * color: <hex>,
  16087. * opacity: <float>,
  16088. * map: new THREE.Texture( <Image> ),
  16089. * alphaMap: new THREE.Texture( <Image> ),
  16090. *
  16091. * size: <float>,
  16092. * sizeAttenuation: <bool>
  16093. *
  16094. * morphTargets: <bool>
  16095. * }
  16096. */
  16097. function PointsMaterial( parameters ) {
  16098. Material.call( this );
  16099. this.type = 'PointsMaterial';
  16100. this.color = new Color( 0xffffff );
  16101. this.map = null;
  16102. this.alphaMap = null;
  16103. this.size = 1;
  16104. this.sizeAttenuation = true;
  16105. this.morphTargets = false;
  16106. this.setValues( parameters );
  16107. }
  16108. PointsMaterial.prototype = Object.create( Material.prototype );
  16109. PointsMaterial.prototype.constructor = PointsMaterial;
  16110. PointsMaterial.prototype.isPointsMaterial = true;
  16111. PointsMaterial.prototype.copy = function ( source ) {
  16112. Material.prototype.copy.call( this, source );
  16113. this.color.copy( source.color );
  16114. this.map = source.map;
  16115. this.alphaMap = source.alphaMap;
  16116. this.size = source.size;
  16117. this.sizeAttenuation = source.sizeAttenuation;
  16118. this.morphTargets = source.morphTargets;
  16119. return this;
  16120. };
  16121. const _inverseMatrix$2 = new Matrix4();
  16122. const _ray$2 = new Ray();
  16123. const _sphere$3 = new Sphere();
  16124. const _position$1 = new Vector3();
  16125. function Points( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  16126. Object3D.call( this );
  16127. this.type = 'Points';
  16128. this.geometry = geometry;
  16129. this.material = material;
  16130. this.updateMorphTargets();
  16131. }
  16132. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16133. constructor: Points,
  16134. isPoints: true,
  16135. copy: function ( source ) {
  16136. Object3D.prototype.copy.call( this, source );
  16137. this.material = source.material;
  16138. this.geometry = source.geometry;
  16139. return this;
  16140. },
  16141. raycast: function ( raycaster, intersects ) {
  16142. const geometry = this.geometry;
  16143. const matrixWorld = this.matrixWorld;
  16144. const threshold = raycaster.params.Points.threshold;
  16145. // Checking boundingSphere distance to ray
  16146. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16147. _sphere$3.copy( geometry.boundingSphere );
  16148. _sphere$3.applyMatrix4( matrixWorld );
  16149. _sphere$3.radius += threshold;
  16150. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  16151. //
  16152. _inverseMatrix$2.copy( matrixWorld ).invert();
  16153. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  16154. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16155. const localThresholdSq = localThreshold * localThreshold;
  16156. if ( geometry.isBufferGeometry ) {
  16157. const index = geometry.index;
  16158. const attributes = geometry.attributes;
  16159. const positionAttribute = attributes.position;
  16160. if ( index !== null ) {
  16161. const indices = index.array;
  16162. for ( let i = 0, il = indices.length; i < il; i ++ ) {
  16163. const a = indices[ i ];
  16164. _position$1.fromBufferAttribute( positionAttribute, a );
  16165. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16166. }
  16167. } else {
  16168. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  16169. _position$1.fromBufferAttribute( positionAttribute, i );
  16170. testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16171. }
  16172. }
  16173. } else {
  16174. const vertices = geometry.vertices;
  16175. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  16176. testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16177. }
  16178. }
  16179. },
  16180. updateMorphTargets: function () {
  16181. const geometry = this.geometry;
  16182. if ( geometry.isBufferGeometry ) {
  16183. const morphAttributes = geometry.morphAttributes;
  16184. const keys = Object.keys( morphAttributes );
  16185. if ( keys.length > 0 ) {
  16186. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16187. if ( morphAttribute !== undefined ) {
  16188. this.morphTargetInfluences = [];
  16189. this.morphTargetDictionary = {};
  16190. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16191. const name = morphAttribute[ m ].name || String( m );
  16192. this.morphTargetInfluences.push( 0 );
  16193. this.morphTargetDictionary[ name ] = m;
  16194. }
  16195. }
  16196. }
  16197. } else {
  16198. const morphTargets = geometry.morphTargets;
  16199. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16200. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16201. }
  16202. }
  16203. }
  16204. } );
  16205. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16206. const rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  16207. if ( rayPointDistanceSq < localThresholdSq ) {
  16208. const intersectPoint = new Vector3();
  16209. _ray$2.closestPointToPoint( point, intersectPoint );
  16210. intersectPoint.applyMatrix4( matrixWorld );
  16211. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16212. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16213. intersects.push( {
  16214. distance: distance,
  16215. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16216. point: intersectPoint,
  16217. index: index,
  16218. face: null,
  16219. object: object
  16220. } );
  16221. }
  16222. }
  16223. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16224. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16225. this.format = format !== undefined ? format : RGBFormat;
  16226. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16227. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16228. this.generateMipmaps = false;
  16229. const scope = this;
  16230. function updateVideo() {
  16231. scope.needsUpdate = true;
  16232. video.requestVideoFrameCallback( updateVideo );
  16233. }
  16234. if ( 'requestVideoFrameCallback' in video ) {
  16235. video.requestVideoFrameCallback( updateVideo );
  16236. }
  16237. }
  16238. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  16239. constructor: VideoTexture,
  16240. clone: function () {
  16241. return new this.constructor( this.image ).copy( this );
  16242. },
  16243. isVideoTexture: true,
  16244. update: function () {
  16245. const video = this.image;
  16246. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16247. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16248. this.needsUpdate = true;
  16249. }
  16250. }
  16251. } );
  16252. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  16253. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16254. this.image = { width: width, height: height };
  16255. this.mipmaps = mipmaps;
  16256. // no flipping for cube textures
  16257. // (also flipping doesn't work for compressed textures )
  16258. this.flipY = false;
  16259. // can't generate mipmaps for compressed textures
  16260. // mips must be embedded in DDS files
  16261. this.generateMipmaps = false;
  16262. }
  16263. CompressedTexture.prototype = Object.create( Texture.prototype );
  16264. CompressedTexture.prototype.constructor = CompressedTexture;
  16265. CompressedTexture.prototype.isCompressedTexture = true;
  16266. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16267. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16268. this.needsUpdate = true;
  16269. }
  16270. CanvasTexture.prototype = Object.create( Texture.prototype );
  16271. CanvasTexture.prototype.constructor = CanvasTexture;
  16272. CanvasTexture.prototype.isCanvasTexture = true;
  16273. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  16274. format = format !== undefined ? format : DepthFormat;
  16275. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  16276. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  16277. }
  16278. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  16279. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type$1;
  16280. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16281. this.image = { width: width, height: height };
  16282. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16283. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16284. this.flipY = false;
  16285. this.generateMipmaps = false;
  16286. }
  16287. DepthTexture.prototype = Object.create( Texture.prototype );
  16288. DepthTexture.prototype.constructor = DepthTexture;
  16289. DepthTexture.prototype.isDepthTexture = true;
  16290. let _geometryId = 0; // Geometry uses even numbers as Id
  16291. const _m1$3 = new Matrix4();
  16292. const _obj$1 = new Object3D();
  16293. const _offset$1 = new Vector3();
  16294. function Geometry() {
  16295. Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
  16296. this.uuid = MathUtils.generateUUID();
  16297. this.name = '';
  16298. this.type = 'Geometry';
  16299. this.vertices = [];
  16300. this.colors = [];
  16301. this.faces = [];
  16302. this.faceVertexUvs = [[]];
  16303. this.morphTargets = [];
  16304. this.morphNormals = [];
  16305. this.skinWeights = [];
  16306. this.skinIndices = [];
  16307. this.lineDistances = [];
  16308. this.boundingBox = null;
  16309. this.boundingSphere = null;
  16310. // update flags
  16311. this.elementsNeedUpdate = false;
  16312. this.verticesNeedUpdate = false;
  16313. this.uvsNeedUpdate = false;
  16314. this.normalsNeedUpdate = false;
  16315. this.colorsNeedUpdate = false;
  16316. this.lineDistancesNeedUpdate = false;
  16317. this.groupsNeedUpdate = false;
  16318. }
  16319. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  16320. constructor: Geometry,
  16321. isGeometry: true,
  16322. applyMatrix4: function ( matrix ) {
  16323. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  16324. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  16325. const vertex = this.vertices[ i ];
  16326. vertex.applyMatrix4( matrix );
  16327. }
  16328. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  16329. const face = this.faces[ i ];
  16330. face.normal.applyMatrix3( normalMatrix ).normalize();
  16331. for ( let j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  16332. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  16333. }
  16334. }
  16335. if ( this.boundingBox !== null ) {
  16336. this.computeBoundingBox();
  16337. }
  16338. if ( this.boundingSphere !== null ) {
  16339. this.computeBoundingSphere();
  16340. }
  16341. this.verticesNeedUpdate = true;
  16342. this.normalsNeedUpdate = true;
  16343. return this;
  16344. },
  16345. rotateX: function ( angle ) {
  16346. // rotate geometry around world x-axis
  16347. _m1$3.makeRotationX( angle );
  16348. this.applyMatrix4( _m1$3 );
  16349. return this;
  16350. },
  16351. rotateY: function ( angle ) {
  16352. // rotate geometry around world y-axis
  16353. _m1$3.makeRotationY( angle );
  16354. this.applyMatrix4( _m1$3 );
  16355. return this;
  16356. },
  16357. rotateZ: function ( angle ) {
  16358. // rotate geometry around world z-axis
  16359. _m1$3.makeRotationZ( angle );
  16360. this.applyMatrix4( _m1$3 );
  16361. return this;
  16362. },
  16363. translate: function ( x, y, z ) {
  16364. // translate geometry
  16365. _m1$3.makeTranslation( x, y, z );
  16366. this.applyMatrix4( _m1$3 );
  16367. return this;
  16368. },
  16369. scale: function ( x, y, z ) {
  16370. // scale geometry
  16371. _m1$3.makeScale( x, y, z );
  16372. this.applyMatrix4( _m1$3 );
  16373. return this;
  16374. },
  16375. lookAt: function ( vector ) {
  16376. _obj$1.lookAt( vector );
  16377. _obj$1.updateMatrix();
  16378. this.applyMatrix4( _obj$1.matrix );
  16379. return this;
  16380. },
  16381. fromBufferGeometry: function ( geometry ) {
  16382. const scope = this;
  16383. const index = geometry.index !== null ? geometry.index : undefined;
  16384. const attributes = geometry.attributes;
  16385. if ( attributes.position === undefined ) {
  16386. console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
  16387. return this;
  16388. }
  16389. const position = attributes.position;
  16390. const normal = attributes.normal;
  16391. const color = attributes.color;
  16392. const uv = attributes.uv;
  16393. const uv2 = attributes.uv2;
  16394. if ( uv2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  16395. for ( let i = 0; i < position.count; i ++ ) {
  16396. scope.vertices.push( new Vector3().fromBufferAttribute( position, i ) );
  16397. if ( color !== undefined ) {
  16398. scope.colors.push( new Color().fromBufferAttribute( color, i ) );
  16399. }
  16400. }
  16401. function addFace( a, b, c, materialIndex ) {
  16402. const vertexColors = ( color === undefined ) ? [] : [
  16403. scope.colors[ a ].clone(),
  16404. scope.colors[ b ].clone(),
  16405. scope.colors[ c ].clone()
  16406. ];
  16407. const vertexNormals = ( normal === undefined ) ? [] : [
  16408. new Vector3().fromBufferAttribute( normal, a ),
  16409. new Vector3().fromBufferAttribute( normal, b ),
  16410. new Vector3().fromBufferAttribute( normal, c )
  16411. ];
  16412. const face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  16413. scope.faces.push( face );
  16414. if ( uv !== undefined ) {
  16415. scope.faceVertexUvs[ 0 ].push( [
  16416. new Vector2().fromBufferAttribute( uv, a ),
  16417. new Vector2().fromBufferAttribute( uv, b ),
  16418. new Vector2().fromBufferAttribute( uv, c )
  16419. ] );
  16420. }
  16421. if ( uv2 !== undefined ) {
  16422. scope.faceVertexUvs[ 1 ].push( [
  16423. new Vector2().fromBufferAttribute( uv2, a ),
  16424. new Vector2().fromBufferAttribute( uv2, b ),
  16425. new Vector2().fromBufferAttribute( uv2, c )
  16426. ] );
  16427. }
  16428. }
  16429. const groups = geometry.groups;
  16430. if ( groups.length > 0 ) {
  16431. for ( let i = 0; i < groups.length; i ++ ) {
  16432. const group = groups[ i ];
  16433. const start = group.start;
  16434. const count = group.count;
  16435. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  16436. if ( index !== undefined ) {
  16437. addFace( index.getX( j ), index.getX( j + 1 ), index.getX( j + 2 ), group.materialIndex );
  16438. } else {
  16439. addFace( j, j + 1, j + 2, group.materialIndex );
  16440. }
  16441. }
  16442. }
  16443. } else {
  16444. if ( index !== undefined ) {
  16445. for ( let i = 0; i < index.count; i += 3 ) {
  16446. addFace( index.getX( i ), index.getX( i + 1 ), index.getX( i + 2 ) );
  16447. }
  16448. } else {
  16449. for ( let i = 0; i < position.count; i += 3 ) {
  16450. addFace( i, i + 1, i + 2 );
  16451. }
  16452. }
  16453. }
  16454. this.computeFaceNormals();
  16455. if ( geometry.boundingBox !== null ) {
  16456. this.boundingBox = geometry.boundingBox.clone();
  16457. }
  16458. if ( geometry.boundingSphere !== null ) {
  16459. this.boundingSphere = geometry.boundingSphere.clone();
  16460. }
  16461. return this;
  16462. },
  16463. center: function () {
  16464. this.computeBoundingBox();
  16465. this.boundingBox.getCenter( _offset$1 ).negate();
  16466. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  16467. return this;
  16468. },
  16469. normalize: function () {
  16470. this.computeBoundingSphere();
  16471. const center = this.boundingSphere.center;
  16472. const radius = this.boundingSphere.radius;
  16473. const s = radius === 0 ? 1 : 1.0 / radius;
  16474. const matrix = new Matrix4();
  16475. matrix.set(
  16476. s, 0, 0, - s * center.x,
  16477. 0, s, 0, - s * center.y,
  16478. 0, 0, s, - s * center.z,
  16479. 0, 0, 0, 1
  16480. );
  16481. this.applyMatrix4( matrix );
  16482. return this;
  16483. },
  16484. computeFaceNormals: function () {
  16485. const cb = new Vector3(), ab = new Vector3();
  16486. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16487. const face = this.faces[ f ];
  16488. const vA = this.vertices[ face.a ];
  16489. const vB = this.vertices[ face.b ];
  16490. const vC = this.vertices[ face.c ];
  16491. cb.subVectors( vC, vB );
  16492. ab.subVectors( vA, vB );
  16493. cb.cross( ab );
  16494. cb.normalize();
  16495. face.normal.copy( cb );
  16496. }
  16497. },
  16498. computeVertexNormals: function ( areaWeighted = true ) {
  16499. const vertices = new Array( this.vertices.length );
  16500. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  16501. vertices[ v ] = new Vector3();
  16502. }
  16503. if ( areaWeighted ) {
  16504. // vertex normals weighted by triangle areas
  16505. // http://www.iquilezles.org/www/articles/normals/normals.htm
  16506. const cb = new Vector3(), ab = new Vector3();
  16507. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16508. const face = this.faces[ f ];
  16509. const vA = this.vertices[ face.a ];
  16510. const vB = this.vertices[ face.b ];
  16511. const vC = this.vertices[ face.c ];
  16512. cb.subVectors( vC, vB );
  16513. ab.subVectors( vA, vB );
  16514. cb.cross( ab );
  16515. vertices[ face.a ].add( cb );
  16516. vertices[ face.b ].add( cb );
  16517. vertices[ face.c ].add( cb );
  16518. }
  16519. } else {
  16520. this.computeFaceNormals();
  16521. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16522. const face = this.faces[ f ];
  16523. vertices[ face.a ].add( face.normal );
  16524. vertices[ face.b ].add( face.normal );
  16525. vertices[ face.c ].add( face.normal );
  16526. }
  16527. }
  16528. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  16529. vertices[ v ].normalize();
  16530. }
  16531. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16532. const face = this.faces[ f ];
  16533. const vertexNormals = face.vertexNormals;
  16534. if ( vertexNormals.length === 3 ) {
  16535. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  16536. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  16537. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  16538. } else {
  16539. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  16540. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  16541. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  16542. }
  16543. }
  16544. if ( this.faces.length > 0 ) {
  16545. this.normalsNeedUpdate = true;
  16546. }
  16547. },
  16548. computeFlatVertexNormals: function () {
  16549. this.computeFaceNormals();
  16550. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16551. const face = this.faces[ f ];
  16552. const vertexNormals = face.vertexNormals;
  16553. if ( vertexNormals.length === 3 ) {
  16554. vertexNormals[ 0 ].copy( face.normal );
  16555. vertexNormals[ 1 ].copy( face.normal );
  16556. vertexNormals[ 2 ].copy( face.normal );
  16557. } else {
  16558. vertexNormals[ 0 ] = face.normal.clone();
  16559. vertexNormals[ 1 ] = face.normal.clone();
  16560. vertexNormals[ 2 ] = face.normal.clone();
  16561. }
  16562. }
  16563. if ( this.faces.length > 0 ) {
  16564. this.normalsNeedUpdate = true;
  16565. }
  16566. },
  16567. computeMorphNormals: function () {
  16568. // save original normals
  16569. // - create temp variables on first access
  16570. // otherwise just copy (for faster repeated calls)
  16571. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16572. const face = this.faces[ f ];
  16573. if ( ! face.__originalFaceNormal ) {
  16574. face.__originalFaceNormal = face.normal.clone();
  16575. } else {
  16576. face.__originalFaceNormal.copy( face.normal );
  16577. }
  16578. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  16579. for ( let i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  16580. if ( ! face.__originalVertexNormals[ i ] ) {
  16581. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  16582. } else {
  16583. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  16584. }
  16585. }
  16586. }
  16587. // use temp geometry to compute face and vertex normals for each morph
  16588. const tmpGeo = new Geometry();
  16589. tmpGeo.faces = this.faces;
  16590. for ( let i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  16591. // create on first access
  16592. if ( ! this.morphNormals[ i ] ) {
  16593. this.morphNormals[ i ] = {};
  16594. this.morphNormals[ i ].faceNormals = [];
  16595. this.morphNormals[ i ].vertexNormals = [];
  16596. const dstNormalsFace = this.morphNormals[ i ].faceNormals;
  16597. const dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  16598. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16599. const faceNormal = new Vector3();
  16600. const vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  16601. dstNormalsFace.push( faceNormal );
  16602. dstNormalsVertex.push( vertexNormals );
  16603. }
  16604. }
  16605. const morphNormals = this.morphNormals[ i ];
  16606. // set vertices to morph target
  16607. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  16608. // compute morph normals
  16609. tmpGeo.computeFaceNormals();
  16610. tmpGeo.computeVertexNormals();
  16611. // store morph normals
  16612. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16613. const face = this.faces[ f ];
  16614. const faceNormal = morphNormals.faceNormals[ f ];
  16615. const vertexNormals = morphNormals.vertexNormals[ f ];
  16616. faceNormal.copy( face.normal );
  16617. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  16618. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  16619. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  16620. }
  16621. }
  16622. // restore original normals
  16623. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  16624. const face = this.faces[ f ];
  16625. face.normal = face.__originalFaceNormal;
  16626. face.vertexNormals = face.__originalVertexNormals;
  16627. }
  16628. },
  16629. computeBoundingBox: function () {
  16630. if ( this.boundingBox === null ) {
  16631. this.boundingBox = new Box3();
  16632. }
  16633. this.boundingBox.setFromPoints( this.vertices );
  16634. },
  16635. computeBoundingSphere: function () {
  16636. if ( this.boundingSphere === null ) {
  16637. this.boundingSphere = new Sphere();
  16638. }
  16639. this.boundingSphere.setFromPoints( this.vertices );
  16640. },
  16641. merge: function ( geometry, matrix, materialIndexOffset = 0 ) {
  16642. if ( ! ( geometry && geometry.isGeometry ) ) {
  16643. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  16644. return;
  16645. }
  16646. let normalMatrix;
  16647. const vertexOffset = this.vertices.length,
  16648. vertices1 = this.vertices,
  16649. vertices2 = geometry.vertices,
  16650. faces1 = this.faces,
  16651. faces2 = geometry.faces,
  16652. colors1 = this.colors,
  16653. colors2 = geometry.colors;
  16654. if ( matrix !== undefined ) {
  16655. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  16656. }
  16657. // vertices
  16658. for ( let i = 0, il = vertices2.length; i < il; i ++ ) {
  16659. const vertex = vertices2[ i ];
  16660. const vertexCopy = vertex.clone();
  16661. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  16662. vertices1.push( vertexCopy );
  16663. }
  16664. // colors
  16665. for ( let i = 0, il = colors2.length; i < il; i ++ ) {
  16666. colors1.push( colors2[ i ].clone() );
  16667. }
  16668. // faces
  16669. for ( let i = 0, il = faces2.length; i < il; i ++ ) {
  16670. const face = faces2[ i ];
  16671. let normal, color;
  16672. const faceVertexNormals = face.vertexNormals,
  16673. faceVertexColors = face.vertexColors;
  16674. const faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  16675. faceCopy.normal.copy( face.normal );
  16676. if ( normalMatrix !== undefined ) {
  16677. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  16678. }
  16679. for ( let j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  16680. normal = faceVertexNormals[ j ].clone();
  16681. if ( normalMatrix !== undefined ) {
  16682. normal.applyMatrix3( normalMatrix ).normalize();
  16683. }
  16684. faceCopy.vertexNormals.push( normal );
  16685. }
  16686. faceCopy.color.copy( face.color );
  16687. for ( let j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  16688. color = faceVertexColors[ j ];
  16689. faceCopy.vertexColors.push( color.clone() );
  16690. }
  16691. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  16692. faces1.push( faceCopy );
  16693. }
  16694. // uvs
  16695. for ( let i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16696. const faceVertexUvs2 = geometry.faceVertexUvs[ i ];
  16697. if ( this.faceVertexUvs[ i ] === undefined ) this.faceVertexUvs[ i ] = [];
  16698. for ( let j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {
  16699. const uvs2 = faceVertexUvs2[ j ], uvsCopy = [];
  16700. for ( let k = 0, kl = uvs2.length; k < kl; k ++ ) {
  16701. uvsCopy.push( uvs2[ k ].clone() );
  16702. }
  16703. this.faceVertexUvs[ i ].push( uvsCopy );
  16704. }
  16705. }
  16706. },
  16707. mergeMesh: function ( mesh ) {
  16708. if ( ! ( mesh && mesh.isMesh ) ) {
  16709. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  16710. return;
  16711. }
  16712. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  16713. this.merge( mesh.geometry, mesh.matrix );
  16714. },
  16715. /*
  16716. * Checks for duplicate vertices with hashmap.
  16717. * Duplicated vertices are removed
  16718. * and faces' vertices are updated.
  16719. */
  16720. mergeVertices: function ( precisionPoints = 4 ) {
  16721. const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  16722. const unique = [], changes = [];
  16723. const precision = Math.pow( 10, precisionPoints );
  16724. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  16725. const v = this.vertices[ i ];
  16726. const key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  16727. if ( verticesMap[ key ] === undefined ) {
  16728. verticesMap[ key ] = i;
  16729. unique.push( this.vertices[ i ] );
  16730. changes[ i ] = unique.length - 1;
  16731. } else {
  16732. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  16733. changes[ i ] = changes[ verticesMap[ key ] ];
  16734. }
  16735. }
  16736. // if faces are completely degenerate after merging vertices, we
  16737. // have to remove them from the geometry.
  16738. const faceIndicesToRemove = [];
  16739. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  16740. const face = this.faces[ i ];
  16741. face.a = changes[ face.a ];
  16742. face.b = changes[ face.b ];
  16743. face.c = changes[ face.c ];
  16744. const indices = [ face.a, face.b, face.c ];
  16745. // if any duplicate vertices are found in a Face3
  16746. // we have to remove the face as nothing can be saved
  16747. for ( let n = 0; n < 3; n ++ ) {
  16748. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  16749. faceIndicesToRemove.push( i );
  16750. break;
  16751. }
  16752. }
  16753. }
  16754. for ( let i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  16755. const idx = faceIndicesToRemove[ i ];
  16756. this.faces.splice( idx, 1 );
  16757. for ( let j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  16758. this.faceVertexUvs[ j ].splice( idx, 1 );
  16759. }
  16760. }
  16761. // Use unique set of vertices
  16762. const diff = this.vertices.length - unique.length;
  16763. this.vertices = unique;
  16764. return diff;
  16765. },
  16766. setFromPoints: function ( points ) {
  16767. this.vertices = [];
  16768. for ( let i = 0, l = points.length; i < l; i ++ ) {
  16769. const point = points[ i ];
  16770. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  16771. }
  16772. return this;
  16773. },
  16774. sortFacesByMaterialIndex: function () {
  16775. const faces = this.faces;
  16776. const length = faces.length;
  16777. // tag faces
  16778. for ( let i = 0; i < length; i ++ ) {
  16779. faces[ i ]._id = i;
  16780. }
  16781. // sort faces
  16782. function materialIndexSort( a, b ) {
  16783. return a.materialIndex - b.materialIndex;
  16784. }
  16785. faces.sort( materialIndexSort );
  16786. // sort uvs
  16787. const uvs1 = this.faceVertexUvs[ 0 ];
  16788. const uvs2 = this.faceVertexUvs[ 1 ];
  16789. let newUvs1, newUvs2;
  16790. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  16791. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  16792. for ( let i = 0; i < length; i ++ ) {
  16793. const id = faces[ i ]._id;
  16794. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  16795. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  16796. }
  16797. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  16798. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  16799. },
  16800. toJSON: function () {
  16801. const data = {
  16802. metadata: {
  16803. version: 4.5,
  16804. type: 'Geometry',
  16805. generator: 'Geometry.toJSON'
  16806. }
  16807. };
  16808. // standard Geometry serialization
  16809. data.uuid = this.uuid;
  16810. data.type = this.type;
  16811. if ( this.name !== '' ) data.name = this.name;
  16812. if ( this.parameters !== undefined ) {
  16813. const parameters = this.parameters;
  16814. for ( const key in parameters ) {
  16815. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  16816. }
  16817. return data;
  16818. }
  16819. const vertices = [];
  16820. for ( let i = 0; i < this.vertices.length; i ++ ) {
  16821. const vertex = this.vertices[ i ];
  16822. vertices.push( vertex.x, vertex.y, vertex.z );
  16823. }
  16824. const faces = [];
  16825. const normals = [];
  16826. const normalsHash = {};
  16827. const colors = [];
  16828. const colorsHash = {};
  16829. const uvs = [];
  16830. const uvsHash = {};
  16831. for ( let i = 0; i < this.faces.length; i ++ ) {
  16832. const face = this.faces[ i ];
  16833. const hasMaterial = true;
  16834. const hasFaceUv = false; // deprecated
  16835. const hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  16836. const hasFaceNormal = face.normal.length() > 0;
  16837. const hasFaceVertexNormal = face.vertexNormals.length > 0;
  16838. const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  16839. const hasFaceVertexColor = face.vertexColors.length > 0;
  16840. let faceType = 0;
  16841. faceType = setBit( faceType, 0, 0 ); // isQuad
  16842. faceType = setBit( faceType, 1, hasMaterial );
  16843. faceType = setBit( faceType, 2, hasFaceUv );
  16844. faceType = setBit( faceType, 3, hasFaceVertexUv );
  16845. faceType = setBit( faceType, 4, hasFaceNormal );
  16846. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  16847. faceType = setBit( faceType, 6, hasFaceColor );
  16848. faceType = setBit( faceType, 7, hasFaceVertexColor );
  16849. faces.push( faceType );
  16850. faces.push( face.a, face.b, face.c );
  16851. faces.push( face.materialIndex );
  16852. if ( hasFaceVertexUv ) {
  16853. const faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  16854. faces.push(
  16855. getUvIndex( faceVertexUvs[ 0 ] ),
  16856. getUvIndex( faceVertexUvs[ 1 ] ),
  16857. getUvIndex( faceVertexUvs[ 2 ] )
  16858. );
  16859. }
  16860. if ( hasFaceNormal ) {
  16861. faces.push( getNormalIndex( face.normal ) );
  16862. }
  16863. if ( hasFaceVertexNormal ) {
  16864. const vertexNormals = face.vertexNormals;
  16865. faces.push(
  16866. getNormalIndex( vertexNormals[ 0 ] ),
  16867. getNormalIndex( vertexNormals[ 1 ] ),
  16868. getNormalIndex( vertexNormals[ 2 ] )
  16869. );
  16870. }
  16871. if ( hasFaceColor ) {
  16872. faces.push( getColorIndex( face.color ) );
  16873. }
  16874. if ( hasFaceVertexColor ) {
  16875. const vertexColors = face.vertexColors;
  16876. faces.push(
  16877. getColorIndex( vertexColors[ 0 ] ),
  16878. getColorIndex( vertexColors[ 1 ] ),
  16879. getColorIndex( vertexColors[ 2 ] )
  16880. );
  16881. }
  16882. }
  16883. function setBit( value, position, enabled ) {
  16884. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  16885. }
  16886. function getNormalIndex( normal ) {
  16887. const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  16888. if ( normalsHash[ hash ] !== undefined ) {
  16889. return normalsHash[ hash ];
  16890. }
  16891. normalsHash[ hash ] = normals.length / 3;
  16892. normals.push( normal.x, normal.y, normal.z );
  16893. return normalsHash[ hash ];
  16894. }
  16895. function getColorIndex( color ) {
  16896. const hash = color.r.toString() + color.g.toString() + color.b.toString();
  16897. if ( colorsHash[ hash ] !== undefined ) {
  16898. return colorsHash[ hash ];
  16899. }
  16900. colorsHash[ hash ] = colors.length;
  16901. colors.push( color.getHex() );
  16902. return colorsHash[ hash ];
  16903. }
  16904. function getUvIndex( uv ) {
  16905. const hash = uv.x.toString() + uv.y.toString();
  16906. if ( uvsHash[ hash ] !== undefined ) {
  16907. return uvsHash[ hash ];
  16908. }
  16909. uvsHash[ hash ] = uvs.length / 2;
  16910. uvs.push( uv.x, uv.y );
  16911. return uvsHash[ hash ];
  16912. }
  16913. data.data = {};
  16914. data.data.vertices = vertices;
  16915. data.data.normals = normals;
  16916. if ( colors.length > 0 ) data.data.colors = colors;
  16917. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  16918. data.data.faces = faces;
  16919. return data;
  16920. },
  16921. clone: function () {
  16922. /*
  16923. // Handle primitives
  16924. const parameters = this.parameters;
  16925. if ( parameters !== undefined ) {
  16926. const values = [];
  16927. for ( const key in parameters ) {
  16928. values.push( parameters[ key ] );
  16929. }
  16930. const geometry = Object.create( this.constructor.prototype );
  16931. this.constructor.apply( geometry, values );
  16932. return geometry;
  16933. }
  16934. return new this.constructor().copy( this );
  16935. */
  16936. return new Geometry().copy( this );
  16937. },
  16938. copy: function ( source ) {
  16939. // reset
  16940. this.vertices = [];
  16941. this.colors = [];
  16942. this.faces = [];
  16943. this.faceVertexUvs = [[]];
  16944. this.morphTargets = [];
  16945. this.morphNormals = [];
  16946. this.skinWeights = [];
  16947. this.skinIndices = [];
  16948. this.lineDistances = [];
  16949. this.boundingBox = null;
  16950. this.boundingSphere = null;
  16951. // name
  16952. this.name = source.name;
  16953. // vertices
  16954. const vertices = source.vertices;
  16955. for ( let i = 0, il = vertices.length; i < il; i ++ ) {
  16956. this.vertices.push( vertices[ i ].clone() );
  16957. }
  16958. // colors
  16959. const colors = source.colors;
  16960. for ( let i = 0, il = colors.length; i < il; i ++ ) {
  16961. this.colors.push( colors[ i ].clone() );
  16962. }
  16963. // faces
  16964. const faces = source.faces;
  16965. for ( let i = 0, il = faces.length; i < il; i ++ ) {
  16966. this.faces.push( faces[ i ].clone() );
  16967. }
  16968. // face vertex uvs
  16969. for ( let i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  16970. const faceVertexUvs = source.faceVertexUvs[ i ];
  16971. if ( this.faceVertexUvs[ i ] === undefined ) {
  16972. this.faceVertexUvs[ i ] = [];
  16973. }
  16974. for ( let j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  16975. const uvs = faceVertexUvs[ j ], uvsCopy = [];
  16976. for ( let k = 0, kl = uvs.length; k < kl; k ++ ) {
  16977. const uv = uvs[ k ];
  16978. uvsCopy.push( uv.clone() );
  16979. }
  16980. this.faceVertexUvs[ i ].push( uvsCopy );
  16981. }
  16982. }
  16983. // morph targets
  16984. const morphTargets = source.morphTargets;
  16985. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  16986. const morphTarget = {};
  16987. morphTarget.name = morphTargets[ i ].name;
  16988. // vertices
  16989. if ( morphTargets[ i ].vertices !== undefined ) {
  16990. morphTarget.vertices = [];
  16991. for ( let j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  16992. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  16993. }
  16994. }
  16995. // normals
  16996. if ( morphTargets[ i ].normals !== undefined ) {
  16997. morphTarget.normals = [];
  16998. for ( let j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  16999. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  17000. }
  17001. }
  17002. this.morphTargets.push( morphTarget );
  17003. }
  17004. // morph normals
  17005. const morphNormals = source.morphNormals;
  17006. for ( let i = 0, il = morphNormals.length; i < il; i ++ ) {
  17007. const morphNormal = {};
  17008. // vertex normals
  17009. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  17010. morphNormal.vertexNormals = [];
  17011. for ( let j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  17012. const srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  17013. const destVertexNormal = {};
  17014. destVertexNormal.a = srcVertexNormal.a.clone();
  17015. destVertexNormal.b = srcVertexNormal.b.clone();
  17016. destVertexNormal.c = srcVertexNormal.c.clone();
  17017. morphNormal.vertexNormals.push( destVertexNormal );
  17018. }
  17019. }
  17020. // face normals
  17021. if ( morphNormals[ i ].faceNormals !== undefined ) {
  17022. morphNormal.faceNormals = [];
  17023. for ( let j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  17024. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  17025. }
  17026. }
  17027. this.morphNormals.push( morphNormal );
  17028. }
  17029. // skin weights
  17030. const skinWeights = source.skinWeights;
  17031. for ( let i = 0, il = skinWeights.length; i < il; i ++ ) {
  17032. this.skinWeights.push( skinWeights[ i ].clone() );
  17033. }
  17034. // skin indices
  17035. const skinIndices = source.skinIndices;
  17036. for ( let i = 0, il = skinIndices.length; i < il; i ++ ) {
  17037. this.skinIndices.push( skinIndices[ i ].clone() );
  17038. }
  17039. // line distances
  17040. const lineDistances = source.lineDistances;
  17041. for ( let i = 0, il = lineDistances.length; i < il; i ++ ) {
  17042. this.lineDistances.push( lineDistances[ i ] );
  17043. }
  17044. // bounding box
  17045. const boundingBox = source.boundingBox;
  17046. if ( boundingBox !== null ) {
  17047. this.boundingBox = boundingBox.clone();
  17048. }
  17049. // bounding sphere
  17050. const boundingSphere = source.boundingSphere;
  17051. if ( boundingSphere !== null ) {
  17052. this.boundingSphere = boundingSphere.clone();
  17053. }
  17054. // update flags
  17055. this.elementsNeedUpdate = source.elementsNeedUpdate;
  17056. this.verticesNeedUpdate = source.verticesNeedUpdate;
  17057. this.uvsNeedUpdate = source.uvsNeedUpdate;
  17058. this.normalsNeedUpdate = source.normalsNeedUpdate;
  17059. this.colorsNeedUpdate = source.colorsNeedUpdate;
  17060. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  17061. this.groupsNeedUpdate = source.groupsNeedUpdate;
  17062. return this;
  17063. },
  17064. dispose: function () {
  17065. this.dispatchEvent( { type: 'dispose' } );
  17066. }
  17067. } );
  17068. class BoxGeometry extends Geometry {
  17069. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17070. super();
  17071. this.type = 'BoxGeometry';
  17072. this.parameters = {
  17073. width: width,
  17074. height: height,
  17075. depth: depth,
  17076. widthSegments: widthSegments,
  17077. heightSegments: heightSegments,
  17078. depthSegments: depthSegments
  17079. };
  17080. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  17081. this.mergeVertices();
  17082. }
  17083. }
  17084. class CircleBufferGeometry extends BufferGeometry {
  17085. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17086. super();
  17087. this.type = 'CircleBufferGeometry';
  17088. this.parameters = {
  17089. radius: radius,
  17090. segments: segments,
  17091. thetaStart: thetaStart,
  17092. thetaLength: thetaLength
  17093. };
  17094. segments = Math.max( 3, segments );
  17095. // buffers
  17096. const indices = [];
  17097. const vertices = [];
  17098. const normals = [];
  17099. const uvs = [];
  17100. // helper variables
  17101. const vertex = new Vector3();
  17102. const uv = new Vector2();
  17103. // center point
  17104. vertices.push( 0, 0, 0 );
  17105. normals.push( 0, 0, 1 );
  17106. uvs.push( 0.5, 0.5 );
  17107. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17108. const segment = thetaStart + s / segments * thetaLength;
  17109. // vertex
  17110. vertex.x = radius * Math.cos( segment );
  17111. vertex.y = radius * Math.sin( segment );
  17112. vertices.push( vertex.x, vertex.y, vertex.z );
  17113. // normal
  17114. normals.push( 0, 0, 1 );
  17115. // uvs
  17116. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17117. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17118. uvs.push( uv.x, uv.y );
  17119. }
  17120. // indices
  17121. for ( let i = 1; i <= segments; i ++ ) {
  17122. indices.push( i, i + 1, 0 );
  17123. }
  17124. // build geometry
  17125. this.setIndex( indices );
  17126. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17127. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17128. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17129. }
  17130. }
  17131. class CircleGeometry extends Geometry {
  17132. constructor( radius, segments, thetaStart, thetaLength ) {
  17133. super();
  17134. this.type = 'CircleGeometry';
  17135. this.parameters = {
  17136. radius: radius,
  17137. segments: segments,
  17138. thetaStart: thetaStart,
  17139. thetaLength: thetaLength
  17140. };
  17141. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17142. this.mergeVertices();
  17143. }
  17144. }
  17145. class CylinderBufferGeometry extends BufferGeometry {
  17146. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17147. super();
  17148. this.type = 'CylinderBufferGeometry';
  17149. this.parameters = {
  17150. radiusTop: radiusTop,
  17151. radiusBottom: radiusBottom,
  17152. height: height,
  17153. radialSegments: radialSegments,
  17154. heightSegments: heightSegments,
  17155. openEnded: openEnded,
  17156. thetaStart: thetaStart,
  17157. thetaLength: thetaLength
  17158. };
  17159. const scope = this;
  17160. radialSegments = Math.floor( radialSegments );
  17161. heightSegments = Math.floor( heightSegments );
  17162. // buffers
  17163. const indices = [];
  17164. const vertices = [];
  17165. const normals = [];
  17166. const uvs = [];
  17167. // helper variables
  17168. let index = 0;
  17169. const indexArray = [];
  17170. const halfHeight = height / 2;
  17171. let groupStart = 0;
  17172. // generate geometry
  17173. generateTorso();
  17174. if ( openEnded === false ) {
  17175. if ( radiusTop > 0 ) generateCap( true );
  17176. if ( radiusBottom > 0 ) generateCap( false );
  17177. }
  17178. // build geometry
  17179. this.setIndex( indices );
  17180. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17181. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17182. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17183. function generateTorso() {
  17184. const normal = new Vector3();
  17185. const vertex = new Vector3();
  17186. let groupCount = 0;
  17187. // this will be used to calculate the normal
  17188. const slope = ( radiusBottom - radiusTop ) / height;
  17189. // generate vertices, normals and uvs
  17190. for ( let y = 0; y <= heightSegments; y ++ ) {
  17191. const indexRow = [];
  17192. const v = y / heightSegments;
  17193. // calculate the radius of the current row
  17194. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17195. for ( let x = 0; x <= radialSegments; x ++ ) {
  17196. const u = x / radialSegments;
  17197. const theta = u * thetaLength + thetaStart;
  17198. const sinTheta = Math.sin( theta );
  17199. const cosTheta = Math.cos( theta );
  17200. // vertex
  17201. vertex.x = radius * sinTheta;
  17202. vertex.y = - v * height + halfHeight;
  17203. vertex.z = radius * cosTheta;
  17204. vertices.push( vertex.x, vertex.y, vertex.z );
  17205. // normal
  17206. normal.set( sinTheta, slope, cosTheta ).normalize();
  17207. normals.push( normal.x, normal.y, normal.z );
  17208. // uv
  17209. uvs.push( u, 1 - v );
  17210. // save index of vertex in respective row
  17211. indexRow.push( index ++ );
  17212. }
  17213. // now save vertices of the row in our index array
  17214. indexArray.push( indexRow );
  17215. }
  17216. // generate indices
  17217. for ( let x = 0; x < radialSegments; x ++ ) {
  17218. for ( let y = 0; y < heightSegments; y ++ ) {
  17219. // we use the index array to access the correct indices
  17220. const a = indexArray[ y ][ x ];
  17221. const b = indexArray[ y + 1 ][ x ];
  17222. const c = indexArray[ y + 1 ][ x + 1 ];
  17223. const d = indexArray[ y ][ x + 1 ];
  17224. // faces
  17225. indices.push( a, b, d );
  17226. indices.push( b, c, d );
  17227. // update group counter
  17228. groupCount += 6;
  17229. }
  17230. }
  17231. // add a group to the geometry. this will ensure multi material support
  17232. scope.addGroup( groupStart, groupCount, 0 );
  17233. // calculate new start value for groups
  17234. groupStart += groupCount;
  17235. }
  17236. function generateCap( top ) {
  17237. // save the index of the first center vertex
  17238. const centerIndexStart = index;
  17239. const uv = new Vector2();
  17240. const vertex = new Vector3();
  17241. let groupCount = 0;
  17242. const radius = ( top === true ) ? radiusTop : radiusBottom;
  17243. const sign = ( top === true ) ? 1 : - 1;
  17244. // first we generate the center vertex data of the cap.
  17245. // because the geometry needs one set of uvs per face,
  17246. // we must generate a center vertex per face/segment
  17247. for ( let x = 1; x <= radialSegments; x ++ ) {
  17248. // vertex
  17249. vertices.push( 0, halfHeight * sign, 0 );
  17250. // normal
  17251. normals.push( 0, sign, 0 );
  17252. // uv
  17253. uvs.push( 0.5, 0.5 );
  17254. // increase index
  17255. index ++;
  17256. }
  17257. // save the index of the last center vertex
  17258. const centerIndexEnd = index;
  17259. // now we generate the surrounding vertices, normals and uvs
  17260. for ( let x = 0; x <= radialSegments; x ++ ) {
  17261. const u = x / radialSegments;
  17262. const theta = u * thetaLength + thetaStart;
  17263. const cosTheta = Math.cos( theta );
  17264. const sinTheta = Math.sin( theta );
  17265. // vertex
  17266. vertex.x = radius * sinTheta;
  17267. vertex.y = halfHeight * sign;
  17268. vertex.z = radius * cosTheta;
  17269. vertices.push( vertex.x, vertex.y, vertex.z );
  17270. // normal
  17271. normals.push( 0, sign, 0 );
  17272. // uv
  17273. uv.x = ( cosTheta * 0.5 ) + 0.5;
  17274. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  17275. uvs.push( uv.x, uv.y );
  17276. // increase index
  17277. index ++;
  17278. }
  17279. // generate indices
  17280. for ( let x = 0; x < radialSegments; x ++ ) {
  17281. const c = centerIndexStart + x;
  17282. const i = centerIndexEnd + x;
  17283. if ( top === true ) {
  17284. // face top
  17285. indices.push( i, i + 1, c );
  17286. } else {
  17287. // face bottom
  17288. indices.push( i + 1, i, c );
  17289. }
  17290. groupCount += 3;
  17291. }
  17292. // add a group to the geometry. this will ensure multi material support
  17293. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  17294. // calculate new start value for groups
  17295. groupStart += groupCount;
  17296. }
  17297. }
  17298. }
  17299. class CylinderGeometry extends Geometry {
  17300. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17301. super();
  17302. this.type = 'CylinderGeometry';
  17303. this.parameters = {
  17304. radiusTop: radiusTop,
  17305. radiusBottom: radiusBottom,
  17306. height: height,
  17307. radialSegments: radialSegments,
  17308. heightSegments: heightSegments,
  17309. openEnded: openEnded,
  17310. thetaStart: thetaStart,
  17311. thetaLength: thetaLength
  17312. };
  17313. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  17314. this.mergeVertices();
  17315. }
  17316. }
  17317. class ConeGeometry extends CylinderGeometry {
  17318. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  17319. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17320. this.type = 'ConeGeometry';
  17321. this.parameters = {
  17322. radius: radius,
  17323. height: height,
  17324. radialSegments: radialSegments,
  17325. heightSegments: heightSegments,
  17326. openEnded: openEnded,
  17327. thetaStart: thetaStart,
  17328. thetaLength: thetaLength
  17329. };
  17330. }
  17331. }
  17332. class ConeBufferGeometry extends CylinderBufferGeometry {
  17333. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17334. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  17335. this.type = 'ConeBufferGeometry';
  17336. this.parameters = {
  17337. radius: radius,
  17338. height: height,
  17339. radialSegments: radialSegments,
  17340. heightSegments: heightSegments,
  17341. openEnded: openEnded,
  17342. thetaStart: thetaStart,
  17343. thetaLength: thetaLength
  17344. };
  17345. }
  17346. }
  17347. class PolyhedronBufferGeometry extends BufferGeometry {
  17348. constructor( vertices, indices, radius = 1, detail = 0 ) {
  17349. super();
  17350. this.type = 'PolyhedronBufferGeometry';
  17351. this.parameters = {
  17352. vertices: vertices,
  17353. indices: indices,
  17354. radius: radius,
  17355. detail: detail
  17356. };
  17357. // default buffer data
  17358. const vertexBuffer = [];
  17359. const uvBuffer = [];
  17360. // the subdivision creates the vertex buffer data
  17361. subdivide( detail );
  17362. // all vertices should lie on a conceptual sphere with a given radius
  17363. applyRadius( radius );
  17364. // finally, create the uv data
  17365. generateUVs();
  17366. // build non-indexed geometry
  17367. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  17368. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  17369. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  17370. if ( detail === 0 ) {
  17371. this.computeVertexNormals(); // flat normals
  17372. } else {
  17373. this.normalizeNormals(); // smooth normals
  17374. }
  17375. // helper functions
  17376. function subdivide( detail ) {
  17377. const a = new Vector3();
  17378. const b = new Vector3();
  17379. const c = new Vector3();
  17380. // iterate over all faces and apply a subdivison with the given detail value
  17381. for ( let i = 0; i < indices.length; i += 3 ) {
  17382. // get the vertices of the face
  17383. getVertexByIndex( indices[ i + 0 ], a );
  17384. getVertexByIndex( indices[ i + 1 ], b );
  17385. getVertexByIndex( indices[ i + 2 ], c );
  17386. // perform subdivision
  17387. subdivideFace( a, b, c, detail );
  17388. }
  17389. }
  17390. function subdivideFace( a, b, c, detail ) {
  17391. const cols = detail + 1;
  17392. // we use this multidimensional array as a data structure for creating the subdivision
  17393. const v = [];
  17394. // construct all of the vertices for this subdivision
  17395. for ( let i = 0; i <= cols; i ++ ) {
  17396. v[ i ] = [];
  17397. const aj = a.clone().lerp( c, i / cols );
  17398. const bj = b.clone().lerp( c, i / cols );
  17399. const rows = cols - i;
  17400. for ( let j = 0; j <= rows; j ++ ) {
  17401. if ( j === 0 && i === cols ) {
  17402. v[ i ][ j ] = aj;
  17403. } else {
  17404. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  17405. }
  17406. }
  17407. }
  17408. // construct all of the faces
  17409. for ( let i = 0; i < cols; i ++ ) {
  17410. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  17411. const k = Math.floor( j / 2 );
  17412. if ( j % 2 === 0 ) {
  17413. pushVertex( v[ i ][ k + 1 ] );
  17414. pushVertex( v[ i + 1 ][ k ] );
  17415. pushVertex( v[ i ][ k ] );
  17416. } else {
  17417. pushVertex( v[ i ][ k + 1 ] );
  17418. pushVertex( v[ i + 1 ][ k + 1 ] );
  17419. pushVertex( v[ i + 1 ][ k ] );
  17420. }
  17421. }
  17422. }
  17423. }
  17424. function applyRadius( radius ) {
  17425. const vertex = new Vector3();
  17426. // iterate over the entire buffer and apply the radius to each vertex
  17427. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  17428. vertex.x = vertexBuffer[ i + 0 ];
  17429. vertex.y = vertexBuffer[ i + 1 ];
  17430. vertex.z = vertexBuffer[ i + 2 ];
  17431. vertex.normalize().multiplyScalar( radius );
  17432. vertexBuffer[ i + 0 ] = vertex.x;
  17433. vertexBuffer[ i + 1 ] = vertex.y;
  17434. vertexBuffer[ i + 2 ] = vertex.z;
  17435. }
  17436. }
  17437. function generateUVs() {
  17438. const vertex = new Vector3();
  17439. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  17440. vertex.x = vertexBuffer[ i + 0 ];
  17441. vertex.y = vertexBuffer[ i + 1 ];
  17442. vertex.z = vertexBuffer[ i + 2 ];
  17443. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  17444. const v = inclination( vertex ) / Math.PI + 0.5;
  17445. uvBuffer.push( u, 1 - v );
  17446. }
  17447. correctUVs();
  17448. correctSeam();
  17449. }
  17450. function correctSeam() {
  17451. // handle case when face straddles the seam, see #3269
  17452. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  17453. // uv data of a single face
  17454. const x0 = uvBuffer[ i + 0 ];
  17455. const x1 = uvBuffer[ i + 2 ];
  17456. const x2 = uvBuffer[ i + 4 ];
  17457. const max = Math.max( x0, x1, x2 );
  17458. const min = Math.min( x0, x1, x2 );
  17459. // 0.9 is somewhat arbitrary
  17460. if ( max > 0.9 && min < 0.1 ) {
  17461. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  17462. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  17463. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  17464. }
  17465. }
  17466. }
  17467. function pushVertex( vertex ) {
  17468. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  17469. }
  17470. function getVertexByIndex( index, vertex ) {
  17471. const stride = index * 3;
  17472. vertex.x = vertices[ stride + 0 ];
  17473. vertex.y = vertices[ stride + 1 ];
  17474. vertex.z = vertices[ stride + 2 ];
  17475. }
  17476. function correctUVs() {
  17477. const a = new Vector3();
  17478. const b = new Vector3();
  17479. const c = new Vector3();
  17480. const centroid = new Vector3();
  17481. const uvA = new Vector2();
  17482. const uvB = new Vector2();
  17483. const uvC = new Vector2();
  17484. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  17485. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  17486. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  17487. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  17488. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  17489. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  17490. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  17491. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  17492. const azi = azimuth( centroid );
  17493. correctUV( uvA, j + 0, a, azi );
  17494. correctUV( uvB, j + 2, b, azi );
  17495. correctUV( uvC, j + 4, c, azi );
  17496. }
  17497. }
  17498. function correctUV( uv, stride, vector, azimuth ) {
  17499. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  17500. uvBuffer[ stride ] = uv.x - 1;
  17501. }
  17502. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  17503. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  17504. }
  17505. }
  17506. // Angle around the Y axis, counter-clockwise when looking from above.
  17507. function azimuth( vector ) {
  17508. return Math.atan2( vector.z, - vector.x );
  17509. }
  17510. // Angle above the XZ plane.
  17511. function inclination( vector ) {
  17512. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  17513. }
  17514. }
  17515. }
  17516. class DodecahedronBufferGeometry extends PolyhedronBufferGeometry {
  17517. constructor( radius = 1, detail = 0 ) {
  17518. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  17519. const r = 1 / t;
  17520. const vertices = [
  17521. // (±1, ±1, ±1)
  17522. - 1, - 1, - 1, - 1, - 1, 1,
  17523. - 1, 1, - 1, - 1, 1, 1,
  17524. 1, - 1, - 1, 1, - 1, 1,
  17525. 1, 1, - 1, 1, 1, 1,
  17526. // (0, ±1/φ, ±φ)
  17527. 0, - r, - t, 0, - r, t,
  17528. 0, r, - t, 0, r, t,
  17529. // (±1/φ, ±φ, 0)
  17530. - r, - t, 0, - r, t, 0,
  17531. r, - t, 0, r, t, 0,
  17532. // (±φ, 0, ±1/φ)
  17533. - t, 0, - r, t, 0, - r,
  17534. - t, 0, r, t, 0, r
  17535. ];
  17536. const indices = [
  17537. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  17538. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  17539. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  17540. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  17541. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  17542. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  17543. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  17544. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  17545. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  17546. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  17547. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  17548. 1, 12, 14, 1, 14, 5, 1, 5, 9
  17549. ];
  17550. super( vertices, indices, radius, detail );
  17551. this.type = 'DodecahedronBufferGeometry';
  17552. this.parameters = {
  17553. radius: radius,
  17554. detail: detail
  17555. };
  17556. }
  17557. }
  17558. class DodecahedronGeometry extends Geometry {
  17559. constructor( radius, detail ) {
  17560. super();
  17561. this.type = 'DodecahedronGeometry';
  17562. this.parameters = {
  17563. radius: radius,
  17564. detail: detail
  17565. };
  17566. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  17567. this.mergeVertices();
  17568. }
  17569. }
  17570. const _v0$2 = new Vector3();
  17571. const _v1$5 = new Vector3();
  17572. const _normal$1 = new Vector3();
  17573. const _triangle = new Triangle();
  17574. class EdgesGeometry extends BufferGeometry {
  17575. constructor( geometry, thresholdAngle ) {
  17576. super();
  17577. this.type = 'EdgesGeometry';
  17578. this.parameters = {
  17579. thresholdAngle: thresholdAngle
  17580. };
  17581. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  17582. if ( geometry.isGeometry ) {
  17583. geometry = new BufferGeometry().fromGeometry( geometry );
  17584. }
  17585. const precisionPoints = 4;
  17586. const precision = Math.pow( 10, precisionPoints );
  17587. const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
  17588. const indexAttr = geometry.getIndex();
  17589. const positionAttr = geometry.getAttribute( 'position' );
  17590. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  17591. const indexArr = [ 0, 0, 0 ];
  17592. const vertKeys = [ 'a', 'b', 'c' ];
  17593. const hashes = new Array( 3 );
  17594. const edgeData = {};
  17595. const vertices = [];
  17596. for ( let i = 0; i < indexCount; i += 3 ) {
  17597. if ( indexAttr ) {
  17598. indexArr[ 0 ] = indexAttr.getX( i );
  17599. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  17600. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  17601. } else {
  17602. indexArr[ 0 ] = i;
  17603. indexArr[ 1 ] = i + 1;
  17604. indexArr[ 2 ] = i + 2;
  17605. }
  17606. const { a, b, c } = _triangle;
  17607. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  17608. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  17609. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  17610. _triangle.getNormal( _normal$1 );
  17611. // create hashes for the edge from the vertices
  17612. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  17613. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  17614. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  17615. // skip degenerate triangles
  17616. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  17617. continue;
  17618. }
  17619. // iterate over every edge
  17620. for ( let j = 0; j < 3; j ++ ) {
  17621. // get the first and next vertex making up the edge
  17622. const jNext = ( j + 1 ) % 3;
  17623. const vecHash0 = hashes[ j ];
  17624. const vecHash1 = hashes[ jNext ];
  17625. const v0 = _triangle[ vertKeys[ j ] ];
  17626. const v1 = _triangle[ vertKeys[ jNext ] ];
  17627. const hash = `${ vecHash0 }_${ vecHash1 }`;
  17628. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  17629. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  17630. // if we found a sibling edge add it into the vertex array if
  17631. // it meets the angle threshold and delete the edge from the map.
  17632. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  17633. vertices.push( v0.x, v0.y, v0.z );
  17634. vertices.push( v1.x, v1.y, v1.z );
  17635. }
  17636. edgeData[ reverseHash ] = null;
  17637. } else if ( ! ( hash in edgeData ) ) {
  17638. // if we've already got an edge here then skip adding a new one
  17639. edgeData[ hash ] = {
  17640. index0: indexArr[ j ],
  17641. index1: indexArr[ jNext ],
  17642. normal: _normal$1.clone(),
  17643. };
  17644. }
  17645. }
  17646. }
  17647. // iterate over all remaining, unmatched edges and add them to the vertex array
  17648. for ( const key in edgeData ) {
  17649. if ( edgeData[ key ] ) {
  17650. const { index0, index1 } = edgeData[ key ];
  17651. _v0$2.fromBufferAttribute( positionAttr, index0 );
  17652. _v1$5.fromBufferAttribute( positionAttr, index1 );
  17653. vertices.push( _v0$2.x, _v0$2.y, _v0$2.z );
  17654. vertices.push( _v1$5.x, _v1$5.y, _v1$5.z );
  17655. }
  17656. }
  17657. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17658. }
  17659. }
  17660. /**
  17661. * Port from https://github.com/mapbox/earcut (v2.2.2)
  17662. */
  17663. const Earcut = {
  17664. triangulate: function ( data, holeIndices, dim ) {
  17665. dim = dim || 2;
  17666. const hasHoles = holeIndices && holeIndices.length;
  17667. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  17668. let outerNode = linkedList( data, 0, outerLen, dim, true );
  17669. const triangles = [];
  17670. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  17671. let minX, minY, maxX, maxY, x, y, invSize;
  17672. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  17673. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  17674. if ( data.length > 80 * dim ) {
  17675. minX = maxX = data[ 0 ];
  17676. minY = maxY = data[ 1 ];
  17677. for ( let i = dim; i < outerLen; i += dim ) {
  17678. x = data[ i ];
  17679. y = data[ i + 1 ];
  17680. if ( x < minX ) minX = x;
  17681. if ( y < minY ) minY = y;
  17682. if ( x > maxX ) maxX = x;
  17683. if ( y > maxY ) maxY = y;
  17684. }
  17685. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17686. invSize = Math.max( maxX - minX, maxY - minY );
  17687. invSize = invSize !== 0 ? 1 / invSize : 0;
  17688. }
  17689. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  17690. return triangles;
  17691. }
  17692. };
  17693. // create a circular doubly linked list from polygon points in the specified winding order
  17694. function linkedList( data, start, end, dim, clockwise ) {
  17695. let i, last;
  17696. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  17697. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  17698. } else {
  17699. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  17700. }
  17701. if ( last && equals( last, last.next ) ) {
  17702. removeNode( last );
  17703. last = last.next;
  17704. }
  17705. return last;
  17706. }
  17707. // eliminate colinear or duplicate points
  17708. function filterPoints( start, end ) {
  17709. if ( ! start ) return start;
  17710. if ( ! end ) end = start;
  17711. let p = start,
  17712. again;
  17713. do {
  17714. again = false;
  17715. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  17716. removeNode( p );
  17717. p = end = p.prev;
  17718. if ( p === p.next ) break;
  17719. again = true;
  17720. } else {
  17721. p = p.next;
  17722. }
  17723. } while ( again || p !== end );
  17724. return end;
  17725. }
  17726. // main ear slicing loop which triangulates a polygon (given as a linked list)
  17727. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  17728. if ( ! ear ) return;
  17729. // interlink polygon nodes in z-order
  17730. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  17731. let stop = ear,
  17732. prev, next;
  17733. // iterate through ears, slicing them one by one
  17734. while ( ear.prev !== ear.next ) {
  17735. prev = ear.prev;
  17736. next = ear.next;
  17737. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  17738. // cut off the triangle
  17739. triangles.push( prev.i / dim );
  17740. triangles.push( ear.i / dim );
  17741. triangles.push( next.i / dim );
  17742. removeNode( ear );
  17743. // skipping the next vertex leads to less sliver triangles
  17744. ear = next.next;
  17745. stop = next.next;
  17746. continue;
  17747. }
  17748. ear = next;
  17749. // if we looped through the whole remaining polygon and can't find any more ears
  17750. if ( ear === stop ) {
  17751. // try filtering points and slicing again
  17752. if ( ! pass ) {
  17753. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  17754. // if this didn't work, try curing all small self-intersections locally
  17755. } else if ( pass === 1 ) {
  17756. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  17757. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  17758. // as a last resort, try splitting the remaining polygon into two
  17759. } else if ( pass === 2 ) {
  17760. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  17761. }
  17762. break;
  17763. }
  17764. }
  17765. }
  17766. // check whether a polygon node forms a valid ear with adjacent nodes
  17767. function isEar( ear ) {
  17768. const a = ear.prev,
  17769. b = ear,
  17770. c = ear.next;
  17771. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  17772. // now make sure we don't have other points inside the potential ear
  17773. let p = ear.next.next;
  17774. while ( p !== ear.prev ) {
  17775. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17776. area( p.prev, p, p.next ) >= 0 ) return false;
  17777. p = p.next;
  17778. }
  17779. return true;
  17780. }
  17781. function isEarHashed( ear, minX, minY, invSize ) {
  17782. const a = ear.prev,
  17783. b = ear,
  17784. c = ear.next;
  17785. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  17786. // triangle bbox; min & max are calculated like this for speed
  17787. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  17788. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  17789. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  17790. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  17791. // z-order range for the current triangle bbox;
  17792. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  17793. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  17794. let p = ear.prevZ,
  17795. n = ear.nextZ;
  17796. // look for points inside the triangle in both directions
  17797. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  17798. if ( p !== ear.prev && p !== ear.next &&
  17799. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17800. area( p.prev, p, p.next ) >= 0 ) return false;
  17801. p = p.prevZ;
  17802. if ( n !== ear.prev && n !== ear.next &&
  17803. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  17804. area( n.prev, n, n.next ) >= 0 ) return false;
  17805. n = n.nextZ;
  17806. }
  17807. // look for remaining points in decreasing z-order
  17808. while ( p && p.z >= minZ ) {
  17809. if ( p !== ear.prev && p !== ear.next &&
  17810. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  17811. area( p.prev, p, p.next ) >= 0 ) return false;
  17812. p = p.prevZ;
  17813. }
  17814. // look for remaining points in increasing z-order
  17815. while ( n && n.z <= maxZ ) {
  17816. if ( n !== ear.prev && n !== ear.next &&
  17817. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  17818. area( n.prev, n, n.next ) >= 0 ) return false;
  17819. n = n.nextZ;
  17820. }
  17821. return true;
  17822. }
  17823. // go through all polygon nodes and cure small local self-intersections
  17824. function cureLocalIntersections( start, triangles, dim ) {
  17825. let p = start;
  17826. do {
  17827. const a = p.prev,
  17828. b = p.next.next;
  17829. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  17830. triangles.push( a.i / dim );
  17831. triangles.push( p.i / dim );
  17832. triangles.push( b.i / dim );
  17833. // remove two nodes involved
  17834. removeNode( p );
  17835. removeNode( p.next );
  17836. p = start = b;
  17837. }
  17838. p = p.next;
  17839. } while ( p !== start );
  17840. return filterPoints( p );
  17841. }
  17842. // try splitting polygon into two and triangulate them independently
  17843. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  17844. // look for a valid diagonal that divides the polygon into two
  17845. let a = start;
  17846. do {
  17847. let b = a.next.next;
  17848. while ( b !== a.prev ) {
  17849. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  17850. // split the polygon in two by the diagonal
  17851. let c = splitPolygon( a, b );
  17852. // filter colinear points around the cuts
  17853. a = filterPoints( a, a.next );
  17854. c = filterPoints( c, c.next );
  17855. // run earcut on each half
  17856. earcutLinked( a, triangles, dim, minX, minY, invSize );
  17857. earcutLinked( c, triangles, dim, minX, minY, invSize );
  17858. return;
  17859. }
  17860. b = b.next;
  17861. }
  17862. a = a.next;
  17863. } while ( a !== start );
  17864. }
  17865. // link every hole into the outer loop, producing a single-ring polygon without holes
  17866. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  17867. const queue = [];
  17868. let i, len, start, end, list;
  17869. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  17870. start = holeIndices[ i ] * dim;
  17871. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  17872. list = linkedList( data, start, end, dim, false );
  17873. if ( list === list.next ) list.steiner = true;
  17874. queue.push( getLeftmost( list ) );
  17875. }
  17876. queue.sort( compareX );
  17877. // process holes from left to right
  17878. for ( i = 0; i < queue.length; i ++ ) {
  17879. eliminateHole( queue[ i ], outerNode );
  17880. outerNode = filterPoints( outerNode, outerNode.next );
  17881. }
  17882. return outerNode;
  17883. }
  17884. function compareX( a, b ) {
  17885. return a.x - b.x;
  17886. }
  17887. // find a bridge between vertices that connects hole with an outer ring and and link it
  17888. function eliminateHole( hole, outerNode ) {
  17889. outerNode = findHoleBridge( hole, outerNode );
  17890. if ( outerNode ) {
  17891. const b = splitPolygon( outerNode, hole );
  17892. // filter collinear points around the cuts
  17893. filterPoints( outerNode, outerNode.next );
  17894. filterPoints( b, b.next );
  17895. }
  17896. }
  17897. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17898. function findHoleBridge( hole, outerNode ) {
  17899. let p = outerNode;
  17900. const hx = hole.x;
  17901. const hy = hole.y;
  17902. let qx = - Infinity, m;
  17903. // find a segment intersected by a ray from the hole's leftmost point to the left;
  17904. // segment's endpoint with lesser x will be potential connection point
  17905. do {
  17906. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  17907. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  17908. if ( x <= hx && x > qx ) {
  17909. qx = x;
  17910. if ( x === hx ) {
  17911. if ( hy === p.y ) return p;
  17912. if ( hy === p.next.y ) return p.next;
  17913. }
  17914. m = p.x < p.next.x ? p : p.next;
  17915. }
  17916. }
  17917. p = p.next;
  17918. } while ( p !== outerNode );
  17919. if ( ! m ) return null;
  17920. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  17921. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17922. // if there are no points found, we have a valid connection;
  17923. // otherwise choose the point of the minimum angle with the ray as connection point
  17924. const stop = m,
  17925. mx = m.x,
  17926. my = m.y;
  17927. let tanMin = Infinity, tan;
  17928. p = m;
  17929. do {
  17930. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  17931. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  17932. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  17933. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  17934. m = p;
  17935. tanMin = tan;
  17936. }
  17937. }
  17938. p = p.next;
  17939. } while ( p !== stop );
  17940. return m;
  17941. }
  17942. // whether sector in vertex m contains sector in vertex p in the same coordinates
  17943. function sectorContainsSector( m, p ) {
  17944. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  17945. }
  17946. // interlink polygon nodes in z-order
  17947. function indexCurve( start, minX, minY, invSize ) {
  17948. let p = start;
  17949. do {
  17950. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  17951. p.prevZ = p.prev;
  17952. p.nextZ = p.next;
  17953. p = p.next;
  17954. } while ( p !== start );
  17955. p.prevZ.nextZ = null;
  17956. p.prevZ = null;
  17957. sortLinked( p );
  17958. }
  17959. // Simon Tatham's linked list merge sort algorithm
  17960. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17961. function sortLinked( list ) {
  17962. let i, p, q, e, tail, numMerges, pSize, qSize,
  17963. inSize = 1;
  17964. do {
  17965. p = list;
  17966. list = null;
  17967. tail = null;
  17968. numMerges = 0;
  17969. while ( p ) {
  17970. numMerges ++;
  17971. q = p;
  17972. pSize = 0;
  17973. for ( i = 0; i < inSize; i ++ ) {
  17974. pSize ++;
  17975. q = q.nextZ;
  17976. if ( ! q ) break;
  17977. }
  17978. qSize = inSize;
  17979. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  17980. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  17981. e = p;
  17982. p = p.nextZ;
  17983. pSize --;
  17984. } else {
  17985. e = q;
  17986. q = q.nextZ;
  17987. qSize --;
  17988. }
  17989. if ( tail ) tail.nextZ = e;
  17990. else list = e;
  17991. e.prevZ = tail;
  17992. tail = e;
  17993. }
  17994. p = q;
  17995. }
  17996. tail.nextZ = null;
  17997. inSize *= 2;
  17998. } while ( numMerges > 1 );
  17999. return list;
  18000. }
  18001. // z-order of a point given coords and inverse of the longer side of data bbox
  18002. function zOrder( x, y, minX, minY, invSize ) {
  18003. // coords are transformed into non-negative 15-bit integer range
  18004. x = 32767 * ( x - minX ) * invSize;
  18005. y = 32767 * ( y - minY ) * invSize;
  18006. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  18007. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  18008. x = ( x | ( x << 2 ) ) & 0x33333333;
  18009. x = ( x | ( x << 1 ) ) & 0x55555555;
  18010. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  18011. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  18012. y = ( y | ( y << 2 ) ) & 0x33333333;
  18013. y = ( y | ( y << 1 ) ) & 0x55555555;
  18014. return x | ( y << 1 );
  18015. }
  18016. // find the leftmost node of a polygon ring
  18017. function getLeftmost( start ) {
  18018. let p = start,
  18019. leftmost = start;
  18020. do {
  18021. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  18022. p = p.next;
  18023. } while ( p !== start );
  18024. return leftmost;
  18025. }
  18026. // check if a point lies within a convex triangle
  18027. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  18028. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  18029. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  18030. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  18031. }
  18032. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18033. function isValidDiagonal( a, b ) {
  18034. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  18035. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  18036. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  18037. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  18038. }
  18039. // signed area of a triangle
  18040. function area( p, q, r ) {
  18041. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  18042. }
  18043. // check if two points are equal
  18044. function equals( p1, p2 ) {
  18045. return p1.x === p2.x && p1.y === p2.y;
  18046. }
  18047. // check if two segments intersect
  18048. function intersects( p1, q1, p2, q2 ) {
  18049. const o1 = sign( area( p1, q1, p2 ) );
  18050. const o2 = sign( area( p1, q1, q2 ) );
  18051. const o3 = sign( area( p2, q2, p1 ) );
  18052. const o4 = sign( area( p2, q2, q1 ) );
  18053. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  18054. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18055. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18056. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18057. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18058. return false;
  18059. }
  18060. // for collinear points p, q, r, check if point q lies on segment pr
  18061. function onSegment( p, q, r ) {
  18062. 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 );
  18063. }
  18064. function sign( num ) {
  18065. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  18066. }
  18067. // check if a polygon diagonal intersects any polygon segments
  18068. function intersectsPolygon( a, b ) {
  18069. let p = a;
  18070. do {
  18071. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  18072. intersects( p, p.next, a, b ) ) return true;
  18073. p = p.next;
  18074. } while ( p !== a );
  18075. return false;
  18076. }
  18077. // check if a polygon diagonal is locally inside the polygon
  18078. function locallyInside( a, b ) {
  18079. return area( a.prev, a, a.next ) < 0 ?
  18080. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  18081. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  18082. }
  18083. // check if the middle point of a polygon diagonal is inside the polygon
  18084. function middleInside( a, b ) {
  18085. let p = a,
  18086. inside = false;
  18087. const px = ( a.x + b.x ) / 2,
  18088. py = ( a.y + b.y ) / 2;
  18089. do {
  18090. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  18091. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  18092. inside = ! inside;
  18093. p = p.next;
  18094. } while ( p !== a );
  18095. return inside;
  18096. }
  18097. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18098. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18099. function splitPolygon( a, b ) {
  18100. const a2 = new Node( a.i, a.x, a.y ),
  18101. b2 = new Node( b.i, b.x, b.y ),
  18102. an = a.next,
  18103. bp = b.prev;
  18104. a.next = b;
  18105. b.prev = a;
  18106. a2.next = an;
  18107. an.prev = a2;
  18108. b2.next = a2;
  18109. a2.prev = b2;
  18110. bp.next = b2;
  18111. b2.prev = bp;
  18112. return b2;
  18113. }
  18114. // create a node and optionally link it with previous one (in a circular doubly linked list)
  18115. function insertNode( i, x, y, last ) {
  18116. const p = new Node( i, x, y );
  18117. if ( ! last ) {
  18118. p.prev = p;
  18119. p.next = p;
  18120. } else {
  18121. p.next = last.next;
  18122. p.prev = last;
  18123. last.next.prev = p;
  18124. last.next = p;
  18125. }
  18126. return p;
  18127. }
  18128. function removeNode( p ) {
  18129. p.next.prev = p.prev;
  18130. p.prev.next = p.next;
  18131. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  18132. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  18133. }
  18134. function Node( i, x, y ) {
  18135. // vertex index in coordinates array
  18136. this.i = i;
  18137. // vertex coordinates
  18138. this.x = x;
  18139. this.y = y;
  18140. // previous and next vertex nodes in a polygon ring
  18141. this.prev = null;
  18142. this.next = null;
  18143. // z-order curve value
  18144. this.z = null;
  18145. // previous and next nodes in z-order
  18146. this.prevZ = null;
  18147. this.nextZ = null;
  18148. // indicates whether this is a steiner point
  18149. this.steiner = false;
  18150. }
  18151. function signedArea( data, start, end, dim ) {
  18152. let sum = 0;
  18153. for ( let i = start, j = end - dim; i < end; i += dim ) {
  18154. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  18155. j = i;
  18156. }
  18157. return sum;
  18158. }
  18159. const ShapeUtils = {
  18160. // calculate area of the contour polygon
  18161. area: function ( contour ) {
  18162. const n = contour.length;
  18163. let a = 0.0;
  18164. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  18165. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  18166. }
  18167. return a * 0.5;
  18168. },
  18169. isClockWise: function ( pts ) {
  18170. return ShapeUtils.area( pts ) < 0;
  18171. },
  18172. triangulateShape: function ( contour, holes ) {
  18173. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18174. const holeIndices = []; // array of hole indices
  18175. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18176. removeDupEndPts( contour );
  18177. addContour( vertices, contour );
  18178. //
  18179. let holeIndex = contour.length;
  18180. holes.forEach( removeDupEndPts );
  18181. for ( let i = 0; i < holes.length; i ++ ) {
  18182. holeIndices.push( holeIndex );
  18183. holeIndex += holes[ i ].length;
  18184. addContour( vertices, holes[ i ] );
  18185. }
  18186. //
  18187. const triangles = Earcut.triangulate( vertices, holeIndices );
  18188. //
  18189. for ( let i = 0; i < triangles.length; i += 3 ) {
  18190. faces.push( triangles.slice( i, i + 3 ) );
  18191. }
  18192. return faces;
  18193. }
  18194. };
  18195. function removeDupEndPts( points ) {
  18196. const l = points.length;
  18197. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  18198. points.pop();
  18199. }
  18200. }
  18201. function addContour( vertices, contour ) {
  18202. for ( let i = 0; i < contour.length; i ++ ) {
  18203. vertices.push( contour[ i ].x );
  18204. vertices.push( contour[ i ].y );
  18205. }
  18206. }
  18207. /**
  18208. * Creates extruded geometry from a path shape.
  18209. *
  18210. * parameters = {
  18211. *
  18212. * curveSegments: <int>, // number of points on the curves
  18213. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18214. * depth: <float>, // Depth to extrude the shape
  18215. *
  18216. * bevelEnabled: <bool>, // turn on bevel
  18217. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18218. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18219. * bevelOffset: <float>, // how far from shape outline does bevel start
  18220. * bevelSegments: <int>, // number of bevel layers
  18221. *
  18222. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18223. *
  18224. * UVGenerator: <Object> // object that provides UV generator functions
  18225. *
  18226. * }
  18227. */
  18228. class ExtrudeBufferGeometry extends BufferGeometry {
  18229. constructor( shapes, options ) {
  18230. super();
  18231. this.type = 'ExtrudeBufferGeometry';
  18232. this.parameters = {
  18233. shapes: shapes,
  18234. options: options
  18235. };
  18236. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18237. const scope = this;
  18238. const verticesArray = [];
  18239. const uvArray = [];
  18240. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18241. const shape = shapes[ i ];
  18242. addShape( shape );
  18243. }
  18244. // build geometry
  18245. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  18246. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  18247. this.computeVertexNormals();
  18248. // functions
  18249. function addShape( shape ) {
  18250. const placeholder = [];
  18251. // options
  18252. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18253. const steps = options.steps !== undefined ? options.steps : 1;
  18254. let depth = options.depth !== undefined ? options.depth : 100;
  18255. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18256. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18257. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18258. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18259. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18260. const extrudePath = options.extrudePath;
  18261. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  18262. // deprecated options
  18263. if ( options.amount !== undefined ) {
  18264. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  18265. depth = options.amount;
  18266. }
  18267. //
  18268. let extrudePts, extrudeByPath = false;
  18269. let splineTube, binormal, normal, position2;
  18270. if ( extrudePath ) {
  18271. extrudePts = extrudePath.getSpacedPoints( steps );
  18272. extrudeByPath = true;
  18273. bevelEnabled = false; // bevels not supported for path extrusion
  18274. // SETUP TNB variables
  18275. // TODO1 - have a .isClosed in spline?
  18276. splineTube = extrudePath.computeFrenetFrames( steps, false );
  18277. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18278. binormal = new Vector3();
  18279. normal = new Vector3();
  18280. position2 = new Vector3();
  18281. }
  18282. // Safeguards if bevels are not enabled
  18283. if ( ! bevelEnabled ) {
  18284. bevelSegments = 0;
  18285. bevelThickness = 0;
  18286. bevelSize = 0;
  18287. bevelOffset = 0;
  18288. }
  18289. // Variables initialization
  18290. const shapePoints = shape.extractPoints( curveSegments );
  18291. let vertices = shapePoints.shape;
  18292. const holes = shapePoints.holes;
  18293. const reverse = ! ShapeUtils.isClockWise( vertices );
  18294. if ( reverse ) {
  18295. vertices = vertices.reverse();
  18296. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18297. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18298. const ahole = holes[ h ];
  18299. if ( ShapeUtils.isClockWise( ahole ) ) {
  18300. holes[ h ] = ahole.reverse();
  18301. }
  18302. }
  18303. }
  18304. const faces = ShapeUtils.triangulateShape( vertices, holes );
  18305. /* Vertices */
  18306. const contour = vertices; // vertices has all points but contour has only points of circumference
  18307. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18308. const ahole = holes[ h ];
  18309. vertices = vertices.concat( ahole );
  18310. }
  18311. function scalePt2( pt, vec, size ) {
  18312. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  18313. return vec.clone().multiplyScalar( size ).add( pt );
  18314. }
  18315. const vlen = vertices.length, flen = faces.length;
  18316. // Find directions for point movement
  18317. function getBevelVec( inPt, inPrev, inNext ) {
  18318. // computes for inPt the corresponding point inPt' on a new contour
  18319. // shifted by 1 unit (length of normalized vector) to the left
  18320. // if we walk along contour clockwise, this new contour is outside the old one
  18321. //
  18322. // inPt' is the intersection of the two lines parallel to the two
  18323. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18324. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18325. // good reading for geometry algorithms (here: line-line intersection)
  18326. // http://geomalgorithms.com/a05-_intersect-1.html
  18327. const v_prev_x = inPt.x - inPrev.x,
  18328. v_prev_y = inPt.y - inPrev.y;
  18329. const v_next_x = inNext.x - inPt.x,
  18330. v_next_y = inNext.y - inPt.y;
  18331. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18332. // check for collinear edges
  18333. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18334. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  18335. // not collinear
  18336. // length of vectors for normalizing
  18337. const v_prev_len = Math.sqrt( v_prev_lensq );
  18338. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18339. // shift adjacent points by unit vectors to the left
  18340. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18341. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18342. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18343. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18344. // scaling factor for v_prev to intersection point
  18345. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18346. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18347. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18348. // vector from inPt to intersection point
  18349. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18350. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18351. // Don't normalize!, otherwise sharp corners become ugly
  18352. // but prevent crazy spikes
  18353. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  18354. if ( v_trans_lensq <= 2 ) {
  18355. return new Vector2( v_trans_x, v_trans_y );
  18356. } else {
  18357. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18358. }
  18359. } else {
  18360. // handle special case of collinear edges
  18361. let direction_eq = false; // assumes: opposite
  18362. if ( v_prev_x > Number.EPSILON ) {
  18363. if ( v_next_x > Number.EPSILON ) {
  18364. direction_eq = true;
  18365. }
  18366. } else {
  18367. if ( v_prev_x < - Number.EPSILON ) {
  18368. if ( v_next_x < - Number.EPSILON ) {
  18369. direction_eq = true;
  18370. }
  18371. } else {
  18372. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  18373. direction_eq = true;
  18374. }
  18375. }
  18376. }
  18377. if ( direction_eq ) {
  18378. // console.log("Warning: lines are a straight sequence");
  18379. v_trans_x = - v_prev_y;
  18380. v_trans_y = v_prev_x;
  18381. shrink_by = Math.sqrt( v_prev_lensq );
  18382. } else {
  18383. // console.log("Warning: lines are a straight spike");
  18384. v_trans_x = v_prev_x;
  18385. v_trans_y = v_prev_y;
  18386. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18387. }
  18388. }
  18389. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18390. }
  18391. const contourMovements = [];
  18392. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18393. if ( j === il ) j = 0;
  18394. if ( k === il ) k = 0;
  18395. // (j)---(i)---(k)
  18396. // console.log('i,j,k', i, j , k)
  18397. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18398. }
  18399. const holesMovements = [];
  18400. let oneHoleMovements, verticesMovements = contourMovements.concat();
  18401. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18402. const ahole = holes[ h ];
  18403. oneHoleMovements = [];
  18404. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18405. if ( j === il ) j = 0;
  18406. if ( k === il ) k = 0;
  18407. // (j)---(i)---(k)
  18408. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18409. }
  18410. holesMovements.push( oneHoleMovements );
  18411. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18412. }
  18413. // Loop bevelSegments, 1 for the front, 1 for the back
  18414. for ( let b = 0; b < bevelSegments; b ++ ) {
  18415. //for ( b = bevelSegments; b > 0; b -- ) {
  18416. const t = b / bevelSegments;
  18417. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  18418. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  18419. // contract shape
  18420. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  18421. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18422. v( vert.x, vert.y, - z );
  18423. }
  18424. // expand holes
  18425. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18426. const ahole = holes[ h ];
  18427. oneHoleMovements = holesMovements[ h ];
  18428. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  18429. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18430. v( vert.x, vert.y, - z );
  18431. }
  18432. }
  18433. }
  18434. const bs = bevelSize + bevelOffset;
  18435. // Back facing vertices
  18436. for ( let i = 0; i < vlen; i ++ ) {
  18437. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18438. if ( ! extrudeByPath ) {
  18439. v( vert.x, vert.y, 0 );
  18440. } else {
  18441. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18442. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  18443. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  18444. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  18445. v( position2.x, position2.y, position2.z );
  18446. }
  18447. }
  18448. // Add stepped vertices...
  18449. // Including front facing vertices
  18450. for ( let s = 1; s <= steps; s ++ ) {
  18451. for ( let i = 0; i < vlen; i ++ ) {
  18452. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18453. if ( ! extrudeByPath ) {
  18454. v( vert.x, vert.y, depth / steps * s );
  18455. } else {
  18456. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18457. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  18458. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  18459. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  18460. v( position2.x, position2.y, position2.z );
  18461. }
  18462. }
  18463. }
  18464. // Add bevel segments planes
  18465. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18466. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  18467. const t = b / bevelSegments;
  18468. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  18469. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  18470. // contract shape
  18471. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  18472. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18473. v( vert.x, vert.y, depth + z );
  18474. }
  18475. // expand holes
  18476. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18477. const ahole = holes[ h ];
  18478. oneHoleMovements = holesMovements[ h ];
  18479. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  18480. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18481. if ( ! extrudeByPath ) {
  18482. v( vert.x, vert.y, depth + z );
  18483. } else {
  18484. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18485. }
  18486. }
  18487. }
  18488. }
  18489. /* Faces */
  18490. // Top and bottom faces
  18491. buildLidFaces();
  18492. // Sides faces
  18493. buildSideFaces();
  18494. ///// Internal functions
  18495. function buildLidFaces() {
  18496. const start = verticesArray.length / 3;
  18497. if ( bevelEnabled ) {
  18498. let layer = 0; // steps + 1
  18499. let offset = vlen * layer;
  18500. // Bottom faces
  18501. for ( let i = 0; i < flen; i ++ ) {
  18502. const face = faces[ i ];
  18503. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18504. }
  18505. layer = steps + bevelSegments * 2;
  18506. offset = vlen * layer;
  18507. // Top faces
  18508. for ( let i = 0; i < flen; i ++ ) {
  18509. const face = faces[ i ];
  18510. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18511. }
  18512. } else {
  18513. // Bottom faces
  18514. for ( let i = 0; i < flen; i ++ ) {
  18515. const face = faces[ i ];
  18516. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18517. }
  18518. // Top faces
  18519. for ( let i = 0; i < flen; i ++ ) {
  18520. const face = faces[ i ];
  18521. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18522. }
  18523. }
  18524. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  18525. }
  18526. // Create faces for the z-sides of the shape
  18527. function buildSideFaces() {
  18528. const start = verticesArray.length / 3;
  18529. let layeroffset = 0;
  18530. sidewalls( contour, layeroffset );
  18531. layeroffset += contour.length;
  18532. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  18533. const ahole = holes[ h ];
  18534. sidewalls( ahole, layeroffset );
  18535. //, true
  18536. layeroffset += ahole.length;
  18537. }
  18538. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  18539. }
  18540. function sidewalls( contour, layeroffset ) {
  18541. let i = contour.length;
  18542. while ( -- i >= 0 ) {
  18543. const j = i;
  18544. let k = i - 1;
  18545. if ( k < 0 ) k = contour.length - 1;
  18546. //console.log('b', i,j, i-1, k,vertices.length);
  18547. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  18548. const slen1 = vlen * s;
  18549. const slen2 = vlen * ( s + 1 );
  18550. const a = layeroffset + j + slen1,
  18551. b = layeroffset + k + slen1,
  18552. c = layeroffset + k + slen2,
  18553. d = layeroffset + j + slen2;
  18554. f4( a, b, c, d );
  18555. }
  18556. }
  18557. }
  18558. function v( x, y, z ) {
  18559. placeholder.push( x );
  18560. placeholder.push( y );
  18561. placeholder.push( z );
  18562. }
  18563. function f3( a, b, c ) {
  18564. addVertex( a );
  18565. addVertex( b );
  18566. addVertex( c );
  18567. const nextIndex = verticesArray.length / 3;
  18568. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  18569. addUV( uvs[ 0 ] );
  18570. addUV( uvs[ 1 ] );
  18571. addUV( uvs[ 2 ] );
  18572. }
  18573. function f4( a, b, c, d ) {
  18574. addVertex( a );
  18575. addVertex( b );
  18576. addVertex( d );
  18577. addVertex( b );
  18578. addVertex( c );
  18579. addVertex( d );
  18580. const nextIndex = verticesArray.length / 3;
  18581. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  18582. addUV( uvs[ 0 ] );
  18583. addUV( uvs[ 1 ] );
  18584. addUV( uvs[ 3 ] );
  18585. addUV( uvs[ 1 ] );
  18586. addUV( uvs[ 2 ] );
  18587. addUV( uvs[ 3 ] );
  18588. }
  18589. function addVertex( index ) {
  18590. verticesArray.push( placeholder[ index * 3 + 0 ] );
  18591. verticesArray.push( placeholder[ index * 3 + 1 ] );
  18592. verticesArray.push( placeholder[ index * 3 + 2 ] );
  18593. }
  18594. function addUV( vector2 ) {
  18595. uvArray.push( vector2.x );
  18596. uvArray.push( vector2.y );
  18597. }
  18598. }
  18599. }
  18600. toJSON() {
  18601. const data = BufferGeometry.prototype.toJSON.call( this );
  18602. const shapes = this.parameters.shapes;
  18603. const options = this.parameters.options;
  18604. return toJSON( shapes, options, data );
  18605. }
  18606. }
  18607. const WorldUVGenerator = {
  18608. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  18609. const a_x = vertices[ indexA * 3 ];
  18610. const a_y = vertices[ indexA * 3 + 1 ];
  18611. const b_x = vertices[ indexB * 3 ];
  18612. const b_y = vertices[ indexB * 3 + 1 ];
  18613. const c_x = vertices[ indexC * 3 ];
  18614. const c_y = vertices[ indexC * 3 + 1 ];
  18615. return [
  18616. new Vector2( a_x, a_y ),
  18617. new Vector2( b_x, b_y ),
  18618. new Vector2( c_x, c_y )
  18619. ];
  18620. },
  18621. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  18622. const a_x = vertices[ indexA * 3 ];
  18623. const a_y = vertices[ indexA * 3 + 1 ];
  18624. const a_z = vertices[ indexA * 3 + 2 ];
  18625. const b_x = vertices[ indexB * 3 ];
  18626. const b_y = vertices[ indexB * 3 + 1 ];
  18627. const b_z = vertices[ indexB * 3 + 2 ];
  18628. const c_x = vertices[ indexC * 3 ];
  18629. const c_y = vertices[ indexC * 3 + 1 ];
  18630. const c_z = vertices[ indexC * 3 + 2 ];
  18631. const d_x = vertices[ indexD * 3 ];
  18632. const d_y = vertices[ indexD * 3 + 1 ];
  18633. const d_z = vertices[ indexD * 3 + 2 ];
  18634. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  18635. return [
  18636. new Vector2( a_x, 1 - a_z ),
  18637. new Vector2( b_x, 1 - b_z ),
  18638. new Vector2( c_x, 1 - c_z ),
  18639. new Vector2( d_x, 1 - d_z )
  18640. ];
  18641. } else {
  18642. return [
  18643. new Vector2( a_y, 1 - a_z ),
  18644. new Vector2( b_y, 1 - b_z ),
  18645. new Vector2( c_y, 1 - c_z ),
  18646. new Vector2( d_y, 1 - d_z )
  18647. ];
  18648. }
  18649. }
  18650. };
  18651. function toJSON( shapes, options, data ) {
  18652. data.shapes = [];
  18653. if ( Array.isArray( shapes ) ) {
  18654. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18655. const shape = shapes[ i ];
  18656. data.shapes.push( shape.uuid );
  18657. }
  18658. } else {
  18659. data.shapes.push( shapes.uuid );
  18660. }
  18661. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  18662. return data;
  18663. }
  18664. /**
  18665. * Creates extruded geometry from a path shape.
  18666. *
  18667. * parameters = {
  18668. *
  18669. * curveSegments: <int>, // number of points on the curves
  18670. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18671. * depth: <float>, // Depth to extrude the shape
  18672. *
  18673. * bevelEnabled: <bool>, // turn on bevel
  18674. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18675. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18676. * bevelOffset: <float>, // how far from shape outline does bevel start
  18677. * bevelSegments: <int>, // number of bevel layers
  18678. *
  18679. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18680. *
  18681. * UVGenerator: <Object> // object that provides UV generator functions
  18682. *
  18683. * }
  18684. */
  18685. class ExtrudeGeometry extends Geometry {
  18686. constructor( shapes, options ) {
  18687. super();
  18688. this.type = 'ExtrudeGeometry';
  18689. this.parameters = {
  18690. shapes: shapes,
  18691. options: options
  18692. };
  18693. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  18694. this.mergeVertices();
  18695. }
  18696. toJSON() {
  18697. const data = super.toJSON();
  18698. const shapes = this.parameters.shapes;
  18699. const options = this.parameters.options;
  18700. return toJSON$1( shapes, options, data );
  18701. }
  18702. }
  18703. function toJSON$1( shapes, options, data ) {
  18704. data.shapes = [];
  18705. if ( Array.isArray( shapes ) ) {
  18706. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18707. const shape = shapes[ i ];
  18708. data.shapes.push( shape.uuid );
  18709. }
  18710. } else {
  18711. data.shapes.push( shapes.uuid );
  18712. }
  18713. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  18714. return data;
  18715. }
  18716. class IcosahedronBufferGeometry extends PolyhedronBufferGeometry {
  18717. constructor( radius = 1, detail = 0 ) {
  18718. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18719. const vertices = [
  18720. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  18721. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  18722. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  18723. ];
  18724. const indices = [
  18725. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  18726. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  18727. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  18728. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  18729. ];
  18730. super( vertices, indices, radius, detail );
  18731. this.type = 'IcosahedronBufferGeometry';
  18732. this.parameters = {
  18733. radius: radius,
  18734. detail: detail
  18735. };
  18736. }
  18737. }
  18738. class IcosahedronGeometry extends Geometry {
  18739. constructor( radius, detail ) {
  18740. super();
  18741. this.type = 'IcosahedronGeometry';
  18742. this.parameters = {
  18743. radius: radius,
  18744. detail: detail
  18745. };
  18746. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  18747. this.mergeVertices();
  18748. }
  18749. }
  18750. class LatheBufferGeometry extends BufferGeometry {
  18751. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  18752. super();
  18753. this.type = 'LatheBufferGeometry';
  18754. this.parameters = {
  18755. points: points,
  18756. segments: segments,
  18757. phiStart: phiStart,
  18758. phiLength: phiLength
  18759. };
  18760. segments = Math.floor( segments );
  18761. // clamp phiLength so it's in range of [ 0, 2PI ]
  18762. phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
  18763. // buffers
  18764. const indices = [];
  18765. const vertices = [];
  18766. const uvs = [];
  18767. // helper variables
  18768. const inverseSegments = 1.0 / segments;
  18769. const vertex = new Vector3();
  18770. const uv = new Vector2();
  18771. // generate vertices and uvs
  18772. for ( let i = 0; i <= segments; i ++ ) {
  18773. const phi = phiStart + i * inverseSegments * phiLength;
  18774. const sin = Math.sin( phi );
  18775. const cos = Math.cos( phi );
  18776. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  18777. // vertex
  18778. vertex.x = points[ j ].x * sin;
  18779. vertex.y = points[ j ].y;
  18780. vertex.z = points[ j ].x * cos;
  18781. vertices.push( vertex.x, vertex.y, vertex.z );
  18782. // uv
  18783. uv.x = i / segments;
  18784. uv.y = j / ( points.length - 1 );
  18785. uvs.push( uv.x, uv.y );
  18786. }
  18787. }
  18788. // indices
  18789. for ( let i = 0; i < segments; i ++ ) {
  18790. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  18791. const base = j + i * points.length;
  18792. const a = base;
  18793. const b = base + points.length;
  18794. const c = base + points.length + 1;
  18795. const d = base + 1;
  18796. // faces
  18797. indices.push( a, b, d );
  18798. indices.push( b, c, d );
  18799. }
  18800. }
  18801. // build geometry
  18802. this.setIndex( indices );
  18803. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18804. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18805. // generate normals
  18806. this.computeVertexNormals();
  18807. // if the geometry is closed, we need to average the normals along the seam.
  18808. // because the corresponding vertices are identical (but still have different UVs).
  18809. if ( phiLength === Math.PI * 2 ) {
  18810. const normals = this.attributes.normal.array;
  18811. const n1 = new Vector3();
  18812. const n2 = new Vector3();
  18813. const n = new Vector3();
  18814. // this is the buffer offset for the last line of vertices
  18815. const base = segments * points.length * 3;
  18816. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  18817. // select the normal of the vertex in the first line
  18818. n1.x = normals[ j + 0 ];
  18819. n1.y = normals[ j + 1 ];
  18820. n1.z = normals[ j + 2 ];
  18821. // select the normal of the vertex in the last line
  18822. n2.x = normals[ base + j + 0 ];
  18823. n2.y = normals[ base + j + 1 ];
  18824. n2.z = normals[ base + j + 2 ];
  18825. // average normals
  18826. n.addVectors( n1, n2 ).normalize();
  18827. // assign the new values to both normals
  18828. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  18829. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  18830. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  18831. }
  18832. }
  18833. }
  18834. }
  18835. class LatheGeometry extends Geometry {
  18836. constructor( points, segments, phiStart, phiLength ) {
  18837. super();
  18838. this.type = 'LatheGeometry';
  18839. this.parameters = {
  18840. points: points,
  18841. segments: segments,
  18842. phiStart: phiStart,
  18843. phiLength: phiLength
  18844. };
  18845. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  18846. this.mergeVertices();
  18847. }
  18848. }
  18849. class OctahedronBufferGeometry extends PolyhedronBufferGeometry {
  18850. constructor( radius = 1, detail = 0 ) {
  18851. const vertices = [
  18852. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  18853. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  18854. ];
  18855. const indices = [
  18856. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  18857. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  18858. 1, 3, 4, 1, 4, 2
  18859. ];
  18860. super( vertices, indices, radius, detail );
  18861. this.type = 'OctahedronBufferGeometry';
  18862. this.parameters = {
  18863. radius: radius,
  18864. detail: detail
  18865. };
  18866. }
  18867. }
  18868. class OctahedronGeometry extends Geometry {
  18869. constructor( radius, detail ) {
  18870. super();
  18871. this.type = 'OctahedronGeometry';
  18872. this.parameters = {
  18873. radius: radius,
  18874. detail: detail
  18875. };
  18876. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  18877. this.mergeVertices();
  18878. }
  18879. }
  18880. /**
  18881. * Parametric Surfaces Geometry
  18882. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  18883. */
  18884. function ParametricBufferGeometry( func, slices, stacks ) {
  18885. BufferGeometry.call( this );
  18886. this.type = 'ParametricBufferGeometry';
  18887. this.parameters = {
  18888. func: func,
  18889. slices: slices,
  18890. stacks: stacks
  18891. };
  18892. // buffers
  18893. const indices = [];
  18894. const vertices = [];
  18895. const normals = [];
  18896. const uvs = [];
  18897. const EPS = 0.00001;
  18898. const normal = new Vector3();
  18899. const p0 = new Vector3(), p1 = new Vector3();
  18900. const pu = new Vector3(), pv = new Vector3();
  18901. if ( func.length < 3 ) {
  18902. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  18903. }
  18904. // generate vertices, normals and uvs
  18905. const sliceCount = slices + 1;
  18906. for ( let i = 0; i <= stacks; i ++ ) {
  18907. const v = i / stacks;
  18908. for ( let j = 0; j <= slices; j ++ ) {
  18909. const u = j / slices;
  18910. // vertex
  18911. func( u, v, p0 );
  18912. vertices.push( p0.x, p0.y, p0.z );
  18913. // normal
  18914. // approximate tangent vectors via finite differences
  18915. if ( u - EPS >= 0 ) {
  18916. func( u - EPS, v, p1 );
  18917. pu.subVectors( p0, p1 );
  18918. } else {
  18919. func( u + EPS, v, p1 );
  18920. pu.subVectors( p1, p0 );
  18921. }
  18922. if ( v - EPS >= 0 ) {
  18923. func( u, v - EPS, p1 );
  18924. pv.subVectors( p0, p1 );
  18925. } else {
  18926. func( u, v + EPS, p1 );
  18927. pv.subVectors( p1, p0 );
  18928. }
  18929. // cross product of tangent vectors returns surface normal
  18930. normal.crossVectors( pu, pv ).normalize();
  18931. normals.push( normal.x, normal.y, normal.z );
  18932. // uv
  18933. uvs.push( u, v );
  18934. }
  18935. }
  18936. // generate indices
  18937. for ( let i = 0; i < stacks; i ++ ) {
  18938. for ( let j = 0; j < slices; j ++ ) {
  18939. const a = i * sliceCount + j;
  18940. const b = i * sliceCount + j + 1;
  18941. const c = ( i + 1 ) * sliceCount + j + 1;
  18942. const d = ( i + 1 ) * sliceCount + j;
  18943. // faces one and two
  18944. indices.push( a, b, d );
  18945. indices.push( b, c, d );
  18946. }
  18947. }
  18948. // build geometry
  18949. this.setIndex( indices );
  18950. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18951. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18952. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18953. }
  18954. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18955. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18956. /**
  18957. * Parametric Surfaces Geometry
  18958. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  18959. */
  18960. function ParametricGeometry( func, slices, stacks ) {
  18961. Geometry.call( this );
  18962. this.type = 'ParametricGeometry';
  18963. this.parameters = {
  18964. func: func,
  18965. slices: slices,
  18966. stacks: stacks
  18967. };
  18968. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  18969. this.mergeVertices();
  18970. }
  18971. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  18972. ParametricGeometry.prototype.constructor = ParametricGeometry;
  18973. class PlaneGeometry extends Geometry {
  18974. constructor( width, height, widthSegments, heightSegments ) {
  18975. super();
  18976. this.type = 'PlaneGeometry';
  18977. this.parameters = {
  18978. width: width,
  18979. height: height,
  18980. widthSegments: widthSegments,
  18981. heightSegments: heightSegments
  18982. };
  18983. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  18984. this.mergeVertices();
  18985. }
  18986. }
  18987. class PolyhedronGeometry extends Geometry {
  18988. constructor( vertices, indices, radius, detail ) {
  18989. super();
  18990. this.type = 'PolyhedronGeometry';
  18991. this.parameters = {
  18992. vertices: vertices,
  18993. indices: indices,
  18994. radius: radius,
  18995. detail: detail
  18996. };
  18997. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  18998. this.mergeVertices();
  18999. }
  19000. }
  19001. class RingBufferGeometry extends BufferGeometry {
  19002. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19003. super();
  19004. this.type = 'RingBufferGeometry';
  19005. this.parameters = {
  19006. innerRadius: innerRadius,
  19007. outerRadius: outerRadius,
  19008. thetaSegments: thetaSegments,
  19009. phiSegments: phiSegments,
  19010. thetaStart: thetaStart,
  19011. thetaLength: thetaLength
  19012. };
  19013. thetaSegments = Math.max( 3, thetaSegments );
  19014. phiSegments = Math.max( 1, phiSegments );
  19015. // buffers
  19016. const indices = [];
  19017. const vertices = [];
  19018. const normals = [];
  19019. const uvs = [];
  19020. // some helper variables
  19021. let radius = innerRadius;
  19022. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19023. const vertex = new Vector3();
  19024. const uv = new Vector2();
  19025. // generate vertices, normals and uvs
  19026. for ( let j = 0; j <= phiSegments; j ++ ) {
  19027. for ( let i = 0; i <= thetaSegments; i ++ ) {
  19028. // values are generate from the inside of the ring to the outside
  19029. const segment = thetaStart + i / thetaSegments * thetaLength;
  19030. // vertex
  19031. vertex.x = radius * Math.cos( segment );
  19032. vertex.y = radius * Math.sin( segment );
  19033. vertices.push( vertex.x, vertex.y, vertex.z );
  19034. // normal
  19035. normals.push( 0, 0, 1 );
  19036. // uv
  19037. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  19038. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  19039. uvs.push( uv.x, uv.y );
  19040. }
  19041. // increase the radius for next row of vertices
  19042. radius += radiusStep;
  19043. }
  19044. // indices
  19045. for ( let j = 0; j < phiSegments; j ++ ) {
  19046. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  19047. for ( let i = 0; i < thetaSegments; i ++ ) {
  19048. const segment = i + thetaSegmentLevel;
  19049. const a = segment;
  19050. const b = segment + thetaSegments + 1;
  19051. const c = segment + thetaSegments + 2;
  19052. const d = segment + 1;
  19053. // faces
  19054. indices.push( a, b, d );
  19055. indices.push( b, c, d );
  19056. }
  19057. }
  19058. // build geometry
  19059. this.setIndex( indices );
  19060. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19061. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19062. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19063. }
  19064. }
  19065. class RingGeometry extends Geometry {
  19066. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19067. super();
  19068. this.type = 'RingGeometry';
  19069. this.parameters = {
  19070. innerRadius: innerRadius,
  19071. outerRadius: outerRadius,
  19072. thetaSegments: thetaSegments,
  19073. phiSegments: phiSegments,
  19074. thetaStart: thetaStart,
  19075. thetaLength: thetaLength
  19076. };
  19077. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  19078. this.mergeVertices();
  19079. }
  19080. }
  19081. class ShapeBufferGeometry extends BufferGeometry {
  19082. constructor( shapes, curveSegments = 12 ) {
  19083. super();
  19084. this.type = 'ShapeBufferGeometry';
  19085. this.parameters = {
  19086. shapes: shapes,
  19087. curveSegments: curveSegments
  19088. };
  19089. // buffers
  19090. const indices = [];
  19091. const vertices = [];
  19092. const normals = [];
  19093. const uvs = [];
  19094. // helper variables
  19095. let groupStart = 0;
  19096. let groupCount = 0;
  19097. // allow single and array values for "shapes" parameter
  19098. if ( Array.isArray( shapes ) === false ) {
  19099. addShape( shapes );
  19100. } else {
  19101. for ( let i = 0; i < shapes.length; i ++ ) {
  19102. addShape( shapes[ i ] );
  19103. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  19104. groupStart += groupCount;
  19105. groupCount = 0;
  19106. }
  19107. }
  19108. // build geometry
  19109. this.setIndex( indices );
  19110. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19111. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19112. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19113. // helper functions
  19114. function addShape( shape ) {
  19115. const indexOffset = vertices.length / 3;
  19116. const points = shape.extractPoints( curveSegments );
  19117. let shapeVertices = points.shape;
  19118. const shapeHoles = points.holes;
  19119. // check direction of vertices
  19120. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  19121. shapeVertices = shapeVertices.reverse();
  19122. }
  19123. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19124. const shapeHole = shapeHoles[ i ];
  19125. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  19126. shapeHoles[ i ] = shapeHole.reverse();
  19127. }
  19128. }
  19129. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  19130. // join vertices of inner and outer paths to a single array
  19131. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19132. const shapeHole = shapeHoles[ i ];
  19133. shapeVertices = shapeVertices.concat( shapeHole );
  19134. }
  19135. // vertices, normals, uvs
  19136. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  19137. const vertex = shapeVertices[ i ];
  19138. vertices.push( vertex.x, vertex.y, 0 );
  19139. normals.push( 0, 0, 1 );
  19140. uvs.push( vertex.x, vertex.y ); // world uvs
  19141. }
  19142. // incides
  19143. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  19144. const face = faces[ i ];
  19145. const a = face[ 0 ] + indexOffset;
  19146. const b = face[ 1 ] + indexOffset;
  19147. const c = face[ 2 ] + indexOffset;
  19148. indices.push( a, b, c );
  19149. groupCount += 3;
  19150. }
  19151. }
  19152. }
  19153. toJSON() {
  19154. const data = BufferGeometry.prototype.toJSON.call( this );
  19155. const shapes = this.parameters.shapes;
  19156. return toJSON$2( shapes, data );
  19157. }
  19158. }
  19159. function toJSON$2( shapes, data ) {
  19160. data.shapes = [];
  19161. if ( Array.isArray( shapes ) ) {
  19162. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19163. const shape = shapes[ i ];
  19164. data.shapes.push( shape.uuid );
  19165. }
  19166. } else {
  19167. data.shapes.push( shapes.uuid );
  19168. }
  19169. return data;
  19170. }
  19171. class ShapeGeometry extends Geometry {
  19172. constructor( shapes, curveSegments ) {
  19173. super();
  19174. this.type = 'ShapeGeometry';
  19175. if ( typeof curveSegments === 'object' ) {
  19176. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  19177. curveSegments = curveSegments.curveSegments;
  19178. }
  19179. this.parameters = {
  19180. shapes: shapes,
  19181. curveSegments: curveSegments
  19182. };
  19183. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  19184. this.mergeVertices();
  19185. }
  19186. toJSON() {
  19187. const data = Geometry.prototype.toJSON.call( this );
  19188. const shapes = this.parameters.shapes;
  19189. return toJSON$3( shapes, data );
  19190. }
  19191. }
  19192. function toJSON$3( shapes, data ) {
  19193. data.shapes = [];
  19194. if ( Array.isArray( shapes ) ) {
  19195. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19196. const shape = shapes[ i ];
  19197. data.shapes.push( shape.uuid );
  19198. }
  19199. } else {
  19200. data.shapes.push( shapes.uuid );
  19201. }
  19202. return data;
  19203. }
  19204. class SphereBufferGeometry extends BufferGeometry {
  19205. constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  19206. super();
  19207. this.type = 'SphereBufferGeometry';
  19208. this.parameters = {
  19209. radius: radius,
  19210. widthSegments: widthSegments,
  19211. heightSegments: heightSegments,
  19212. phiStart: phiStart,
  19213. phiLength: phiLength,
  19214. thetaStart: thetaStart,
  19215. thetaLength: thetaLength
  19216. };
  19217. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  19218. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  19219. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  19220. let index = 0;
  19221. const grid = [];
  19222. const vertex = new Vector3();
  19223. const normal = new Vector3();
  19224. // buffers
  19225. const indices = [];
  19226. const vertices = [];
  19227. const normals = [];
  19228. const uvs = [];
  19229. // generate vertices, normals and uvs
  19230. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  19231. const verticesRow = [];
  19232. const v = iy / heightSegments;
  19233. // special case for the poles
  19234. let uOffset = 0;
  19235. if ( iy == 0 && thetaStart == 0 ) {
  19236. uOffset = 0.5 / widthSegments;
  19237. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  19238. uOffset = - 0.5 / widthSegments;
  19239. }
  19240. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  19241. const u = ix / widthSegments;
  19242. // vertex
  19243. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19244. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19245. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19246. vertices.push( vertex.x, vertex.y, vertex.z );
  19247. // normal
  19248. normal.copy( vertex ).normalize();
  19249. normals.push( normal.x, normal.y, normal.z );
  19250. // uv
  19251. uvs.push( u + uOffset, 1 - v );
  19252. verticesRow.push( index ++ );
  19253. }
  19254. grid.push( verticesRow );
  19255. }
  19256. // indices
  19257. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  19258. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  19259. const a = grid[ iy ][ ix + 1 ];
  19260. const b = grid[ iy ][ ix ];
  19261. const c = grid[ iy + 1 ][ ix ];
  19262. const d = grid[ iy + 1 ][ ix + 1 ];
  19263. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  19264. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  19265. }
  19266. }
  19267. // build geometry
  19268. this.setIndex( indices );
  19269. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19270. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19271. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19272. }
  19273. }
  19274. class SphereGeometry extends Geometry {
  19275. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19276. super();
  19277. this.type = 'SphereGeometry';
  19278. this.parameters = {
  19279. radius: radius,
  19280. widthSegments: widthSegments,
  19281. heightSegments: heightSegments,
  19282. phiStart: phiStart,
  19283. phiLength: phiLength,
  19284. thetaStart: thetaStart,
  19285. thetaLength: thetaLength
  19286. };
  19287. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  19288. this.mergeVertices();
  19289. }
  19290. }
  19291. class TetrahedronBufferGeometry extends PolyhedronBufferGeometry {
  19292. constructor( radius = 1, detail = 0 ) {
  19293. const vertices = [
  19294. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19295. ];
  19296. const indices = [
  19297. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19298. ];
  19299. super( vertices, indices, radius, detail );
  19300. this.type = 'TetrahedronBufferGeometry';
  19301. this.parameters = {
  19302. radius: radius,
  19303. detail: detail
  19304. };
  19305. }
  19306. }
  19307. class TetrahedronGeometry extends Geometry {
  19308. constructor( radius, detail ) {
  19309. super();
  19310. this.type = 'TetrahedronGeometry';
  19311. this.parameters = {
  19312. radius: radius,
  19313. detail: detail
  19314. };
  19315. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  19316. this.mergeVertices();
  19317. }
  19318. }
  19319. /**
  19320. * Text = 3D Text
  19321. *
  19322. * parameters = {
  19323. * font: <THREE.Font>, // font
  19324. *
  19325. * size: <float>, // size of the text
  19326. * height: <float>, // thickness to extrude text
  19327. * curveSegments: <int>, // number of points on the curves
  19328. *
  19329. * bevelEnabled: <bool>, // turn on bevel
  19330. * bevelThickness: <float>, // how deep into text bevel goes
  19331. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19332. * bevelOffset: <float> // how far from text outline does bevel start
  19333. * }
  19334. */
  19335. class TextBufferGeometry extends ExtrudeBufferGeometry {
  19336. constructor( text, parameters = {} ) {
  19337. const font = parameters.font;
  19338. if ( ! ( font && font.isFont ) ) {
  19339. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  19340. return new BufferGeometry();
  19341. }
  19342. const shapes = font.generateShapes( text, parameters.size );
  19343. // translate parameters to ExtrudeGeometry API
  19344. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  19345. // defaults
  19346. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19347. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19348. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19349. super( shapes, parameters );
  19350. this.type = 'TextBufferGeometry';
  19351. }
  19352. }
  19353. /**
  19354. * Text = 3D Text
  19355. *
  19356. * parameters = {
  19357. * font: <THREE.Font>, // font
  19358. *
  19359. * size: <float>, // size of the text
  19360. * height: <float>, // thickness to extrude text
  19361. * curveSegments: <int>, // number of points on the curves
  19362. *
  19363. * bevelEnabled: <bool>, // turn on bevel
  19364. * bevelThickness: <float>, // how deep into text bevel goes
  19365. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19366. * bevelOffset: <float> // how far from text outline does bevel start
  19367. * }
  19368. */
  19369. class TextGeometry extends Geometry {
  19370. constructor( text, parameters ) {
  19371. super();
  19372. this.type = 'TextGeometry';
  19373. this.parameters = {
  19374. text: text,
  19375. parameters: parameters
  19376. };
  19377. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  19378. this.mergeVertices();
  19379. }
  19380. }
  19381. class TorusBufferGeometry extends BufferGeometry {
  19382. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  19383. super();
  19384. this.type = 'TorusBufferGeometry';
  19385. this.parameters = {
  19386. radius: radius,
  19387. tube: tube,
  19388. radialSegments: radialSegments,
  19389. tubularSegments: tubularSegments,
  19390. arc: arc
  19391. };
  19392. radialSegments = Math.floor( radialSegments );
  19393. tubularSegments = Math.floor( tubularSegments );
  19394. // buffers
  19395. const indices = [];
  19396. const vertices = [];
  19397. const normals = [];
  19398. const uvs = [];
  19399. // helper variables
  19400. const center = new Vector3();
  19401. const vertex = new Vector3();
  19402. const normal = new Vector3();
  19403. // generate vertices, normals and uvs
  19404. for ( let j = 0; j <= radialSegments; j ++ ) {
  19405. for ( let i = 0; i <= tubularSegments; i ++ ) {
  19406. const u = i / tubularSegments * arc;
  19407. const v = j / radialSegments * Math.PI * 2;
  19408. // vertex
  19409. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19410. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19411. vertex.z = tube * Math.sin( v );
  19412. vertices.push( vertex.x, vertex.y, vertex.z );
  19413. // normal
  19414. center.x = radius * Math.cos( u );
  19415. center.y = radius * Math.sin( u );
  19416. normal.subVectors( vertex, center ).normalize();
  19417. normals.push( normal.x, normal.y, normal.z );
  19418. // uv
  19419. uvs.push( i / tubularSegments );
  19420. uvs.push( j / radialSegments );
  19421. }
  19422. }
  19423. // generate indices
  19424. for ( let j = 1; j <= radialSegments; j ++ ) {
  19425. for ( let i = 1; i <= tubularSegments; i ++ ) {
  19426. // indices
  19427. const a = ( tubularSegments + 1 ) * j + i - 1;
  19428. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19429. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19430. const d = ( tubularSegments + 1 ) * j + i;
  19431. // faces
  19432. indices.push( a, b, d );
  19433. indices.push( b, c, d );
  19434. }
  19435. }
  19436. // build geometry
  19437. this.setIndex( indices );
  19438. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19439. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19440. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19441. }
  19442. }
  19443. class TorusGeometry extends Geometry {
  19444. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  19445. super();
  19446. this.type = 'TorusGeometry';
  19447. this.parameters = {
  19448. radius: radius,
  19449. tube: tube,
  19450. radialSegments: radialSegments,
  19451. tubularSegments: tubularSegments,
  19452. arc: arc
  19453. };
  19454. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  19455. this.mergeVertices();
  19456. }
  19457. }
  19458. class TorusKnotBufferGeometry extends BufferGeometry {
  19459. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  19460. super();
  19461. this.type = 'TorusKnotBufferGeometry';
  19462. this.parameters = {
  19463. radius: radius,
  19464. tube: tube,
  19465. tubularSegments: tubularSegments,
  19466. radialSegments: radialSegments,
  19467. p: p,
  19468. q: q
  19469. };
  19470. tubularSegments = Math.floor( tubularSegments );
  19471. radialSegments = Math.floor( radialSegments );
  19472. // buffers
  19473. const indices = [];
  19474. const vertices = [];
  19475. const normals = [];
  19476. const uvs = [];
  19477. // helper variables
  19478. const vertex = new Vector3();
  19479. const normal = new Vector3();
  19480. const P1 = new Vector3();
  19481. const P2 = new Vector3();
  19482. const B = new Vector3();
  19483. const T = new Vector3();
  19484. const N = new Vector3();
  19485. // generate vertices, normals and uvs
  19486. for ( let i = 0; i <= tubularSegments; ++ i ) {
  19487. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19488. const u = i / tubularSegments * p * Math.PI * 2;
  19489. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  19490. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19491. calculatePositionOnCurve( u, p, q, radius, P1 );
  19492. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  19493. // calculate orthonormal basis
  19494. T.subVectors( P2, P1 );
  19495. N.addVectors( P2, P1 );
  19496. B.crossVectors( T, N );
  19497. N.crossVectors( B, T );
  19498. // normalize B, N. T can be ignored, we don't use it
  19499. B.normalize();
  19500. N.normalize();
  19501. for ( let j = 0; j <= radialSegments; ++ j ) {
  19502. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19503. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19504. const v = j / radialSegments * Math.PI * 2;
  19505. const cx = - tube * Math.cos( v );
  19506. const cy = tube * Math.sin( v );
  19507. // now calculate the final vertex position.
  19508. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19509. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  19510. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  19511. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  19512. vertices.push( vertex.x, vertex.y, vertex.z );
  19513. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  19514. normal.subVectors( vertex, P1 ).normalize();
  19515. normals.push( normal.x, normal.y, normal.z );
  19516. // uv
  19517. uvs.push( i / tubularSegments );
  19518. uvs.push( j / radialSegments );
  19519. }
  19520. }
  19521. // generate indices
  19522. for ( let j = 1; j <= tubularSegments; j ++ ) {
  19523. for ( let i = 1; i <= radialSegments; i ++ ) {
  19524. // indices
  19525. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19526. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  19527. const c = ( radialSegments + 1 ) * j + i;
  19528. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19529. // faces
  19530. indices.push( a, b, d );
  19531. indices.push( b, c, d );
  19532. }
  19533. }
  19534. // build geometry
  19535. this.setIndex( indices );
  19536. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19537. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19538. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19539. // this function calculates the current position on the torus curve
  19540. function calculatePositionOnCurve( u, p, q, radius, position ) {
  19541. const cu = Math.cos( u );
  19542. const su = Math.sin( u );
  19543. const quOverP = q / p * u;
  19544. const cs = Math.cos( quOverP );
  19545. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  19546. position.y = radius * ( 2 + cs ) * su * 0.5;
  19547. position.z = radius * Math.sin( quOverP ) * 0.5;
  19548. }
  19549. }
  19550. }
  19551. class TorusKnotGeometry extends Geometry {
  19552. constructor( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  19553. super();
  19554. this.type = 'TorusKnotGeometry';
  19555. this.parameters = {
  19556. radius: radius,
  19557. tube: tube,
  19558. tubularSegments: tubularSegments,
  19559. radialSegments: radialSegments,
  19560. p: p,
  19561. q: q
  19562. };
  19563. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  19564. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  19565. this.mergeVertices();
  19566. }
  19567. }
  19568. class TubeBufferGeometry extends BufferGeometry {
  19569. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  19570. super();
  19571. this.type = 'TubeBufferGeometry';
  19572. this.parameters = {
  19573. path: path,
  19574. tubularSegments: tubularSegments,
  19575. radius: radius,
  19576. radialSegments: radialSegments,
  19577. closed: closed
  19578. };
  19579. const frames = path.computeFrenetFrames( tubularSegments, closed );
  19580. // expose internals
  19581. this.tangents = frames.tangents;
  19582. this.normals = frames.normals;
  19583. this.binormals = frames.binormals;
  19584. // helper variables
  19585. const vertex = new Vector3();
  19586. const normal = new Vector3();
  19587. const uv = new Vector2();
  19588. let P = new Vector3();
  19589. // buffer
  19590. const vertices = [];
  19591. const normals = [];
  19592. const uvs = [];
  19593. const indices = [];
  19594. // create buffer data
  19595. generateBufferData();
  19596. // build geometry
  19597. this.setIndex( indices );
  19598. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19599. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19600. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19601. // functions
  19602. function generateBufferData() {
  19603. for ( let i = 0; i < tubularSegments; i ++ ) {
  19604. generateSegment( i );
  19605. }
  19606. // if the geometry is not closed, generate the last row of vertices and normals
  19607. // at the regular position on the given path
  19608. //
  19609. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19610. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  19611. // uvs are generated in a separate function.
  19612. // this makes it easy compute correct values for closed geometries
  19613. generateUVs();
  19614. // finally create faces
  19615. generateIndices();
  19616. }
  19617. function generateSegment( i ) {
  19618. // we use getPointAt to sample evenly distributed points from the given path
  19619. P = path.getPointAt( i / tubularSegments, P );
  19620. // retrieve corresponding normal and binormal
  19621. const N = frames.normals[ i ];
  19622. const B = frames.binormals[ i ];
  19623. // generate normals and vertices for the current segment
  19624. for ( let j = 0; j <= radialSegments; j ++ ) {
  19625. const v = j / radialSegments * Math.PI * 2;
  19626. const sin = Math.sin( v );
  19627. const cos = - Math.cos( v );
  19628. // normal
  19629. normal.x = ( cos * N.x + sin * B.x );
  19630. normal.y = ( cos * N.y + sin * B.y );
  19631. normal.z = ( cos * N.z + sin * B.z );
  19632. normal.normalize();
  19633. normals.push( normal.x, normal.y, normal.z );
  19634. // vertex
  19635. vertex.x = P.x + radius * normal.x;
  19636. vertex.y = P.y + radius * normal.y;
  19637. vertex.z = P.z + radius * normal.z;
  19638. vertices.push( vertex.x, vertex.y, vertex.z );
  19639. }
  19640. }
  19641. function generateIndices() {
  19642. for ( let j = 1; j <= tubularSegments; j ++ ) {
  19643. for ( let i = 1; i <= radialSegments; i ++ ) {
  19644. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19645. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  19646. const c = ( radialSegments + 1 ) * j + i;
  19647. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19648. // faces
  19649. indices.push( a, b, d );
  19650. indices.push( b, c, d );
  19651. }
  19652. }
  19653. }
  19654. function generateUVs() {
  19655. for ( let i = 0; i <= tubularSegments; i ++ ) {
  19656. for ( let j = 0; j <= radialSegments; j ++ ) {
  19657. uv.x = i / tubularSegments;
  19658. uv.y = j / radialSegments;
  19659. uvs.push( uv.x, uv.y );
  19660. }
  19661. }
  19662. }
  19663. }
  19664. toJSON() {
  19665. const data = BufferGeometry.prototype.toJSON.call( this );
  19666. data.path = this.parameters.path.toJSON();
  19667. return data;
  19668. }
  19669. }
  19670. class TubeGeometry extends Geometry {
  19671. constructor( path, tubularSegments, radius, radialSegments, closed, taper ) {
  19672. super();
  19673. this.type = 'TubeGeometry';
  19674. this.parameters = {
  19675. path: path,
  19676. tubularSegments: tubularSegments,
  19677. radius: radius,
  19678. radialSegments: radialSegments,
  19679. closed: closed
  19680. };
  19681. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  19682. const bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  19683. // expose internals
  19684. this.tangents = bufferGeometry.tangents;
  19685. this.normals = bufferGeometry.normals;
  19686. this.binormals = bufferGeometry.binormals;
  19687. // create geometry
  19688. this.fromBufferGeometry( bufferGeometry );
  19689. this.mergeVertices();
  19690. }
  19691. }
  19692. class WireframeGeometry extends BufferGeometry {
  19693. constructor( geometry ) {
  19694. super();
  19695. this.type = 'WireframeGeometry';
  19696. // buffer
  19697. const vertices = [];
  19698. // helper variables
  19699. const edge = [ 0, 0 ], edges = {};
  19700. const keys = [ 'a', 'b', 'c' ];
  19701. // different logic for Geometry and BufferGeometry
  19702. if ( geometry && geometry.isGeometry ) {
  19703. // create a data structure that contains all edges without duplicates
  19704. const faces = geometry.faces;
  19705. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  19706. const face = faces[ i ];
  19707. for ( let j = 0; j < 3; j ++ ) {
  19708. const edge1 = face[ keys[ j ] ];
  19709. const edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  19710. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19711. edge[ 1 ] = Math.max( edge1, edge2 );
  19712. const key = edge[ 0 ] + ',' + edge[ 1 ];
  19713. if ( edges[ key ] === undefined ) {
  19714. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19715. }
  19716. }
  19717. }
  19718. // generate vertices
  19719. for ( const key in edges ) {
  19720. const e = edges[ key ];
  19721. let vertex = geometry.vertices[ e.index1 ];
  19722. vertices.push( vertex.x, vertex.y, vertex.z );
  19723. vertex = geometry.vertices[ e.index2 ];
  19724. vertices.push( vertex.x, vertex.y, vertex.z );
  19725. }
  19726. } else if ( geometry && geometry.isBufferGeometry ) {
  19727. const vertex = new Vector3();
  19728. if ( geometry.index !== null ) {
  19729. // indexed BufferGeometry
  19730. const position = geometry.attributes.position;
  19731. const indices = geometry.index;
  19732. let groups = geometry.groups;
  19733. if ( groups.length === 0 ) {
  19734. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  19735. }
  19736. // create a data structure that contains all eges without duplicates
  19737. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  19738. const group = groups[ o ];
  19739. const start = group.start;
  19740. const count = group.count;
  19741. for ( let i = start, l = ( start + count ); i < l; i += 3 ) {
  19742. for ( let j = 0; j < 3; j ++ ) {
  19743. const edge1 = indices.getX( i + j );
  19744. const edge2 = indices.getX( i + ( j + 1 ) % 3 );
  19745. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19746. edge[ 1 ] = Math.max( edge1, edge2 );
  19747. const key = edge[ 0 ] + ',' + edge[ 1 ];
  19748. if ( edges[ key ] === undefined ) {
  19749. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19750. }
  19751. }
  19752. }
  19753. }
  19754. // generate vertices
  19755. for ( const key in edges ) {
  19756. const e = edges[ key ];
  19757. vertex.fromBufferAttribute( position, e.index1 );
  19758. vertices.push( vertex.x, vertex.y, vertex.z );
  19759. vertex.fromBufferAttribute( position, e.index2 );
  19760. vertices.push( vertex.x, vertex.y, vertex.z );
  19761. }
  19762. } else {
  19763. // non-indexed BufferGeometry
  19764. const position = geometry.attributes.position;
  19765. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  19766. for ( let j = 0; j < 3; j ++ ) {
  19767. // three edges per triangle, an edge is represented as (index1, index2)
  19768. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  19769. const index1 = 3 * i + j;
  19770. vertex.fromBufferAttribute( position, index1 );
  19771. vertices.push( vertex.x, vertex.y, vertex.z );
  19772. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  19773. vertex.fromBufferAttribute( position, index2 );
  19774. vertices.push( vertex.x, vertex.y, vertex.z );
  19775. }
  19776. }
  19777. }
  19778. }
  19779. // build geometry
  19780. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19781. }
  19782. }
  19783. var Geometries = /*#__PURE__*/Object.freeze({
  19784. __proto__: null,
  19785. BoxGeometry: BoxGeometry,
  19786. BoxBufferGeometry: BoxBufferGeometry,
  19787. CircleGeometry: CircleGeometry,
  19788. CircleBufferGeometry: CircleBufferGeometry,
  19789. ConeGeometry: ConeGeometry,
  19790. ConeBufferGeometry: ConeBufferGeometry,
  19791. CylinderGeometry: CylinderGeometry,
  19792. CylinderBufferGeometry: CylinderBufferGeometry,
  19793. DodecahedronGeometry: DodecahedronGeometry,
  19794. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  19795. EdgesGeometry: EdgesGeometry,
  19796. ExtrudeGeometry: ExtrudeGeometry,
  19797. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  19798. IcosahedronGeometry: IcosahedronGeometry,
  19799. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  19800. LatheGeometry: LatheGeometry,
  19801. LatheBufferGeometry: LatheBufferGeometry,
  19802. OctahedronGeometry: OctahedronGeometry,
  19803. OctahedronBufferGeometry: OctahedronBufferGeometry,
  19804. ParametricGeometry: ParametricGeometry,
  19805. ParametricBufferGeometry: ParametricBufferGeometry,
  19806. PlaneGeometry: PlaneGeometry,
  19807. PlaneBufferGeometry: PlaneBufferGeometry,
  19808. PolyhedronGeometry: PolyhedronGeometry,
  19809. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  19810. RingGeometry: RingGeometry,
  19811. RingBufferGeometry: RingBufferGeometry,
  19812. ShapeGeometry: ShapeGeometry,
  19813. ShapeBufferGeometry: ShapeBufferGeometry,
  19814. SphereGeometry: SphereGeometry,
  19815. SphereBufferGeometry: SphereBufferGeometry,
  19816. TetrahedronGeometry: TetrahedronGeometry,
  19817. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  19818. TextGeometry: TextGeometry,
  19819. TextBufferGeometry: TextBufferGeometry,
  19820. TorusGeometry: TorusGeometry,
  19821. TorusBufferGeometry: TorusBufferGeometry,
  19822. TorusKnotGeometry: TorusKnotGeometry,
  19823. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  19824. TubeGeometry: TubeGeometry,
  19825. TubeBufferGeometry: TubeBufferGeometry,
  19826. WireframeGeometry: WireframeGeometry
  19827. });
  19828. /**
  19829. * parameters = {
  19830. * color: <THREE.Color>
  19831. * }
  19832. */
  19833. function ShadowMaterial( parameters ) {
  19834. Material.call( this );
  19835. this.type = 'ShadowMaterial';
  19836. this.color = new Color( 0x000000 );
  19837. this.transparent = true;
  19838. this.setValues( parameters );
  19839. }
  19840. ShadowMaterial.prototype = Object.create( Material.prototype );
  19841. ShadowMaterial.prototype.constructor = ShadowMaterial;
  19842. ShadowMaterial.prototype.isShadowMaterial = true;
  19843. ShadowMaterial.prototype.copy = function ( source ) {
  19844. Material.prototype.copy.call( this, source );
  19845. this.color.copy( source.color );
  19846. return this;
  19847. };
  19848. function RawShaderMaterial( parameters ) {
  19849. ShaderMaterial.call( this, parameters );
  19850. this.type = 'RawShaderMaterial';
  19851. }
  19852. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  19853. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  19854. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19855. /**
  19856. * parameters = {
  19857. * color: <hex>,
  19858. * roughness: <float>,
  19859. * metalness: <float>,
  19860. * opacity: <float>,
  19861. *
  19862. * map: new THREE.Texture( <Image> ),
  19863. *
  19864. * lightMap: new THREE.Texture( <Image> ),
  19865. * lightMapIntensity: <float>
  19866. *
  19867. * aoMap: new THREE.Texture( <Image> ),
  19868. * aoMapIntensity: <float>
  19869. *
  19870. * emissive: <hex>,
  19871. * emissiveIntensity: <float>
  19872. * emissiveMap: new THREE.Texture( <Image> ),
  19873. *
  19874. * bumpMap: new THREE.Texture( <Image> ),
  19875. * bumpScale: <float>,
  19876. *
  19877. * normalMap: new THREE.Texture( <Image> ),
  19878. * normalMapType: THREE.TangentSpaceNormalMap,
  19879. * normalScale: <Vector2>,
  19880. *
  19881. * displacementMap: new THREE.Texture( <Image> ),
  19882. * displacementScale: <float>,
  19883. * displacementBias: <float>,
  19884. *
  19885. * roughnessMap: new THREE.Texture( <Image> ),
  19886. *
  19887. * metalnessMap: new THREE.Texture( <Image> ),
  19888. *
  19889. * alphaMap: new THREE.Texture( <Image> ),
  19890. *
  19891. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19892. * envMapIntensity: <float>
  19893. *
  19894. * refractionRatio: <float>,
  19895. *
  19896. * wireframe: <boolean>,
  19897. * wireframeLinewidth: <float>,
  19898. *
  19899. * skinning: <bool>,
  19900. * morphTargets: <bool>,
  19901. * morphNormals: <bool>
  19902. * }
  19903. */
  19904. function MeshStandardMaterial( parameters ) {
  19905. Material.call( this );
  19906. this.defines = { 'STANDARD': '' };
  19907. this.type = 'MeshStandardMaterial';
  19908. this.color = new Color( 0xffffff ); // diffuse
  19909. this.roughness = 1.0;
  19910. this.metalness = 0.0;
  19911. this.map = null;
  19912. this.lightMap = null;
  19913. this.lightMapIntensity = 1.0;
  19914. this.aoMap = null;
  19915. this.aoMapIntensity = 1.0;
  19916. this.emissive = new Color( 0x000000 );
  19917. this.emissiveIntensity = 1.0;
  19918. this.emissiveMap = null;
  19919. this.bumpMap = null;
  19920. this.bumpScale = 1;
  19921. this.normalMap = null;
  19922. this.normalMapType = TangentSpaceNormalMap;
  19923. this.normalScale = new Vector2( 1, 1 );
  19924. this.displacementMap = null;
  19925. this.displacementScale = 1;
  19926. this.displacementBias = 0;
  19927. this.roughnessMap = null;
  19928. this.metalnessMap = null;
  19929. this.alphaMap = null;
  19930. this.envMap = null;
  19931. this.envMapIntensity = 1.0;
  19932. this.refractionRatio = 0.98;
  19933. this.wireframe = false;
  19934. this.wireframeLinewidth = 1;
  19935. this.wireframeLinecap = 'round';
  19936. this.wireframeLinejoin = 'round';
  19937. this.skinning = false;
  19938. this.morphTargets = false;
  19939. this.morphNormals = false;
  19940. this.vertexTangents = false;
  19941. this.setValues( parameters );
  19942. }
  19943. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  19944. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  19945. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19946. MeshStandardMaterial.prototype.copy = function ( source ) {
  19947. Material.prototype.copy.call( this, source );
  19948. this.defines = { 'STANDARD': '' };
  19949. this.color.copy( source.color );
  19950. this.roughness = source.roughness;
  19951. this.metalness = source.metalness;
  19952. this.map = source.map;
  19953. this.lightMap = source.lightMap;
  19954. this.lightMapIntensity = source.lightMapIntensity;
  19955. this.aoMap = source.aoMap;
  19956. this.aoMapIntensity = source.aoMapIntensity;
  19957. this.emissive.copy( source.emissive );
  19958. this.emissiveMap = source.emissiveMap;
  19959. this.emissiveIntensity = source.emissiveIntensity;
  19960. this.bumpMap = source.bumpMap;
  19961. this.bumpScale = source.bumpScale;
  19962. this.normalMap = source.normalMap;
  19963. this.normalMapType = source.normalMapType;
  19964. this.normalScale.copy( source.normalScale );
  19965. this.displacementMap = source.displacementMap;
  19966. this.displacementScale = source.displacementScale;
  19967. this.displacementBias = source.displacementBias;
  19968. this.roughnessMap = source.roughnessMap;
  19969. this.metalnessMap = source.metalnessMap;
  19970. this.alphaMap = source.alphaMap;
  19971. this.envMap = source.envMap;
  19972. this.envMapIntensity = source.envMapIntensity;
  19973. this.refractionRatio = source.refractionRatio;
  19974. this.wireframe = source.wireframe;
  19975. this.wireframeLinewidth = source.wireframeLinewidth;
  19976. this.wireframeLinecap = source.wireframeLinecap;
  19977. this.wireframeLinejoin = source.wireframeLinejoin;
  19978. this.skinning = source.skinning;
  19979. this.morphTargets = source.morphTargets;
  19980. this.morphNormals = source.morphNormals;
  19981. this.vertexTangents = source.vertexTangents;
  19982. return this;
  19983. };
  19984. /**
  19985. * parameters = {
  19986. * clearcoat: <float>,
  19987. * clearcoatMap: new THREE.Texture( <Image> ),
  19988. * clearcoatRoughness: <float>,
  19989. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  19990. * clearcoatNormalScale: <Vector2>,
  19991. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19992. *
  19993. * reflectivity: <float>,
  19994. * ior: <float>,
  19995. *
  19996. * sheen: <Color>,
  19997. *
  19998. * transmission: <float>,
  19999. * transmissionMap: new THREE.Texture( <Image> )
  20000. * }
  20001. */
  20002. function MeshPhysicalMaterial( parameters ) {
  20003. MeshStandardMaterial.call( this );
  20004. this.defines = {
  20005. 'STANDARD': '',
  20006. 'PHYSICAL': ''
  20007. };
  20008. this.type = 'MeshPhysicalMaterial';
  20009. this.clearcoat = 0.0;
  20010. this.clearcoatMap = null;
  20011. this.clearcoatRoughness = 0.0;
  20012. this.clearcoatRoughnessMap = null;
  20013. this.clearcoatNormalScale = new Vector2( 1, 1 );
  20014. this.clearcoatNormalMap = null;
  20015. this.reflectivity = 0.5; // maps to F0 = 0.04
  20016. Object.defineProperty( this, 'ior', {
  20017. get: function () {
  20018. return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity );
  20019. },
  20020. set: function ( ior ) {
  20021. this.reflectivity = MathUtils.clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 );
  20022. }
  20023. } );
  20024. this.sheen = null; // null will disable sheen bsdf
  20025. this.transmission = 0.0;
  20026. this.transmissionMap = null;
  20027. this.setValues( parameters );
  20028. }
  20029. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  20030. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20031. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20032. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  20033. MeshStandardMaterial.prototype.copy.call( this, source );
  20034. this.defines = {
  20035. 'STANDARD': '',
  20036. 'PHYSICAL': ''
  20037. };
  20038. this.clearcoat = source.clearcoat;
  20039. this.clearcoatMap = source.clearcoatMap;
  20040. this.clearcoatRoughness = source.clearcoatRoughness;
  20041. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20042. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20043. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  20044. this.reflectivity = source.reflectivity;
  20045. if ( source.sheen ) {
  20046. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  20047. } else {
  20048. this.sheen = null;
  20049. }
  20050. this.transmission = source.transmission;
  20051. this.transmissionMap = source.transmissionMap;
  20052. return this;
  20053. };
  20054. /**
  20055. * parameters = {
  20056. * color: <hex>,
  20057. * specular: <hex>,
  20058. * shininess: <float>,
  20059. * opacity: <float>,
  20060. *
  20061. * map: new THREE.Texture( <Image> ),
  20062. *
  20063. * lightMap: new THREE.Texture( <Image> ),
  20064. * lightMapIntensity: <float>
  20065. *
  20066. * aoMap: new THREE.Texture( <Image> ),
  20067. * aoMapIntensity: <float>
  20068. *
  20069. * emissive: <hex>,
  20070. * emissiveIntensity: <float>
  20071. * emissiveMap: new THREE.Texture( <Image> ),
  20072. *
  20073. * bumpMap: new THREE.Texture( <Image> ),
  20074. * bumpScale: <float>,
  20075. *
  20076. * normalMap: new THREE.Texture( <Image> ),
  20077. * normalMapType: THREE.TangentSpaceNormalMap,
  20078. * normalScale: <Vector2>,
  20079. *
  20080. * displacementMap: new THREE.Texture( <Image> ),
  20081. * displacementScale: <float>,
  20082. * displacementBias: <float>,
  20083. *
  20084. * specularMap: new THREE.Texture( <Image> ),
  20085. *
  20086. * alphaMap: new THREE.Texture( <Image> ),
  20087. *
  20088. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20089. * combine: THREE.MultiplyOperation,
  20090. * reflectivity: <float>,
  20091. * refractionRatio: <float>,
  20092. *
  20093. * wireframe: <boolean>,
  20094. * wireframeLinewidth: <float>,
  20095. *
  20096. * skinning: <bool>,
  20097. * morphTargets: <bool>,
  20098. * morphNormals: <bool>
  20099. * }
  20100. */
  20101. function MeshPhongMaterial( parameters ) {
  20102. Material.call( this );
  20103. this.type = 'MeshPhongMaterial';
  20104. this.color = new Color( 0xffffff ); // diffuse
  20105. this.specular = new Color( 0x111111 );
  20106. this.shininess = 30;
  20107. this.map = null;
  20108. this.lightMap = null;
  20109. this.lightMapIntensity = 1.0;
  20110. this.aoMap = null;
  20111. this.aoMapIntensity = 1.0;
  20112. this.emissive = new Color( 0x000000 );
  20113. this.emissiveIntensity = 1.0;
  20114. this.emissiveMap = null;
  20115. this.bumpMap = null;
  20116. this.bumpScale = 1;
  20117. this.normalMap = null;
  20118. this.normalMapType = TangentSpaceNormalMap;
  20119. this.normalScale = new Vector2( 1, 1 );
  20120. this.displacementMap = null;
  20121. this.displacementScale = 1;
  20122. this.displacementBias = 0;
  20123. this.specularMap = null;
  20124. this.alphaMap = null;
  20125. this.envMap = null;
  20126. this.combine = MultiplyOperation;
  20127. this.reflectivity = 1;
  20128. this.refractionRatio = 0.98;
  20129. this.wireframe = false;
  20130. this.wireframeLinewidth = 1;
  20131. this.wireframeLinecap = 'round';
  20132. this.wireframeLinejoin = 'round';
  20133. this.skinning = false;
  20134. this.morphTargets = false;
  20135. this.morphNormals = false;
  20136. this.setValues( parameters );
  20137. }
  20138. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  20139. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20140. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20141. MeshPhongMaterial.prototype.copy = function ( source ) {
  20142. Material.prototype.copy.call( this, source );
  20143. this.color.copy( source.color );
  20144. this.specular.copy( source.specular );
  20145. this.shininess = source.shininess;
  20146. this.map = source.map;
  20147. this.lightMap = source.lightMap;
  20148. this.lightMapIntensity = source.lightMapIntensity;
  20149. this.aoMap = source.aoMap;
  20150. this.aoMapIntensity = source.aoMapIntensity;
  20151. this.emissive.copy( source.emissive );
  20152. this.emissiveMap = source.emissiveMap;
  20153. this.emissiveIntensity = source.emissiveIntensity;
  20154. this.bumpMap = source.bumpMap;
  20155. this.bumpScale = source.bumpScale;
  20156. this.normalMap = source.normalMap;
  20157. this.normalMapType = source.normalMapType;
  20158. this.normalScale.copy( source.normalScale );
  20159. this.displacementMap = source.displacementMap;
  20160. this.displacementScale = source.displacementScale;
  20161. this.displacementBias = source.displacementBias;
  20162. this.specularMap = source.specularMap;
  20163. this.alphaMap = source.alphaMap;
  20164. this.envMap = source.envMap;
  20165. this.combine = source.combine;
  20166. this.reflectivity = source.reflectivity;
  20167. this.refractionRatio = source.refractionRatio;
  20168. this.wireframe = source.wireframe;
  20169. this.wireframeLinewidth = source.wireframeLinewidth;
  20170. this.wireframeLinecap = source.wireframeLinecap;
  20171. this.wireframeLinejoin = source.wireframeLinejoin;
  20172. this.skinning = source.skinning;
  20173. this.morphTargets = source.morphTargets;
  20174. this.morphNormals = source.morphNormals;
  20175. return this;
  20176. };
  20177. /**
  20178. * parameters = {
  20179. * color: <hex>,
  20180. *
  20181. * map: new THREE.Texture( <Image> ),
  20182. * gradientMap: new THREE.Texture( <Image> ),
  20183. *
  20184. * lightMap: new THREE.Texture( <Image> ),
  20185. * lightMapIntensity: <float>
  20186. *
  20187. * aoMap: new THREE.Texture( <Image> ),
  20188. * aoMapIntensity: <float>
  20189. *
  20190. * emissive: <hex>,
  20191. * emissiveIntensity: <float>
  20192. * emissiveMap: new THREE.Texture( <Image> ),
  20193. *
  20194. * bumpMap: new THREE.Texture( <Image> ),
  20195. * bumpScale: <float>,
  20196. *
  20197. * normalMap: new THREE.Texture( <Image> ),
  20198. * normalMapType: THREE.TangentSpaceNormalMap,
  20199. * normalScale: <Vector2>,
  20200. *
  20201. * displacementMap: new THREE.Texture( <Image> ),
  20202. * displacementScale: <float>,
  20203. * displacementBias: <float>,
  20204. *
  20205. * alphaMap: new THREE.Texture( <Image> ),
  20206. *
  20207. * wireframe: <boolean>,
  20208. * wireframeLinewidth: <float>,
  20209. *
  20210. * skinning: <bool>,
  20211. * morphTargets: <bool>,
  20212. * morphNormals: <bool>
  20213. * }
  20214. */
  20215. function MeshToonMaterial( parameters ) {
  20216. Material.call( this );
  20217. this.defines = { 'TOON': '' };
  20218. this.type = 'MeshToonMaterial';
  20219. this.color = new Color( 0xffffff );
  20220. this.map = null;
  20221. this.gradientMap = null;
  20222. this.lightMap = null;
  20223. this.lightMapIntensity = 1.0;
  20224. this.aoMap = null;
  20225. this.aoMapIntensity = 1.0;
  20226. this.emissive = new Color( 0x000000 );
  20227. this.emissiveIntensity = 1.0;
  20228. this.emissiveMap = null;
  20229. this.bumpMap = null;
  20230. this.bumpScale = 1;
  20231. this.normalMap = null;
  20232. this.normalMapType = TangentSpaceNormalMap;
  20233. this.normalScale = new Vector2( 1, 1 );
  20234. this.displacementMap = null;
  20235. this.displacementScale = 1;
  20236. this.displacementBias = 0;
  20237. this.alphaMap = null;
  20238. this.wireframe = false;
  20239. this.wireframeLinewidth = 1;
  20240. this.wireframeLinecap = 'round';
  20241. this.wireframeLinejoin = 'round';
  20242. this.skinning = false;
  20243. this.morphTargets = false;
  20244. this.morphNormals = false;
  20245. this.setValues( parameters );
  20246. }
  20247. MeshToonMaterial.prototype = Object.create( Material.prototype );
  20248. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20249. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20250. MeshToonMaterial.prototype.copy = function ( source ) {
  20251. Material.prototype.copy.call( this, source );
  20252. this.color.copy( source.color );
  20253. this.map = source.map;
  20254. this.gradientMap = source.gradientMap;
  20255. this.lightMap = source.lightMap;
  20256. this.lightMapIntensity = source.lightMapIntensity;
  20257. this.aoMap = source.aoMap;
  20258. this.aoMapIntensity = source.aoMapIntensity;
  20259. this.emissive.copy( source.emissive );
  20260. this.emissiveMap = source.emissiveMap;
  20261. this.emissiveIntensity = source.emissiveIntensity;
  20262. this.bumpMap = source.bumpMap;
  20263. this.bumpScale = source.bumpScale;
  20264. this.normalMap = source.normalMap;
  20265. this.normalMapType = source.normalMapType;
  20266. this.normalScale.copy( source.normalScale );
  20267. this.displacementMap = source.displacementMap;
  20268. this.displacementScale = source.displacementScale;
  20269. this.displacementBias = source.displacementBias;
  20270. this.alphaMap = source.alphaMap;
  20271. this.wireframe = source.wireframe;
  20272. this.wireframeLinewidth = source.wireframeLinewidth;
  20273. this.wireframeLinecap = source.wireframeLinecap;
  20274. this.wireframeLinejoin = source.wireframeLinejoin;
  20275. this.skinning = source.skinning;
  20276. this.morphTargets = source.morphTargets;
  20277. this.morphNormals = source.morphNormals;
  20278. return this;
  20279. };
  20280. /**
  20281. * parameters = {
  20282. * opacity: <float>,
  20283. *
  20284. * bumpMap: new THREE.Texture( <Image> ),
  20285. * bumpScale: <float>,
  20286. *
  20287. * normalMap: new THREE.Texture( <Image> ),
  20288. * normalMapType: THREE.TangentSpaceNormalMap,
  20289. * normalScale: <Vector2>,
  20290. *
  20291. * displacementMap: new THREE.Texture( <Image> ),
  20292. * displacementScale: <float>,
  20293. * displacementBias: <float>,
  20294. *
  20295. * wireframe: <boolean>,
  20296. * wireframeLinewidth: <float>
  20297. *
  20298. * skinning: <bool>,
  20299. * morphTargets: <bool>,
  20300. * morphNormals: <bool>
  20301. * }
  20302. */
  20303. function MeshNormalMaterial( parameters ) {
  20304. Material.call( this );
  20305. this.type = 'MeshNormalMaterial';
  20306. this.bumpMap = null;
  20307. this.bumpScale = 1;
  20308. this.normalMap = null;
  20309. this.normalMapType = TangentSpaceNormalMap;
  20310. this.normalScale = new Vector2( 1, 1 );
  20311. this.displacementMap = null;
  20312. this.displacementScale = 1;
  20313. this.displacementBias = 0;
  20314. this.wireframe = false;
  20315. this.wireframeLinewidth = 1;
  20316. this.fog = false;
  20317. this.skinning = false;
  20318. this.morphTargets = false;
  20319. this.morphNormals = false;
  20320. this.setValues( parameters );
  20321. }
  20322. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  20323. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20324. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20325. MeshNormalMaterial.prototype.copy = function ( source ) {
  20326. Material.prototype.copy.call( this, source );
  20327. this.bumpMap = source.bumpMap;
  20328. this.bumpScale = source.bumpScale;
  20329. this.normalMap = source.normalMap;
  20330. this.normalMapType = source.normalMapType;
  20331. this.normalScale.copy( source.normalScale );
  20332. this.displacementMap = source.displacementMap;
  20333. this.displacementScale = source.displacementScale;
  20334. this.displacementBias = source.displacementBias;
  20335. this.wireframe = source.wireframe;
  20336. this.wireframeLinewidth = source.wireframeLinewidth;
  20337. this.skinning = source.skinning;
  20338. this.morphTargets = source.morphTargets;
  20339. this.morphNormals = source.morphNormals;
  20340. return this;
  20341. };
  20342. /**
  20343. * parameters = {
  20344. * color: <hex>,
  20345. * opacity: <float>,
  20346. *
  20347. * map: new THREE.Texture( <Image> ),
  20348. *
  20349. * lightMap: new THREE.Texture( <Image> ),
  20350. * lightMapIntensity: <float>
  20351. *
  20352. * aoMap: new THREE.Texture( <Image> ),
  20353. * aoMapIntensity: <float>
  20354. *
  20355. * emissive: <hex>,
  20356. * emissiveIntensity: <float>
  20357. * emissiveMap: new THREE.Texture( <Image> ),
  20358. *
  20359. * specularMap: new THREE.Texture( <Image> ),
  20360. *
  20361. * alphaMap: new THREE.Texture( <Image> ),
  20362. *
  20363. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20364. * combine: THREE.Multiply,
  20365. * reflectivity: <float>,
  20366. * refractionRatio: <float>,
  20367. *
  20368. * wireframe: <boolean>,
  20369. * wireframeLinewidth: <float>,
  20370. *
  20371. * skinning: <bool>,
  20372. * morphTargets: <bool>,
  20373. * morphNormals: <bool>
  20374. * }
  20375. */
  20376. function MeshLambertMaterial( parameters ) {
  20377. Material.call( this );
  20378. this.type = 'MeshLambertMaterial';
  20379. this.color = new Color( 0xffffff ); // diffuse
  20380. this.map = null;
  20381. this.lightMap = null;
  20382. this.lightMapIntensity = 1.0;
  20383. this.aoMap = null;
  20384. this.aoMapIntensity = 1.0;
  20385. this.emissive = new Color( 0x000000 );
  20386. this.emissiveIntensity = 1.0;
  20387. this.emissiveMap = null;
  20388. this.specularMap = null;
  20389. this.alphaMap = null;
  20390. this.envMap = null;
  20391. this.combine = MultiplyOperation;
  20392. this.reflectivity = 1;
  20393. this.refractionRatio = 0.98;
  20394. this.wireframe = false;
  20395. this.wireframeLinewidth = 1;
  20396. this.wireframeLinecap = 'round';
  20397. this.wireframeLinejoin = 'round';
  20398. this.skinning = false;
  20399. this.morphTargets = false;
  20400. this.morphNormals = false;
  20401. this.setValues( parameters );
  20402. }
  20403. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  20404. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  20405. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20406. MeshLambertMaterial.prototype.copy = function ( source ) {
  20407. Material.prototype.copy.call( this, source );
  20408. this.color.copy( source.color );
  20409. this.map = source.map;
  20410. this.lightMap = source.lightMap;
  20411. this.lightMapIntensity = source.lightMapIntensity;
  20412. this.aoMap = source.aoMap;
  20413. this.aoMapIntensity = source.aoMapIntensity;
  20414. this.emissive.copy( source.emissive );
  20415. this.emissiveMap = source.emissiveMap;
  20416. this.emissiveIntensity = source.emissiveIntensity;
  20417. this.specularMap = source.specularMap;
  20418. this.alphaMap = source.alphaMap;
  20419. this.envMap = source.envMap;
  20420. this.combine = source.combine;
  20421. this.reflectivity = source.reflectivity;
  20422. this.refractionRatio = source.refractionRatio;
  20423. this.wireframe = source.wireframe;
  20424. this.wireframeLinewidth = source.wireframeLinewidth;
  20425. this.wireframeLinecap = source.wireframeLinecap;
  20426. this.wireframeLinejoin = source.wireframeLinejoin;
  20427. this.skinning = source.skinning;
  20428. this.morphTargets = source.morphTargets;
  20429. this.morphNormals = source.morphNormals;
  20430. return this;
  20431. };
  20432. /**
  20433. * parameters = {
  20434. * color: <hex>,
  20435. * opacity: <float>,
  20436. *
  20437. * matcap: new THREE.Texture( <Image> ),
  20438. *
  20439. * map: new THREE.Texture( <Image> ),
  20440. *
  20441. * bumpMap: new THREE.Texture( <Image> ),
  20442. * bumpScale: <float>,
  20443. *
  20444. * normalMap: new THREE.Texture( <Image> ),
  20445. * normalMapType: THREE.TangentSpaceNormalMap,
  20446. * normalScale: <Vector2>,
  20447. *
  20448. * displacementMap: new THREE.Texture( <Image> ),
  20449. * displacementScale: <float>,
  20450. * displacementBias: <float>,
  20451. *
  20452. * alphaMap: new THREE.Texture( <Image> ),
  20453. *
  20454. * skinning: <bool>,
  20455. * morphTargets: <bool>,
  20456. * morphNormals: <bool>
  20457. * }
  20458. */
  20459. function MeshMatcapMaterial( parameters ) {
  20460. Material.call( this );
  20461. this.defines = { 'MATCAP': '' };
  20462. this.type = 'MeshMatcapMaterial';
  20463. this.color = new Color( 0xffffff ); // diffuse
  20464. this.matcap = null;
  20465. this.map = null;
  20466. this.bumpMap = null;
  20467. this.bumpScale = 1;
  20468. this.normalMap = null;
  20469. this.normalMapType = TangentSpaceNormalMap;
  20470. this.normalScale = new Vector2( 1, 1 );
  20471. this.displacementMap = null;
  20472. this.displacementScale = 1;
  20473. this.displacementBias = 0;
  20474. this.alphaMap = null;
  20475. this.skinning = false;
  20476. this.morphTargets = false;
  20477. this.morphNormals = false;
  20478. this.setValues( parameters );
  20479. }
  20480. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  20481. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20482. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20483. MeshMatcapMaterial.prototype.copy = function ( source ) {
  20484. Material.prototype.copy.call( this, source );
  20485. this.defines = { 'MATCAP': '' };
  20486. this.color.copy( source.color );
  20487. this.matcap = source.matcap;
  20488. this.map = source.map;
  20489. this.bumpMap = source.bumpMap;
  20490. this.bumpScale = source.bumpScale;
  20491. this.normalMap = source.normalMap;
  20492. this.normalMapType = source.normalMapType;
  20493. this.normalScale.copy( source.normalScale );
  20494. this.displacementMap = source.displacementMap;
  20495. this.displacementScale = source.displacementScale;
  20496. this.displacementBias = source.displacementBias;
  20497. this.alphaMap = source.alphaMap;
  20498. this.skinning = source.skinning;
  20499. this.morphTargets = source.morphTargets;
  20500. this.morphNormals = source.morphNormals;
  20501. return this;
  20502. };
  20503. /**
  20504. * parameters = {
  20505. * color: <hex>,
  20506. * opacity: <float>,
  20507. *
  20508. * linewidth: <float>,
  20509. *
  20510. * scale: <float>,
  20511. * dashSize: <float>,
  20512. * gapSize: <float>
  20513. * }
  20514. */
  20515. function LineDashedMaterial( parameters ) {
  20516. LineBasicMaterial.call( this );
  20517. this.type = 'LineDashedMaterial';
  20518. this.scale = 1;
  20519. this.dashSize = 3;
  20520. this.gapSize = 1;
  20521. this.setValues( parameters );
  20522. }
  20523. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  20524. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20525. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20526. LineDashedMaterial.prototype.copy = function ( source ) {
  20527. LineBasicMaterial.prototype.copy.call( this, source );
  20528. this.scale = source.scale;
  20529. this.dashSize = source.dashSize;
  20530. this.gapSize = source.gapSize;
  20531. return this;
  20532. };
  20533. var Materials = /*#__PURE__*/Object.freeze({
  20534. __proto__: null,
  20535. ShadowMaterial: ShadowMaterial,
  20536. SpriteMaterial: SpriteMaterial,
  20537. RawShaderMaterial: RawShaderMaterial,
  20538. ShaderMaterial: ShaderMaterial,
  20539. PointsMaterial: PointsMaterial,
  20540. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20541. MeshStandardMaterial: MeshStandardMaterial,
  20542. MeshPhongMaterial: MeshPhongMaterial,
  20543. MeshToonMaterial: MeshToonMaterial,
  20544. MeshNormalMaterial: MeshNormalMaterial,
  20545. MeshLambertMaterial: MeshLambertMaterial,
  20546. MeshDepthMaterial: MeshDepthMaterial,
  20547. MeshDistanceMaterial: MeshDistanceMaterial,
  20548. MeshBasicMaterial: MeshBasicMaterial,
  20549. MeshMatcapMaterial: MeshMatcapMaterial,
  20550. LineDashedMaterial: LineDashedMaterial,
  20551. LineBasicMaterial: LineBasicMaterial,
  20552. Material: Material
  20553. });
  20554. const AnimationUtils = {
  20555. // same as Array.prototype.slice, but also works on typed arrays
  20556. arraySlice: function ( array, from, to ) {
  20557. if ( AnimationUtils.isTypedArray( array ) ) {
  20558. // in ios9 array.subarray(from, undefined) will return empty array
  20559. // but array.subarray(from) or array.subarray(from, len) is correct
  20560. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  20561. }
  20562. return array.slice( from, to );
  20563. },
  20564. // converts an array to a specific type
  20565. convertArray: function ( array, type, forceClone ) {
  20566. if ( ! array || // let 'undefined' and 'null' pass
  20567. ! forceClone && array.constructor === type ) return array;
  20568. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  20569. return new type( array ); // create typed array
  20570. }
  20571. return Array.prototype.slice.call( array ); // create Array
  20572. },
  20573. isTypedArray: function ( object ) {
  20574. return ArrayBuffer.isView( object ) &&
  20575. ! ( object instanceof DataView );
  20576. },
  20577. // returns an array by which times and values can be sorted
  20578. getKeyframeOrder: function ( times ) {
  20579. function compareTime( i, j ) {
  20580. return times[ i ] - times[ j ];
  20581. }
  20582. const n = times.length;
  20583. const result = new Array( n );
  20584. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  20585. result.sort( compareTime );
  20586. return result;
  20587. },
  20588. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20589. sortedArray: function ( values, stride, order ) {
  20590. const nValues = values.length;
  20591. const result = new values.constructor( nValues );
  20592. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  20593. const srcOffset = order[ i ] * stride;
  20594. for ( let j = 0; j !== stride; ++ j ) {
  20595. result[ dstOffset ++ ] = values[ srcOffset + j ];
  20596. }
  20597. }
  20598. return result;
  20599. },
  20600. // function for parsing AOS keyframe formats
  20601. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  20602. let i = 1, key = jsonKeys[ 0 ];
  20603. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  20604. key = jsonKeys[ i ++ ];
  20605. }
  20606. if ( key === undefined ) return; // no data
  20607. let value = key[ valuePropertyName ];
  20608. if ( value === undefined ) return; // no data
  20609. if ( Array.isArray( value ) ) {
  20610. do {
  20611. value = key[ valuePropertyName ];
  20612. if ( value !== undefined ) {
  20613. times.push( key.time );
  20614. values.push.apply( values, value ); // push all elements
  20615. }
  20616. key = jsonKeys[ i ++ ];
  20617. } while ( key !== undefined );
  20618. } else if ( value.toArray !== undefined ) {
  20619. // ...assume THREE.Math-ish
  20620. do {
  20621. value = key[ valuePropertyName ];
  20622. if ( value !== undefined ) {
  20623. times.push( key.time );
  20624. value.toArray( values, values.length );
  20625. }
  20626. key = jsonKeys[ i ++ ];
  20627. } while ( key !== undefined );
  20628. } else {
  20629. // otherwise push as-is
  20630. do {
  20631. value = key[ valuePropertyName ];
  20632. if ( value !== undefined ) {
  20633. times.push( key.time );
  20634. values.push( value );
  20635. }
  20636. key = jsonKeys[ i ++ ];
  20637. } while ( key !== undefined );
  20638. }
  20639. },
  20640. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  20641. const clip = sourceClip.clone();
  20642. clip.name = name;
  20643. const tracks = [];
  20644. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  20645. const track = clip.tracks[ i ];
  20646. const valueSize = track.getValueSize();
  20647. const times = [];
  20648. const values = [];
  20649. for ( let j = 0; j < track.times.length; ++ j ) {
  20650. const frame = track.times[ j ] * fps;
  20651. if ( frame < startFrame || frame >= endFrame ) continue;
  20652. times.push( track.times[ j ] );
  20653. for ( let k = 0; k < valueSize; ++ k ) {
  20654. values.push( track.values[ j * valueSize + k ] );
  20655. }
  20656. }
  20657. if ( times.length === 0 ) continue;
  20658. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  20659. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  20660. tracks.push( track );
  20661. }
  20662. clip.tracks = tracks;
  20663. // find minimum .times value across all tracks in the trimmed clip
  20664. let minStartTime = Infinity;
  20665. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  20666. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  20667. minStartTime = clip.tracks[ i ].times[ 0 ];
  20668. }
  20669. }
  20670. // shift all tracks such that clip begins at t=0
  20671. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  20672. clip.tracks[ i ].shift( - 1 * minStartTime );
  20673. }
  20674. clip.resetDuration();
  20675. return clip;
  20676. },
  20677. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  20678. if ( fps <= 0 ) fps = 30;
  20679. const numTracks = referenceClip.tracks.length;
  20680. const referenceTime = referenceFrame / fps;
  20681. // Make each track's values relative to the values at the reference frame
  20682. for ( let i = 0; i < numTracks; ++ i ) {
  20683. const referenceTrack = referenceClip.tracks[ i ];
  20684. const referenceTrackType = referenceTrack.ValueTypeName;
  20685. // Skip this track if it's non-numeric
  20686. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  20687. // Find the track in the target clip whose name and type matches the reference track
  20688. const targetTrack = targetClip.tracks.find( function ( track ) {
  20689. return track.name === referenceTrack.name
  20690. && track.ValueTypeName === referenceTrackType;
  20691. } );
  20692. if ( targetTrack === undefined ) continue;
  20693. let referenceOffset = 0;
  20694. const referenceValueSize = referenceTrack.getValueSize();
  20695. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  20696. referenceOffset = referenceValueSize / 3;
  20697. }
  20698. let targetOffset = 0;
  20699. const targetValueSize = targetTrack.getValueSize();
  20700. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  20701. targetOffset = targetValueSize / 3;
  20702. }
  20703. const lastIndex = referenceTrack.times.length - 1;
  20704. let referenceValue;
  20705. // Find the value to subtract out of the track
  20706. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  20707. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  20708. const startIndex = referenceOffset;
  20709. const endIndex = referenceValueSize - referenceOffset;
  20710. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  20711. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  20712. // Reference frame is after the last keyframe, so just use the last keyframe
  20713. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  20714. const endIndex = startIndex + referenceValueSize - referenceOffset;
  20715. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  20716. } else {
  20717. // Interpolate to the reference value
  20718. const interpolant = referenceTrack.createInterpolant();
  20719. const startIndex = referenceOffset;
  20720. const endIndex = referenceValueSize - referenceOffset;
  20721. interpolant.evaluate( referenceTime );
  20722. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  20723. }
  20724. // Conjugate the quaternion
  20725. if ( referenceTrackType === 'quaternion' ) {
  20726. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  20727. referenceQuat.toArray( referenceValue );
  20728. }
  20729. // Subtract the reference value from all of the track values
  20730. const numTimes = targetTrack.times.length;
  20731. for ( let j = 0; j < numTimes; ++ j ) {
  20732. const valueStart = j * targetValueSize + targetOffset;
  20733. if ( referenceTrackType === 'quaternion' ) {
  20734. // Multiply the conjugate for quaternion track types
  20735. Quaternion.multiplyQuaternionsFlat(
  20736. targetTrack.values,
  20737. valueStart,
  20738. referenceValue,
  20739. 0,
  20740. targetTrack.values,
  20741. valueStart
  20742. );
  20743. } else {
  20744. const valueEnd = targetValueSize - targetOffset * 2;
  20745. // Subtract each value for all other numeric track types
  20746. for ( let k = 0; k < valueEnd; ++ k ) {
  20747. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  20748. }
  20749. }
  20750. }
  20751. }
  20752. targetClip.blendMode = AdditiveAnimationBlendMode;
  20753. return targetClip;
  20754. }
  20755. };
  20756. /**
  20757. * Abstract base class of interpolants over parametric samples.
  20758. *
  20759. * The parameter domain is one dimensional, typically the time or a path
  20760. * along a curve defined by the data.
  20761. *
  20762. * The sample values can have any dimensionality and derived classes may
  20763. * apply special interpretations to the data.
  20764. *
  20765. * This class provides the interval seek in a Template Method, deferring
  20766. * the actual interpolation to derived classes.
  20767. *
  20768. * Time complexity is O(1) for linear access crossing at most two points
  20769. * and O(log N) for random access, where N is the number of positions.
  20770. *
  20771. * References:
  20772. *
  20773. * http://www.oodesign.com/template-method-pattern.html
  20774. *
  20775. */
  20776. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20777. this.parameterPositions = parameterPositions;
  20778. this._cachedIndex = 0;
  20779. this.resultBuffer = resultBuffer !== undefined ?
  20780. resultBuffer : new sampleValues.constructor( sampleSize );
  20781. this.sampleValues = sampleValues;
  20782. this.valueSize = sampleSize;
  20783. }
  20784. Object.assign( Interpolant.prototype, {
  20785. evaluate: function ( t ) {
  20786. const pp = this.parameterPositions;
  20787. let i1 = this._cachedIndex,
  20788. t1 = pp[ i1 ],
  20789. t0 = pp[ i1 - 1 ];
  20790. validate_interval: {
  20791. seek: {
  20792. let right;
  20793. linear_scan: {
  20794. //- See http://jsperf.com/comparison-to-undefined/3
  20795. //- slower code:
  20796. //-
  20797. //- if ( t >= t1 || t1 === undefined ) {
  20798. forward_scan: if ( ! ( t < t1 ) ) {
  20799. for ( let giveUpAt = i1 + 2; ; ) {
  20800. if ( t1 === undefined ) {
  20801. if ( t < t0 ) break forward_scan;
  20802. // after end
  20803. i1 = pp.length;
  20804. this._cachedIndex = i1;
  20805. return this.afterEnd_( i1 - 1, t, t0 );
  20806. }
  20807. if ( i1 === giveUpAt ) break; // this loop
  20808. t0 = t1;
  20809. t1 = pp[ ++ i1 ];
  20810. if ( t < t1 ) {
  20811. // we have arrived at the sought interval
  20812. break seek;
  20813. }
  20814. }
  20815. // prepare binary search on the right side of the index
  20816. right = pp.length;
  20817. break linear_scan;
  20818. }
  20819. //- slower code:
  20820. //- if ( t < t0 || t0 === undefined ) {
  20821. if ( ! ( t >= t0 ) ) {
  20822. // looping?
  20823. const t1global = pp[ 1 ];
  20824. if ( t < t1global ) {
  20825. i1 = 2; // + 1, using the scan for the details
  20826. t0 = t1global;
  20827. }
  20828. // linear reverse scan
  20829. for ( let giveUpAt = i1 - 2; ; ) {
  20830. if ( t0 === undefined ) {
  20831. // before start
  20832. this._cachedIndex = 0;
  20833. return this.beforeStart_( 0, t, t1 );
  20834. }
  20835. if ( i1 === giveUpAt ) break; // this loop
  20836. t1 = t0;
  20837. t0 = pp[ -- i1 - 1 ];
  20838. if ( t >= t0 ) {
  20839. // we have arrived at the sought interval
  20840. break seek;
  20841. }
  20842. }
  20843. // prepare binary search on the left side of the index
  20844. right = i1;
  20845. i1 = 0;
  20846. break linear_scan;
  20847. }
  20848. // the interval is valid
  20849. break validate_interval;
  20850. } // linear scan
  20851. // binary search
  20852. while ( i1 < right ) {
  20853. const mid = ( i1 + right ) >>> 1;
  20854. if ( t < pp[ mid ] ) {
  20855. right = mid;
  20856. } else {
  20857. i1 = mid + 1;
  20858. }
  20859. }
  20860. t1 = pp[ i1 ];
  20861. t0 = pp[ i1 - 1 ];
  20862. // check boundary cases, again
  20863. if ( t0 === undefined ) {
  20864. this._cachedIndex = 0;
  20865. return this.beforeStart_( 0, t, t1 );
  20866. }
  20867. if ( t1 === undefined ) {
  20868. i1 = pp.length;
  20869. this._cachedIndex = i1;
  20870. return this.afterEnd_( i1 - 1, t0, t );
  20871. }
  20872. } // seek
  20873. this._cachedIndex = i1;
  20874. this.intervalChanged_( i1, t0, t1 );
  20875. } // validate_interval
  20876. return this.interpolate_( i1, t0, t, t1 );
  20877. },
  20878. settings: null, // optional, subclass-specific settings structure
  20879. // Note: The indirection allows central control of many interpolants.
  20880. // --- Protected interface
  20881. DefaultSettings_: {},
  20882. getSettings_: function () {
  20883. return this.settings || this.DefaultSettings_;
  20884. },
  20885. copySampleValue_: function ( index ) {
  20886. // copies a sample value to the result buffer
  20887. const result = this.resultBuffer,
  20888. values = this.sampleValues,
  20889. stride = this.valueSize,
  20890. offset = index * stride;
  20891. for ( let i = 0; i !== stride; ++ i ) {
  20892. result[ i ] = values[ offset + i ];
  20893. }
  20894. return result;
  20895. },
  20896. // Template methods for derived classes:
  20897. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  20898. throw new Error( 'call to abstract method' );
  20899. // implementations shall return this.resultBuffer
  20900. },
  20901. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  20902. // empty
  20903. }
  20904. } );
  20905. // DECLARE ALIAS AFTER assign prototype
  20906. Object.assign( Interpolant.prototype, {
  20907. //( 0, t, t0 ), returns this.resultBuffer
  20908. beforeStart_: Interpolant.prototype.copySampleValue_,
  20909. //( N-1, tN-1, t ), returns this.resultBuffer
  20910. afterEnd_: Interpolant.prototype.copySampleValue_,
  20911. } );
  20912. /**
  20913. * Fast and simple cubic spline interpolant.
  20914. *
  20915. * It was derived from a Hermitian construction setting the first derivative
  20916. * at each sample position to the linear slope between neighboring positions
  20917. * over their parameter interval.
  20918. */
  20919. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  20920. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  20921. this._weightPrev = - 0;
  20922. this._offsetPrev = - 0;
  20923. this._weightNext = - 0;
  20924. this._offsetNext = - 0;
  20925. }
  20926. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  20927. constructor: CubicInterpolant,
  20928. DefaultSettings_: {
  20929. endingStart: ZeroCurvatureEnding,
  20930. endingEnd: ZeroCurvatureEnding
  20931. },
  20932. intervalChanged_: function ( i1, t0, t1 ) {
  20933. const pp = this.parameterPositions;
  20934. let iPrev = i1 - 2,
  20935. iNext = i1 + 1,
  20936. tPrev = pp[ iPrev ],
  20937. tNext = pp[ iNext ];
  20938. if ( tPrev === undefined ) {
  20939. switch ( this.getSettings_().endingStart ) {
  20940. case ZeroSlopeEnding:
  20941. // f'(t0) = 0
  20942. iPrev = i1;
  20943. tPrev = 2 * t0 - t1;
  20944. break;
  20945. case WrapAroundEnding:
  20946. // use the other end of the curve
  20947. iPrev = pp.length - 2;
  20948. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  20949. break;
  20950. default: // ZeroCurvatureEnding
  20951. // f''(t0) = 0 a.k.a. Natural Spline
  20952. iPrev = i1;
  20953. tPrev = t1;
  20954. }
  20955. }
  20956. if ( tNext === undefined ) {
  20957. switch ( this.getSettings_().endingEnd ) {
  20958. case ZeroSlopeEnding:
  20959. // f'(tN) = 0
  20960. iNext = i1;
  20961. tNext = 2 * t1 - t0;
  20962. break;
  20963. case WrapAroundEnding:
  20964. // use the other end of the curve
  20965. iNext = 1;
  20966. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  20967. break;
  20968. default: // ZeroCurvatureEnding
  20969. // f''(tN) = 0, a.k.a. Natural Spline
  20970. iNext = i1 - 1;
  20971. tNext = t0;
  20972. }
  20973. }
  20974. const halfDt = ( t1 - t0 ) * 0.5,
  20975. stride = this.valueSize;
  20976. this._weightPrev = halfDt / ( t0 - tPrev );
  20977. this._weightNext = halfDt / ( tNext - t1 );
  20978. this._offsetPrev = iPrev * stride;
  20979. this._offsetNext = iNext * stride;
  20980. },
  20981. interpolate_: function ( i1, t0, t, t1 ) {
  20982. const result = this.resultBuffer,
  20983. values = this.sampleValues,
  20984. stride = this.valueSize,
  20985. o1 = i1 * stride, o0 = o1 - stride,
  20986. oP = this._offsetPrev, oN = this._offsetNext,
  20987. wP = this._weightPrev, wN = this._weightNext,
  20988. p = ( t - t0 ) / ( t1 - t0 ),
  20989. pp = p * p,
  20990. ppp = pp * p;
  20991. // evaluate polynomials
  20992. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  20993. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  20994. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  20995. const sN = wN * ppp - wN * pp;
  20996. // combine data linearly
  20997. for ( let i = 0; i !== stride; ++ i ) {
  20998. result[ i ] =
  20999. sP * values[ oP + i ] +
  21000. s0 * values[ o0 + i ] +
  21001. s1 * values[ o1 + i ] +
  21002. sN * values[ oN + i ];
  21003. }
  21004. return result;
  21005. }
  21006. } );
  21007. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21008. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21009. }
  21010. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21011. constructor: LinearInterpolant,
  21012. interpolate_: function ( i1, t0, t, t1 ) {
  21013. const result = this.resultBuffer,
  21014. values = this.sampleValues,
  21015. stride = this.valueSize,
  21016. offset1 = i1 * stride,
  21017. offset0 = offset1 - stride,
  21018. weight1 = ( t - t0 ) / ( t1 - t0 ),
  21019. weight0 = 1 - weight1;
  21020. for ( let i = 0; i !== stride; ++ i ) {
  21021. result[ i ] =
  21022. values[ offset0 + i ] * weight0 +
  21023. values[ offset1 + i ] * weight1;
  21024. }
  21025. return result;
  21026. }
  21027. } );
  21028. /**
  21029. *
  21030. * Interpolant that evaluates to the sample value at the position preceeding
  21031. * the parameter.
  21032. */
  21033. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21034. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21035. }
  21036. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21037. constructor: DiscreteInterpolant,
  21038. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  21039. return this.copySampleValue_( i1 - 1 );
  21040. }
  21041. } );
  21042. function KeyframeTrack( name, times, values, interpolation ) {
  21043. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  21044. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  21045. this.name = name;
  21046. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  21047. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  21048. this.setInterpolation( interpolation || this.DefaultInterpolation );
  21049. }
  21050. // Static methods
  21051. Object.assign( KeyframeTrack, {
  21052. // Serialization (in static context, because of constructor invocation
  21053. // and automatic invocation of .toJSON):
  21054. toJSON: function ( track ) {
  21055. const trackType = track.constructor;
  21056. let json;
  21057. // derived classes can define a static toJSON method
  21058. if ( trackType.toJSON !== undefined ) {
  21059. json = trackType.toJSON( track );
  21060. } else {
  21061. // by default, we assume the data can be serialized as-is
  21062. json = {
  21063. 'name': track.name,
  21064. 'times': AnimationUtils.convertArray( track.times, Array ),
  21065. 'values': AnimationUtils.convertArray( track.values, Array )
  21066. };
  21067. const interpolation = track.getInterpolation();
  21068. if ( interpolation !== track.DefaultInterpolation ) {
  21069. json.interpolation = interpolation;
  21070. }
  21071. }
  21072. json.type = track.ValueTypeName; // mandatory
  21073. return json;
  21074. }
  21075. } );
  21076. Object.assign( KeyframeTrack.prototype, {
  21077. constructor: KeyframeTrack,
  21078. TimeBufferType: Float32Array,
  21079. ValueBufferType: Float32Array,
  21080. DefaultInterpolation: InterpolateLinear,
  21081. InterpolantFactoryMethodDiscrete: function ( result ) {
  21082. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  21083. },
  21084. InterpolantFactoryMethodLinear: function ( result ) {
  21085. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  21086. },
  21087. InterpolantFactoryMethodSmooth: function ( result ) {
  21088. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  21089. },
  21090. setInterpolation: function ( interpolation ) {
  21091. let factoryMethod;
  21092. switch ( interpolation ) {
  21093. case InterpolateDiscrete:
  21094. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21095. break;
  21096. case InterpolateLinear:
  21097. factoryMethod = this.InterpolantFactoryMethodLinear;
  21098. break;
  21099. case InterpolateSmooth:
  21100. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21101. break;
  21102. }
  21103. if ( factoryMethod === undefined ) {
  21104. const message = 'unsupported interpolation for ' +
  21105. this.ValueTypeName + ' keyframe track named ' + this.name;
  21106. if ( this.createInterpolant === undefined ) {
  21107. // fall back to default, unless the default itself is messed up
  21108. if ( interpolation !== this.DefaultInterpolation ) {
  21109. this.setInterpolation( this.DefaultInterpolation );
  21110. } else {
  21111. throw new Error( message ); // fatal, in this case
  21112. }
  21113. }
  21114. console.warn( 'THREE.KeyframeTrack:', message );
  21115. return this;
  21116. }
  21117. this.createInterpolant = factoryMethod;
  21118. return this;
  21119. },
  21120. getInterpolation: function () {
  21121. switch ( this.createInterpolant ) {
  21122. case this.InterpolantFactoryMethodDiscrete:
  21123. return InterpolateDiscrete;
  21124. case this.InterpolantFactoryMethodLinear:
  21125. return InterpolateLinear;
  21126. case this.InterpolantFactoryMethodSmooth:
  21127. return InterpolateSmooth;
  21128. }
  21129. },
  21130. getValueSize: function () {
  21131. return this.values.length / this.times.length;
  21132. },
  21133. // move all keyframes either forwards or backwards in time
  21134. shift: function ( timeOffset ) {
  21135. if ( timeOffset !== 0.0 ) {
  21136. const times = this.times;
  21137. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21138. times[ i ] += timeOffset;
  21139. }
  21140. }
  21141. return this;
  21142. },
  21143. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21144. scale: function ( timeScale ) {
  21145. if ( timeScale !== 1.0 ) {
  21146. const times = this.times;
  21147. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21148. times[ i ] *= timeScale;
  21149. }
  21150. }
  21151. return this;
  21152. },
  21153. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21154. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21155. trim: function ( startTime, endTime ) {
  21156. const times = this.times,
  21157. nKeys = times.length;
  21158. let from = 0,
  21159. to = nKeys - 1;
  21160. while ( from !== nKeys && times[ from ] < startTime ) {
  21161. ++ from;
  21162. }
  21163. while ( to !== - 1 && times[ to ] > endTime ) {
  21164. -- to;
  21165. }
  21166. ++ to; // inclusive -> exclusive bound
  21167. if ( from !== 0 || to !== nKeys ) {
  21168. // empty tracks are forbidden, so keep at least one keyframe
  21169. if ( from >= to ) {
  21170. to = Math.max( to, 1 );
  21171. from = to - 1;
  21172. }
  21173. const stride = this.getValueSize();
  21174. this.times = AnimationUtils.arraySlice( times, from, to );
  21175. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  21176. }
  21177. return this;
  21178. },
  21179. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21180. validate: function () {
  21181. let valid = true;
  21182. const valueSize = this.getValueSize();
  21183. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  21184. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  21185. valid = false;
  21186. }
  21187. const times = this.times,
  21188. values = this.values,
  21189. nKeys = times.length;
  21190. if ( nKeys === 0 ) {
  21191. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  21192. valid = false;
  21193. }
  21194. let prevTime = null;
  21195. for ( let i = 0; i !== nKeys; i ++ ) {
  21196. const currTime = times[ i ];
  21197. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  21198. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  21199. valid = false;
  21200. break;
  21201. }
  21202. if ( prevTime !== null && prevTime > currTime ) {
  21203. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  21204. valid = false;
  21205. break;
  21206. }
  21207. prevTime = currTime;
  21208. }
  21209. if ( values !== undefined ) {
  21210. if ( AnimationUtils.isTypedArray( values ) ) {
  21211. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  21212. const value = values[ i ];
  21213. if ( isNaN( value ) ) {
  21214. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  21215. valid = false;
  21216. break;
  21217. }
  21218. }
  21219. }
  21220. }
  21221. return valid;
  21222. },
  21223. // removes equivalent sequential keys as common in morph target sequences
  21224. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21225. optimize: function () {
  21226. // times or values may be shared with other tracks, so overwriting is unsafe
  21227. const times = AnimationUtils.arraySlice( this.times ),
  21228. values = AnimationUtils.arraySlice( this.values ),
  21229. stride = this.getValueSize(),
  21230. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21231. lastIndex = times.length - 1;
  21232. let writeIndex = 1;
  21233. for ( let i = 1; i < lastIndex; ++ i ) {
  21234. let keep = false;
  21235. const time = times[ i ];
  21236. const timeNext = times[ i + 1 ];
  21237. // remove adjacent keyframes scheduled at the same time
  21238. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  21239. if ( ! smoothInterpolation ) {
  21240. // remove unnecessary keyframes same as their neighbors
  21241. const offset = i * stride,
  21242. offsetP = offset - stride,
  21243. offsetN = offset + stride;
  21244. for ( let j = 0; j !== stride; ++ j ) {
  21245. const value = values[ offset + j ];
  21246. if ( value !== values[ offsetP + j ] ||
  21247. value !== values[ offsetN + j ] ) {
  21248. keep = true;
  21249. break;
  21250. }
  21251. }
  21252. } else {
  21253. keep = true;
  21254. }
  21255. }
  21256. // in-place compaction
  21257. if ( keep ) {
  21258. if ( i !== writeIndex ) {
  21259. times[ writeIndex ] = times[ i ];
  21260. const readOffset = i * stride,
  21261. writeOffset = writeIndex * stride;
  21262. for ( let j = 0; j !== stride; ++ j ) {
  21263. values[ writeOffset + j ] = values[ readOffset + j ];
  21264. }
  21265. }
  21266. ++ writeIndex;
  21267. }
  21268. }
  21269. // flush last keyframe (compaction looks ahead)
  21270. if ( lastIndex > 0 ) {
  21271. times[ writeIndex ] = times[ lastIndex ];
  21272. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  21273. values[ writeOffset + j ] = values[ readOffset + j ];
  21274. }
  21275. ++ writeIndex;
  21276. }
  21277. if ( writeIndex !== times.length ) {
  21278. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  21279. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  21280. } else {
  21281. this.times = times;
  21282. this.values = values;
  21283. }
  21284. return this;
  21285. },
  21286. clone: function () {
  21287. const times = AnimationUtils.arraySlice( this.times, 0 );
  21288. const values = AnimationUtils.arraySlice( this.values, 0 );
  21289. const TypedKeyframeTrack = this.constructor;
  21290. const track = new TypedKeyframeTrack( this.name, times, values );
  21291. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21292. track.createInterpolant = this.createInterpolant;
  21293. return track;
  21294. }
  21295. } );
  21296. /**
  21297. * A Track of Boolean keyframe values.
  21298. */
  21299. function BooleanKeyframeTrack( name, times, values ) {
  21300. KeyframeTrack.call( this, name, times, values );
  21301. }
  21302. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21303. constructor: BooleanKeyframeTrack,
  21304. ValueTypeName: 'bool',
  21305. ValueBufferType: Array,
  21306. DefaultInterpolation: InterpolateDiscrete,
  21307. InterpolantFactoryMethodLinear: undefined,
  21308. InterpolantFactoryMethodSmooth: undefined
  21309. // Note: Actually this track could have a optimized / compressed
  21310. // representation of a single value and a custom interpolant that
  21311. // computes "firstValue ^ isOdd( index )".
  21312. } );
  21313. /**
  21314. * A Track of keyframe values that represent color.
  21315. */
  21316. function ColorKeyframeTrack( name, times, values, interpolation ) {
  21317. KeyframeTrack.call( this, name, times, values, interpolation );
  21318. }
  21319. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21320. constructor: ColorKeyframeTrack,
  21321. ValueTypeName: 'color'
  21322. // ValueBufferType is inherited
  21323. // DefaultInterpolation is inherited
  21324. // Note: Very basic implementation and nothing special yet.
  21325. // However, this is the place for color space parameterization.
  21326. } );
  21327. /**
  21328. * A Track of numeric keyframe values.
  21329. */
  21330. function NumberKeyframeTrack( name, times, values, interpolation ) {
  21331. KeyframeTrack.call( this, name, times, values, interpolation );
  21332. }
  21333. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21334. constructor: NumberKeyframeTrack,
  21335. ValueTypeName: 'number'
  21336. // ValueBufferType is inherited
  21337. // DefaultInterpolation is inherited
  21338. } );
  21339. /**
  21340. * Spherical linear unit quaternion interpolant.
  21341. */
  21342. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21343. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21344. }
  21345. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21346. constructor: QuaternionLinearInterpolant,
  21347. interpolate_: function ( i1, t0, t, t1 ) {
  21348. const result = this.resultBuffer,
  21349. values = this.sampleValues,
  21350. stride = this.valueSize,
  21351. alpha = ( t - t0 ) / ( t1 - t0 );
  21352. let offset = i1 * stride;
  21353. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  21354. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  21355. }
  21356. return result;
  21357. }
  21358. } );
  21359. /**
  21360. * A Track of quaternion keyframe values.
  21361. */
  21362. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  21363. KeyframeTrack.call( this, name, times, values, interpolation );
  21364. }
  21365. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21366. constructor: QuaternionKeyframeTrack,
  21367. ValueTypeName: 'quaternion',
  21368. // ValueBufferType is inherited
  21369. DefaultInterpolation: InterpolateLinear,
  21370. InterpolantFactoryMethodLinear: function ( result ) {
  21371. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  21372. },
  21373. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21374. } );
  21375. /**
  21376. * A Track that interpolates Strings
  21377. */
  21378. function StringKeyframeTrack( name, times, values, interpolation ) {
  21379. KeyframeTrack.call( this, name, times, values, interpolation );
  21380. }
  21381. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21382. constructor: StringKeyframeTrack,
  21383. ValueTypeName: 'string',
  21384. ValueBufferType: Array,
  21385. DefaultInterpolation: InterpolateDiscrete,
  21386. InterpolantFactoryMethodLinear: undefined,
  21387. InterpolantFactoryMethodSmooth: undefined
  21388. } );
  21389. /**
  21390. * A Track of vectored keyframe values.
  21391. */
  21392. function VectorKeyframeTrack( name, times, values, interpolation ) {
  21393. KeyframeTrack.call( this, name, times, values, interpolation );
  21394. }
  21395. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  21396. constructor: VectorKeyframeTrack,
  21397. ValueTypeName: 'vector'
  21398. // ValueBufferType is inherited
  21399. // DefaultInterpolation is inherited
  21400. } );
  21401. function AnimationClip( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  21402. this.name = name;
  21403. this.tracks = tracks;
  21404. this.duration = duration;
  21405. this.blendMode = blendMode;
  21406. this.uuid = MathUtils.generateUUID();
  21407. // this means it should figure out its duration by scanning the tracks
  21408. if ( this.duration < 0 ) {
  21409. this.resetDuration();
  21410. }
  21411. }
  21412. function getTrackTypeForValueTypeName( typeName ) {
  21413. switch ( typeName.toLowerCase() ) {
  21414. case 'scalar':
  21415. case 'double':
  21416. case 'float':
  21417. case 'number':
  21418. case 'integer':
  21419. return NumberKeyframeTrack;
  21420. case 'vector':
  21421. case 'vector2':
  21422. case 'vector3':
  21423. case 'vector4':
  21424. return VectorKeyframeTrack;
  21425. case 'color':
  21426. return ColorKeyframeTrack;
  21427. case 'quaternion':
  21428. return QuaternionKeyframeTrack;
  21429. case 'bool':
  21430. case 'boolean':
  21431. return BooleanKeyframeTrack;
  21432. case 'string':
  21433. return StringKeyframeTrack;
  21434. }
  21435. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  21436. }
  21437. function parseKeyframeTrack( json ) {
  21438. if ( json.type === undefined ) {
  21439. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  21440. }
  21441. const trackType = getTrackTypeForValueTypeName( json.type );
  21442. if ( json.times === undefined ) {
  21443. const times = [], values = [];
  21444. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  21445. json.times = times;
  21446. json.values = values;
  21447. }
  21448. // derived classes can define a static parse method
  21449. if ( trackType.parse !== undefined ) {
  21450. return trackType.parse( json );
  21451. } else {
  21452. // by default, we assume a constructor compatible with the base
  21453. return new trackType( json.name, json.times, json.values, json.interpolation );
  21454. }
  21455. }
  21456. Object.assign( AnimationClip, {
  21457. parse: function ( json ) {
  21458. const tracks = [],
  21459. jsonTracks = json.tracks,
  21460. frameTime = 1.0 / ( json.fps || 1.0 );
  21461. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  21462. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  21463. }
  21464. const clip = new AnimationClip( json.name, json.duration, tracks, json.blendMode );
  21465. clip.uuid = json.uuid;
  21466. return clip;
  21467. },
  21468. toJSON: function ( clip ) {
  21469. const tracks = [],
  21470. clipTracks = clip.tracks;
  21471. const json = {
  21472. 'name': clip.name,
  21473. 'duration': clip.duration,
  21474. 'tracks': tracks,
  21475. 'uuid': clip.uuid,
  21476. 'blendMode': clip.blendMode
  21477. };
  21478. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  21479. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  21480. }
  21481. return json;
  21482. },
  21483. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  21484. const numMorphTargets = morphTargetSequence.length;
  21485. const tracks = [];
  21486. for ( let i = 0; i < numMorphTargets; i ++ ) {
  21487. let times = [];
  21488. let values = [];
  21489. times.push(
  21490. ( i + numMorphTargets - 1 ) % numMorphTargets,
  21491. i,
  21492. ( i + 1 ) % numMorphTargets );
  21493. values.push( 0, 1, 0 );
  21494. const order = AnimationUtils.getKeyframeOrder( times );
  21495. times = AnimationUtils.sortedArray( times, 1, order );
  21496. values = AnimationUtils.sortedArray( values, 1, order );
  21497. // if there is a key at the first frame, duplicate it as the
  21498. // last frame as well for perfect loop.
  21499. if ( ! noLoop && times[ 0 ] === 0 ) {
  21500. times.push( numMorphTargets );
  21501. values.push( values[ 0 ] );
  21502. }
  21503. tracks.push(
  21504. new NumberKeyframeTrack(
  21505. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  21506. times, values
  21507. ).scale( 1.0 / fps ) );
  21508. }
  21509. return new AnimationClip( name, - 1, tracks );
  21510. },
  21511. findByName: function ( objectOrClipArray, name ) {
  21512. let clipArray = objectOrClipArray;
  21513. if ( ! Array.isArray( objectOrClipArray ) ) {
  21514. const o = objectOrClipArray;
  21515. clipArray = o.geometry && o.geometry.animations || o.animations;
  21516. }
  21517. for ( let i = 0; i < clipArray.length; i ++ ) {
  21518. if ( clipArray[ i ].name === name ) {
  21519. return clipArray[ i ];
  21520. }
  21521. }
  21522. return null;
  21523. },
  21524. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  21525. const animationToMorphTargets = {};
  21526. // tested with https://regex101.com/ on trick sequences
  21527. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21528. const pattern = /^([\w-]*?)([\d]+)$/;
  21529. // sort morph target names into animation groups based
  21530. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21531. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  21532. const morphTarget = morphTargets[ i ];
  21533. const parts = morphTarget.name.match( pattern );
  21534. if ( parts && parts.length > 1 ) {
  21535. const name = parts[ 1 ];
  21536. let animationMorphTargets = animationToMorphTargets[ name ];
  21537. if ( ! animationMorphTargets ) {
  21538. animationToMorphTargets[ name ] = animationMorphTargets = [];
  21539. }
  21540. animationMorphTargets.push( morphTarget );
  21541. }
  21542. }
  21543. const clips = [];
  21544. for ( const name in animationToMorphTargets ) {
  21545. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  21546. }
  21547. return clips;
  21548. },
  21549. // parse the animation.hierarchy format
  21550. parseAnimation: function ( animation, bones ) {
  21551. if ( ! animation ) {
  21552. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  21553. return null;
  21554. }
  21555. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  21556. // only return track if there are actually keys.
  21557. if ( animationKeys.length !== 0 ) {
  21558. const times = [];
  21559. const values = [];
  21560. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  21561. // empty keys are filtered out, so check again
  21562. if ( times.length !== 0 ) {
  21563. destTracks.push( new trackType( trackName, times, values ) );
  21564. }
  21565. }
  21566. };
  21567. const tracks = [];
  21568. const clipName = animation.name || 'default';
  21569. const fps = animation.fps || 30;
  21570. const blendMode = animation.blendMode;
  21571. // automatic length determination in AnimationClip.
  21572. let duration = animation.length || - 1;
  21573. const hierarchyTracks = animation.hierarchy || [];
  21574. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  21575. const animationKeys = hierarchyTracks[ h ].keys;
  21576. // skip empty tracks
  21577. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  21578. // process morph targets
  21579. if ( animationKeys[ 0 ].morphTargets ) {
  21580. // figure out all morph targets used in this track
  21581. const morphTargetNames = {};
  21582. let k;
  21583. for ( k = 0; k < animationKeys.length; k ++ ) {
  21584. if ( animationKeys[ k ].morphTargets ) {
  21585. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  21586. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  21587. }
  21588. }
  21589. }
  21590. // create a track for each morph target with all zero
  21591. // morphTargetInfluences except for the keys in which
  21592. // the morphTarget is named.
  21593. for ( const morphTargetName in morphTargetNames ) {
  21594. const times = [];
  21595. const values = [];
  21596. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  21597. const animationKey = animationKeys[ k ];
  21598. times.push( animationKey.time );
  21599. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  21600. }
  21601. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  21602. }
  21603. duration = morphTargetNames.length * ( fps || 1.0 );
  21604. } else {
  21605. // ...assume skeletal animation
  21606. const boneName = '.bones[' + bones[ h ].name + ']';
  21607. addNonemptyTrack(
  21608. VectorKeyframeTrack, boneName + '.position',
  21609. animationKeys, 'pos', tracks );
  21610. addNonemptyTrack(
  21611. QuaternionKeyframeTrack, boneName + '.quaternion',
  21612. animationKeys, 'rot', tracks );
  21613. addNonemptyTrack(
  21614. VectorKeyframeTrack, boneName + '.scale',
  21615. animationKeys, 'scl', tracks );
  21616. }
  21617. }
  21618. if ( tracks.length === 0 ) {
  21619. return null;
  21620. }
  21621. const clip = new AnimationClip( clipName, duration, tracks, blendMode );
  21622. return clip;
  21623. }
  21624. } );
  21625. Object.assign( AnimationClip.prototype, {
  21626. resetDuration: function () {
  21627. const tracks = this.tracks;
  21628. let duration = 0;
  21629. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  21630. const track = this.tracks[ i ];
  21631. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  21632. }
  21633. this.duration = duration;
  21634. return this;
  21635. },
  21636. trim: function () {
  21637. for ( let i = 0; i < this.tracks.length; i ++ ) {
  21638. this.tracks[ i ].trim( 0, this.duration );
  21639. }
  21640. return this;
  21641. },
  21642. validate: function () {
  21643. let valid = true;
  21644. for ( let i = 0; i < this.tracks.length; i ++ ) {
  21645. valid = valid && this.tracks[ i ].validate();
  21646. }
  21647. return valid;
  21648. },
  21649. optimize: function () {
  21650. for ( let i = 0; i < this.tracks.length; i ++ ) {
  21651. this.tracks[ i ].optimize();
  21652. }
  21653. return this;
  21654. },
  21655. clone: function () {
  21656. const tracks = [];
  21657. for ( let i = 0; i < this.tracks.length; i ++ ) {
  21658. tracks.push( this.tracks[ i ].clone() );
  21659. }
  21660. return new AnimationClip( this.name, this.duration, tracks, this.blendMode );
  21661. },
  21662. toJSON: function () {
  21663. return AnimationClip.toJSON( this );
  21664. }
  21665. } );
  21666. const Cache = {
  21667. enabled: false,
  21668. files: {},
  21669. add: function ( key, file ) {
  21670. if ( this.enabled === false ) return;
  21671. // console.log( 'THREE.Cache', 'Adding key:', key );
  21672. this.files[ key ] = file;
  21673. },
  21674. get: function ( key ) {
  21675. if ( this.enabled === false ) return;
  21676. // console.log( 'THREE.Cache', 'Checking key:', key );
  21677. return this.files[ key ];
  21678. },
  21679. remove: function ( key ) {
  21680. delete this.files[ key ];
  21681. },
  21682. clear: function () {
  21683. this.files = {};
  21684. }
  21685. };
  21686. function LoadingManager( onLoad, onProgress, onError ) {
  21687. const scope = this;
  21688. let isLoading = false;
  21689. let itemsLoaded = 0;
  21690. let itemsTotal = 0;
  21691. let urlModifier = undefined;
  21692. const handlers = [];
  21693. // Refer to #5689 for the reason why we don't set .onStart
  21694. // in the constructor
  21695. this.onStart = undefined;
  21696. this.onLoad = onLoad;
  21697. this.onProgress = onProgress;
  21698. this.onError = onError;
  21699. this.itemStart = function ( url ) {
  21700. itemsTotal ++;
  21701. if ( isLoading === false ) {
  21702. if ( scope.onStart !== undefined ) {
  21703. scope.onStart( url, itemsLoaded, itemsTotal );
  21704. }
  21705. }
  21706. isLoading = true;
  21707. };
  21708. this.itemEnd = function ( url ) {
  21709. itemsLoaded ++;
  21710. if ( scope.onProgress !== undefined ) {
  21711. scope.onProgress( url, itemsLoaded, itemsTotal );
  21712. }
  21713. if ( itemsLoaded === itemsTotal ) {
  21714. isLoading = false;
  21715. if ( scope.onLoad !== undefined ) {
  21716. scope.onLoad();
  21717. }
  21718. }
  21719. };
  21720. this.itemError = function ( url ) {
  21721. if ( scope.onError !== undefined ) {
  21722. scope.onError( url );
  21723. }
  21724. };
  21725. this.resolveURL = function ( url ) {
  21726. if ( urlModifier ) {
  21727. return urlModifier( url );
  21728. }
  21729. return url;
  21730. };
  21731. this.setURLModifier = function ( transform ) {
  21732. urlModifier = transform;
  21733. return this;
  21734. };
  21735. this.addHandler = function ( regex, loader ) {
  21736. handlers.push( regex, loader );
  21737. return this;
  21738. };
  21739. this.removeHandler = function ( regex ) {
  21740. const index = handlers.indexOf( regex );
  21741. if ( index !== - 1 ) {
  21742. handlers.splice( index, 2 );
  21743. }
  21744. return this;
  21745. };
  21746. this.getHandler = function ( file ) {
  21747. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  21748. const regex = handlers[ i ];
  21749. const loader = handlers[ i + 1 ];
  21750. if ( regex.global ) regex.lastIndex = 0; // see #17920
  21751. if ( regex.test( file ) ) {
  21752. return loader;
  21753. }
  21754. }
  21755. return null;
  21756. };
  21757. }
  21758. const DefaultLoadingManager = new LoadingManager();
  21759. function Loader( manager ) {
  21760. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21761. this.crossOrigin = 'anonymous';
  21762. this.withCredentials = false;
  21763. this.path = '';
  21764. this.resourcePath = '';
  21765. this.requestHeader = {};
  21766. }
  21767. Object.assign( Loader.prototype, {
  21768. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  21769. loadAsync: function ( url, onProgress ) {
  21770. const scope = this;
  21771. return new Promise( function ( resolve, reject ) {
  21772. scope.load( url, resolve, onProgress, reject );
  21773. } );
  21774. },
  21775. parse: function ( /* data */ ) {},
  21776. setCrossOrigin: function ( crossOrigin ) {
  21777. this.crossOrigin = crossOrigin;
  21778. return this;
  21779. },
  21780. setWithCredentials: function ( value ) {
  21781. this.withCredentials = value;
  21782. return this;
  21783. },
  21784. setPath: function ( path ) {
  21785. this.path = path;
  21786. return this;
  21787. },
  21788. setResourcePath: function ( resourcePath ) {
  21789. this.resourcePath = resourcePath;
  21790. return this;
  21791. },
  21792. setRequestHeader: function ( requestHeader ) {
  21793. this.requestHeader = requestHeader;
  21794. return this;
  21795. }
  21796. } );
  21797. const loading = {};
  21798. function FileLoader( manager ) {
  21799. Loader.call( this, manager );
  21800. }
  21801. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  21802. constructor: FileLoader,
  21803. load: function ( url, onLoad, onProgress, onError ) {
  21804. if ( url === undefined ) url = '';
  21805. if ( this.path !== undefined ) url = this.path + url;
  21806. url = this.manager.resolveURL( url );
  21807. const scope = this;
  21808. const cached = Cache.get( url );
  21809. if ( cached !== undefined ) {
  21810. scope.manager.itemStart( url );
  21811. setTimeout( function () {
  21812. if ( onLoad ) onLoad( cached );
  21813. scope.manager.itemEnd( url );
  21814. }, 0 );
  21815. return cached;
  21816. }
  21817. // Check if request is duplicate
  21818. if ( loading[ url ] !== undefined ) {
  21819. loading[ url ].push( {
  21820. onLoad: onLoad,
  21821. onProgress: onProgress,
  21822. onError: onError
  21823. } );
  21824. return;
  21825. }
  21826. // Check for data: URI
  21827. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21828. const dataUriRegexResult = url.match( dataUriRegex );
  21829. let request;
  21830. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21831. if ( dataUriRegexResult ) {
  21832. const mimeType = dataUriRegexResult[ 1 ];
  21833. const isBase64 = !! dataUriRegexResult[ 2 ];
  21834. let data = dataUriRegexResult[ 3 ];
  21835. data = decodeURIComponent( data );
  21836. if ( isBase64 ) data = atob( data );
  21837. try {
  21838. let response;
  21839. const responseType = ( this.responseType || '' ).toLowerCase();
  21840. switch ( responseType ) {
  21841. case 'arraybuffer':
  21842. case 'blob':
  21843. const view = new Uint8Array( data.length );
  21844. for ( let i = 0; i < data.length; i ++ ) {
  21845. view[ i ] = data.charCodeAt( i );
  21846. }
  21847. if ( responseType === 'blob' ) {
  21848. response = new Blob( [ view.buffer ], { type: mimeType } );
  21849. } else {
  21850. response = view.buffer;
  21851. }
  21852. break;
  21853. case 'document':
  21854. const parser = new DOMParser();
  21855. response = parser.parseFromString( data, mimeType );
  21856. break;
  21857. case 'json':
  21858. response = JSON.parse( data );
  21859. break;
  21860. default: // 'text' or other
  21861. response = data;
  21862. break;
  21863. }
  21864. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21865. setTimeout( function () {
  21866. if ( onLoad ) onLoad( response );
  21867. scope.manager.itemEnd( url );
  21868. }, 0 );
  21869. } catch ( error ) {
  21870. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21871. setTimeout( function () {
  21872. if ( onError ) onError( error );
  21873. scope.manager.itemError( url );
  21874. scope.manager.itemEnd( url );
  21875. }, 0 );
  21876. }
  21877. } else {
  21878. // Initialise array for duplicate requests
  21879. loading[ url ] = [];
  21880. loading[ url ].push( {
  21881. onLoad: onLoad,
  21882. onProgress: onProgress,
  21883. onError: onError
  21884. } );
  21885. request = new XMLHttpRequest();
  21886. request.open( 'GET', url, true );
  21887. request.addEventListener( 'load', function ( event ) {
  21888. const response = this.response;
  21889. const callbacks = loading[ url ];
  21890. delete loading[ url ];
  21891. if ( this.status === 200 || this.status === 0 ) {
  21892. // Some browsers return HTTP Status 0 when using non-http protocol
  21893. // e.g. 'file://' or 'data://'. Handle as success.
  21894. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  21895. // Add to cache only on HTTP success, so that we do not cache
  21896. // error response bodies as proper responses to requests.
  21897. Cache.add( url, response );
  21898. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21899. const callback = callbacks[ i ];
  21900. if ( callback.onLoad ) callback.onLoad( response );
  21901. }
  21902. scope.manager.itemEnd( url );
  21903. } else {
  21904. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21905. const callback = callbacks[ i ];
  21906. if ( callback.onError ) callback.onError( event );
  21907. }
  21908. scope.manager.itemError( url );
  21909. scope.manager.itemEnd( url );
  21910. }
  21911. }, false );
  21912. request.addEventListener( 'progress', function ( event ) {
  21913. const callbacks = loading[ url ];
  21914. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21915. const callback = callbacks[ i ];
  21916. if ( callback.onProgress ) callback.onProgress( event );
  21917. }
  21918. }, false );
  21919. request.addEventListener( 'error', function ( event ) {
  21920. const callbacks = loading[ url ];
  21921. delete loading[ url ];
  21922. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21923. const callback = callbacks[ i ];
  21924. if ( callback.onError ) callback.onError( event );
  21925. }
  21926. scope.manager.itemError( url );
  21927. scope.manager.itemEnd( url );
  21928. }, false );
  21929. request.addEventListener( 'abort', function ( event ) {
  21930. const callbacks = loading[ url ];
  21931. delete loading[ url ];
  21932. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  21933. const callback = callbacks[ i ];
  21934. if ( callback.onError ) callback.onError( event );
  21935. }
  21936. scope.manager.itemError( url );
  21937. scope.manager.itemEnd( url );
  21938. }, false );
  21939. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  21940. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  21941. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  21942. for ( const header in this.requestHeader ) {
  21943. request.setRequestHeader( header, this.requestHeader[ header ] );
  21944. }
  21945. request.send( null );
  21946. }
  21947. scope.manager.itemStart( url );
  21948. return request;
  21949. },
  21950. setResponseType: function ( value ) {
  21951. this.responseType = value;
  21952. return this;
  21953. },
  21954. setMimeType: function ( value ) {
  21955. this.mimeType = value;
  21956. return this;
  21957. }
  21958. } );
  21959. function AnimationLoader( manager ) {
  21960. Loader.call( this, manager );
  21961. }
  21962. AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  21963. constructor: AnimationLoader,
  21964. load: function ( url, onLoad, onProgress, onError ) {
  21965. const scope = this;
  21966. const loader = new FileLoader( scope.manager );
  21967. loader.setPath( scope.path );
  21968. loader.setRequestHeader( scope.requestHeader );
  21969. loader.setWithCredentials( scope.withCredentials );
  21970. loader.load( url, function ( text ) {
  21971. try {
  21972. onLoad( scope.parse( JSON.parse( text ) ) );
  21973. } catch ( e ) {
  21974. if ( onError ) {
  21975. onError( e );
  21976. } else {
  21977. console.error( e );
  21978. }
  21979. scope.manager.itemError( url );
  21980. }
  21981. }, onProgress, onError );
  21982. },
  21983. parse: function ( json ) {
  21984. const animations = [];
  21985. for ( let i = 0; i < json.length; i ++ ) {
  21986. const clip = AnimationClip.parse( json[ i ] );
  21987. animations.push( clip );
  21988. }
  21989. return animations;
  21990. }
  21991. } );
  21992. /**
  21993. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21994. *
  21995. * Sub classes have to implement the parse() method which will be used in load().
  21996. */
  21997. function CompressedTextureLoader( manager ) {
  21998. Loader.call( this, manager );
  21999. }
  22000. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22001. constructor: CompressedTextureLoader,
  22002. load: function ( url, onLoad, onProgress, onError ) {
  22003. const scope = this;
  22004. const images = [];
  22005. const texture = new CompressedTexture();
  22006. const loader = new FileLoader( this.manager );
  22007. loader.setPath( this.path );
  22008. loader.setResponseType( 'arraybuffer' );
  22009. loader.setRequestHeader( this.requestHeader );
  22010. loader.setWithCredentials( scope.withCredentials );
  22011. let loaded = 0;
  22012. function loadTexture( i ) {
  22013. loader.load( url[ i ], function ( buffer ) {
  22014. const texDatas = scope.parse( buffer, true );
  22015. images[ i ] = {
  22016. width: texDatas.width,
  22017. height: texDatas.height,
  22018. format: texDatas.format,
  22019. mipmaps: texDatas.mipmaps
  22020. };
  22021. loaded += 1;
  22022. if ( loaded === 6 ) {
  22023. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  22024. texture.image = images;
  22025. texture.format = texDatas.format;
  22026. texture.needsUpdate = true;
  22027. if ( onLoad ) onLoad( texture );
  22028. }
  22029. }, onProgress, onError );
  22030. }
  22031. if ( Array.isArray( url ) ) {
  22032. for ( let i = 0, il = url.length; i < il; ++ i ) {
  22033. loadTexture( i );
  22034. }
  22035. } else {
  22036. // compressed cubemap texture stored in a single DDS file
  22037. loader.load( url, function ( buffer ) {
  22038. const texDatas = scope.parse( buffer, true );
  22039. if ( texDatas.isCubemap ) {
  22040. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22041. for ( let f = 0; f < faces; f ++ ) {
  22042. images[ f ] = { mipmaps: [] };
  22043. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  22044. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22045. images[ f ].format = texDatas.format;
  22046. images[ f ].width = texDatas.width;
  22047. images[ f ].height = texDatas.height;
  22048. }
  22049. }
  22050. texture.image = images;
  22051. } else {
  22052. texture.image.width = texDatas.width;
  22053. texture.image.height = texDatas.height;
  22054. texture.mipmaps = texDatas.mipmaps;
  22055. }
  22056. if ( texDatas.mipmapCount === 1 ) {
  22057. texture.minFilter = LinearFilter;
  22058. }
  22059. texture.format = texDatas.format;
  22060. texture.needsUpdate = true;
  22061. if ( onLoad ) onLoad( texture );
  22062. }, onProgress, onError );
  22063. }
  22064. return texture;
  22065. }
  22066. } );
  22067. function ImageLoader( manager ) {
  22068. Loader.call( this, manager );
  22069. }
  22070. ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22071. constructor: ImageLoader,
  22072. load: function ( url, onLoad, onProgress, onError ) {
  22073. if ( this.path !== undefined ) url = this.path + url;
  22074. url = this.manager.resolveURL( url );
  22075. const scope = this;
  22076. const cached = Cache.get( url );
  22077. if ( cached !== undefined ) {
  22078. scope.manager.itemStart( url );
  22079. setTimeout( function () {
  22080. if ( onLoad ) onLoad( cached );
  22081. scope.manager.itemEnd( url );
  22082. }, 0 );
  22083. return cached;
  22084. }
  22085. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  22086. function onImageLoad() {
  22087. image.removeEventListener( 'load', onImageLoad, false );
  22088. image.removeEventListener( 'error', onImageError, false );
  22089. Cache.add( url, this );
  22090. if ( onLoad ) onLoad( this );
  22091. scope.manager.itemEnd( url );
  22092. }
  22093. function onImageError( event ) {
  22094. image.removeEventListener( 'load', onImageLoad, false );
  22095. image.removeEventListener( 'error', onImageError, false );
  22096. if ( onError ) onError( event );
  22097. scope.manager.itemError( url );
  22098. scope.manager.itemEnd( url );
  22099. }
  22100. image.addEventListener( 'load', onImageLoad, false );
  22101. image.addEventListener( 'error', onImageError, false );
  22102. if ( url.substr( 0, 5 ) !== 'data:' ) {
  22103. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  22104. }
  22105. scope.manager.itemStart( url );
  22106. image.src = url;
  22107. return image;
  22108. }
  22109. } );
  22110. function CubeTextureLoader( manager ) {
  22111. Loader.call( this, manager );
  22112. }
  22113. CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22114. constructor: CubeTextureLoader,
  22115. load: function ( urls, onLoad, onProgress, onError ) {
  22116. const texture = new CubeTexture();
  22117. const loader = new ImageLoader( this.manager );
  22118. loader.setCrossOrigin( this.crossOrigin );
  22119. loader.setPath( this.path );
  22120. let loaded = 0;
  22121. function loadTexture( i ) {
  22122. loader.load( urls[ i ], function ( image ) {
  22123. texture.images[ i ] = image;
  22124. loaded ++;
  22125. if ( loaded === 6 ) {
  22126. texture.needsUpdate = true;
  22127. if ( onLoad ) onLoad( texture );
  22128. }
  22129. }, undefined, onError );
  22130. }
  22131. for ( let i = 0; i < urls.length; ++ i ) {
  22132. loadTexture( i );
  22133. }
  22134. return texture;
  22135. }
  22136. } );
  22137. /**
  22138. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22139. *
  22140. * Sub classes have to implement the parse() method which will be used in load().
  22141. */
  22142. function DataTextureLoader( manager ) {
  22143. Loader.call( this, manager );
  22144. }
  22145. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22146. constructor: DataTextureLoader,
  22147. load: function ( url, onLoad, onProgress, onError ) {
  22148. const scope = this;
  22149. const texture = new DataTexture();
  22150. const loader = new FileLoader( this.manager );
  22151. loader.setResponseType( 'arraybuffer' );
  22152. loader.setRequestHeader( this.requestHeader );
  22153. loader.setPath( this.path );
  22154. loader.setWithCredentials( scope.withCredentials );
  22155. loader.load( url, function ( buffer ) {
  22156. const texData = scope.parse( buffer );
  22157. if ( ! texData ) return;
  22158. if ( texData.image !== undefined ) {
  22159. texture.image = texData.image;
  22160. } else if ( texData.data !== undefined ) {
  22161. texture.image.width = texData.width;
  22162. texture.image.height = texData.height;
  22163. texture.image.data = texData.data;
  22164. }
  22165. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22166. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22167. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22168. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22169. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22170. if ( texData.format !== undefined ) {
  22171. texture.format = texData.format;
  22172. }
  22173. if ( texData.type !== undefined ) {
  22174. texture.type = texData.type;
  22175. }
  22176. if ( texData.mipmaps !== undefined ) {
  22177. texture.mipmaps = texData.mipmaps;
  22178. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22179. }
  22180. if ( texData.mipmapCount === 1 ) {
  22181. texture.minFilter = LinearFilter;
  22182. }
  22183. texture.needsUpdate = true;
  22184. if ( onLoad ) onLoad( texture, texData );
  22185. }, onProgress, onError );
  22186. return texture;
  22187. }
  22188. } );
  22189. function TextureLoader( manager ) {
  22190. Loader.call( this, manager );
  22191. }
  22192. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22193. constructor: TextureLoader,
  22194. load: function ( url, onLoad, onProgress, onError ) {
  22195. const texture = new Texture();
  22196. const loader = new ImageLoader( this.manager );
  22197. loader.setCrossOrigin( this.crossOrigin );
  22198. loader.setPath( this.path );
  22199. loader.load( url, function ( image ) {
  22200. texture.image = image;
  22201. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22202. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  22203. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22204. texture.needsUpdate = true;
  22205. if ( onLoad !== undefined ) {
  22206. onLoad( texture );
  22207. }
  22208. }, onProgress, onError );
  22209. return texture;
  22210. }
  22211. } );
  22212. /**
  22213. * Extensible curve object.
  22214. *
  22215. * Some common of curve methods:
  22216. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  22217. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  22218. * .getPoints(), .getSpacedPoints()
  22219. * .getLength()
  22220. * .updateArcLengths()
  22221. *
  22222. * This following curves inherit from THREE.Curve:
  22223. *
  22224. * -- 2D curves --
  22225. * THREE.ArcCurve
  22226. * THREE.CubicBezierCurve
  22227. * THREE.EllipseCurve
  22228. * THREE.LineCurve
  22229. * THREE.QuadraticBezierCurve
  22230. * THREE.SplineCurve
  22231. *
  22232. * -- 3D curves --
  22233. * THREE.CatmullRomCurve3
  22234. * THREE.CubicBezierCurve3
  22235. * THREE.LineCurve3
  22236. * THREE.QuadraticBezierCurve3
  22237. *
  22238. * A series of curves can be represented as a THREE.CurvePath.
  22239. *
  22240. **/
  22241. function Curve() {
  22242. this.type = 'Curve';
  22243. this.arcLengthDivisions = 200;
  22244. }
  22245. Object.assign( Curve.prototype, {
  22246. // Virtual base class method to overwrite and implement in subclasses
  22247. // - t [0 .. 1]
  22248. getPoint: function ( /* t, optionalTarget */ ) {
  22249. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  22250. return null;
  22251. },
  22252. // Get point at relative position in curve according to arc length
  22253. // - u [0 .. 1]
  22254. getPointAt: function ( u, optionalTarget ) {
  22255. const t = this.getUtoTmapping( u );
  22256. return this.getPoint( t, optionalTarget );
  22257. },
  22258. // Get sequence of points using getPoint( t )
  22259. getPoints: function ( divisions = 5 ) {
  22260. const points = [];
  22261. for ( let d = 0; d <= divisions; d ++ ) {
  22262. points.push( this.getPoint( d / divisions ) );
  22263. }
  22264. return points;
  22265. },
  22266. // Get sequence of points using getPointAt( u )
  22267. getSpacedPoints: function ( divisions = 5 ) {
  22268. const points = [];
  22269. for ( let d = 0; d <= divisions; d ++ ) {
  22270. points.push( this.getPointAt( d / divisions ) );
  22271. }
  22272. return points;
  22273. },
  22274. // Get total curve arc length
  22275. getLength: function () {
  22276. const lengths = this.getLengths();
  22277. return lengths[ lengths.length - 1 ];
  22278. },
  22279. // Get list of cumulative segment lengths
  22280. getLengths: function ( divisions ) {
  22281. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  22282. if ( this.cacheArcLengths &&
  22283. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22284. ! this.needsUpdate ) {
  22285. return this.cacheArcLengths;
  22286. }
  22287. this.needsUpdate = false;
  22288. const cache = [];
  22289. let current, last = this.getPoint( 0 );
  22290. let sum = 0;
  22291. cache.push( 0 );
  22292. for ( let p = 1; p <= divisions; p ++ ) {
  22293. current = this.getPoint( p / divisions );
  22294. sum += current.distanceTo( last );
  22295. cache.push( sum );
  22296. last = current;
  22297. }
  22298. this.cacheArcLengths = cache;
  22299. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22300. },
  22301. updateArcLengths: function () {
  22302. this.needsUpdate = true;
  22303. this.getLengths();
  22304. },
  22305. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22306. getUtoTmapping: function ( u, distance ) {
  22307. const arcLengths = this.getLengths();
  22308. let i = 0;
  22309. const il = arcLengths.length;
  22310. let targetArcLength; // The targeted u distance value to get
  22311. if ( distance ) {
  22312. targetArcLength = distance;
  22313. } else {
  22314. targetArcLength = u * arcLengths[ il - 1 ];
  22315. }
  22316. // binary search for the index with largest value smaller than target u distance
  22317. let low = 0, high = il - 1, comparison;
  22318. while ( low <= high ) {
  22319. 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
  22320. comparison = arcLengths[ i ] - targetArcLength;
  22321. if ( comparison < 0 ) {
  22322. low = i + 1;
  22323. } else if ( comparison > 0 ) {
  22324. high = i - 1;
  22325. } else {
  22326. high = i;
  22327. break;
  22328. // DONE
  22329. }
  22330. }
  22331. i = high;
  22332. if ( arcLengths[ i ] === targetArcLength ) {
  22333. return i / ( il - 1 );
  22334. }
  22335. // we could get finer grain at lengths, or use simple interpolation between two points
  22336. const lengthBefore = arcLengths[ i ];
  22337. const lengthAfter = arcLengths[ i + 1 ];
  22338. const segmentLength = lengthAfter - lengthBefore;
  22339. // determine where we are between the 'before' and 'after' points
  22340. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  22341. // add that fractional amount to t
  22342. const t = ( i + segmentFraction ) / ( il - 1 );
  22343. return t;
  22344. },
  22345. // Returns a unit vector tangent at t
  22346. // In case any sub curve does not implement its tangent derivation,
  22347. // 2 points a small delta apart will be used to find its gradient
  22348. // which seems to give a reasonable approximation
  22349. getTangent: function ( t, optionalTarget ) {
  22350. const delta = 0.0001;
  22351. let t1 = t - delta;
  22352. let t2 = t + delta;
  22353. // Capping in case of danger
  22354. if ( t1 < 0 ) t1 = 0;
  22355. if ( t2 > 1 ) t2 = 1;
  22356. const pt1 = this.getPoint( t1 );
  22357. const pt2 = this.getPoint( t2 );
  22358. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  22359. tangent.copy( pt2 ).sub( pt1 ).normalize();
  22360. return tangent;
  22361. },
  22362. getTangentAt: function ( u, optionalTarget ) {
  22363. const t = this.getUtoTmapping( u );
  22364. return this.getTangent( t, optionalTarget );
  22365. },
  22366. computeFrenetFrames: function ( segments, closed ) {
  22367. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22368. const normal = new Vector3();
  22369. const tangents = [];
  22370. const normals = [];
  22371. const binormals = [];
  22372. const vec = new Vector3();
  22373. const mat = new Matrix4();
  22374. // compute the tangent vectors for each segment on the curve
  22375. for ( let i = 0; i <= segments; i ++ ) {
  22376. const u = i / segments;
  22377. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  22378. tangents[ i ].normalize();
  22379. }
  22380. // select an initial normal vector perpendicular to the first tangent vector,
  22381. // and in the direction of the minimum tangent xyz component
  22382. normals[ 0 ] = new Vector3();
  22383. binormals[ 0 ] = new Vector3();
  22384. let min = Number.MAX_VALUE;
  22385. const tx = Math.abs( tangents[ 0 ].x );
  22386. const ty = Math.abs( tangents[ 0 ].y );
  22387. const tz = Math.abs( tangents[ 0 ].z );
  22388. if ( tx <= min ) {
  22389. min = tx;
  22390. normal.set( 1, 0, 0 );
  22391. }
  22392. if ( ty <= min ) {
  22393. min = ty;
  22394. normal.set( 0, 1, 0 );
  22395. }
  22396. if ( tz <= min ) {
  22397. normal.set( 0, 0, 1 );
  22398. }
  22399. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22400. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22401. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22402. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22403. for ( let i = 1; i <= segments; i ++ ) {
  22404. normals[ i ] = normals[ i - 1 ].clone();
  22405. binormals[ i ] = binormals[ i - 1 ].clone();
  22406. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22407. if ( vec.length() > Number.EPSILON ) {
  22408. vec.normalize();
  22409. const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  22410. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22411. }
  22412. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22413. }
  22414. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22415. if ( closed === true ) {
  22416. let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  22417. theta /= segments;
  22418. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  22419. theta = - theta;
  22420. }
  22421. for ( let i = 1; i <= segments; i ++ ) {
  22422. // twist a little...
  22423. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22424. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22425. }
  22426. }
  22427. return {
  22428. tangents: tangents,
  22429. normals: normals,
  22430. binormals: binormals
  22431. };
  22432. },
  22433. clone: function () {
  22434. return new this.constructor().copy( this );
  22435. },
  22436. copy: function ( source ) {
  22437. this.arcLengthDivisions = source.arcLengthDivisions;
  22438. return this;
  22439. },
  22440. toJSON: function () {
  22441. const data = {
  22442. metadata: {
  22443. version: 4.5,
  22444. type: 'Curve',
  22445. generator: 'Curve.toJSON'
  22446. }
  22447. };
  22448. data.arcLengthDivisions = this.arcLengthDivisions;
  22449. data.type = this.type;
  22450. return data;
  22451. },
  22452. fromJSON: function ( json ) {
  22453. this.arcLengthDivisions = json.arcLengthDivisions;
  22454. return this;
  22455. }
  22456. } );
  22457. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  22458. Curve.call( this );
  22459. this.type = 'EllipseCurve';
  22460. this.aX = aX || 0;
  22461. this.aY = aY || 0;
  22462. this.xRadius = xRadius || 1;
  22463. this.yRadius = yRadius || 1;
  22464. this.aStartAngle = aStartAngle || 0;
  22465. this.aEndAngle = aEndAngle || 2 * Math.PI;
  22466. this.aClockwise = aClockwise || false;
  22467. this.aRotation = aRotation || 0;
  22468. }
  22469. EllipseCurve.prototype = Object.create( Curve.prototype );
  22470. EllipseCurve.prototype.constructor = EllipseCurve;
  22471. EllipseCurve.prototype.isEllipseCurve = true;
  22472. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  22473. const point = optionalTarget || new Vector2();
  22474. const twoPi = Math.PI * 2;
  22475. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22476. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  22477. // ensures that deltaAngle is 0 .. 2 PI
  22478. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  22479. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  22480. if ( deltaAngle < Number.EPSILON ) {
  22481. if ( samePoints ) {
  22482. deltaAngle = 0;
  22483. } else {
  22484. deltaAngle = twoPi;
  22485. }
  22486. }
  22487. if ( this.aClockwise === true && ! samePoints ) {
  22488. if ( deltaAngle === twoPi ) {
  22489. deltaAngle = - twoPi;
  22490. } else {
  22491. deltaAngle = deltaAngle - twoPi;
  22492. }
  22493. }
  22494. const angle = this.aStartAngle + t * deltaAngle;
  22495. let x = this.aX + this.xRadius * Math.cos( angle );
  22496. let y = this.aY + this.yRadius * Math.sin( angle );
  22497. if ( this.aRotation !== 0 ) {
  22498. const cos = Math.cos( this.aRotation );
  22499. const sin = Math.sin( this.aRotation );
  22500. const tx = x - this.aX;
  22501. const ty = y - this.aY;
  22502. // Rotate the point about the center of the ellipse.
  22503. x = tx * cos - ty * sin + this.aX;
  22504. y = tx * sin + ty * cos + this.aY;
  22505. }
  22506. return point.set( x, y );
  22507. };
  22508. EllipseCurve.prototype.copy = function ( source ) {
  22509. Curve.prototype.copy.call( this, source );
  22510. this.aX = source.aX;
  22511. this.aY = source.aY;
  22512. this.xRadius = source.xRadius;
  22513. this.yRadius = source.yRadius;
  22514. this.aStartAngle = source.aStartAngle;
  22515. this.aEndAngle = source.aEndAngle;
  22516. this.aClockwise = source.aClockwise;
  22517. this.aRotation = source.aRotation;
  22518. return this;
  22519. };
  22520. EllipseCurve.prototype.toJSON = function () {
  22521. const data = Curve.prototype.toJSON.call( this );
  22522. data.aX = this.aX;
  22523. data.aY = this.aY;
  22524. data.xRadius = this.xRadius;
  22525. data.yRadius = this.yRadius;
  22526. data.aStartAngle = this.aStartAngle;
  22527. data.aEndAngle = this.aEndAngle;
  22528. data.aClockwise = this.aClockwise;
  22529. data.aRotation = this.aRotation;
  22530. return data;
  22531. };
  22532. EllipseCurve.prototype.fromJSON = function ( json ) {
  22533. Curve.prototype.fromJSON.call( this, json );
  22534. this.aX = json.aX;
  22535. this.aY = json.aY;
  22536. this.xRadius = json.xRadius;
  22537. this.yRadius = json.yRadius;
  22538. this.aStartAngle = json.aStartAngle;
  22539. this.aEndAngle = json.aEndAngle;
  22540. this.aClockwise = json.aClockwise;
  22541. this.aRotation = json.aRotation;
  22542. return this;
  22543. };
  22544. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22545. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  22546. this.type = 'ArcCurve';
  22547. }
  22548. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  22549. ArcCurve.prototype.constructor = ArcCurve;
  22550. ArcCurve.prototype.isArcCurve = true;
  22551. /**
  22552. * Centripetal CatmullRom Curve - which is useful for avoiding
  22553. * cusps and self-intersections in non-uniform catmull rom curves.
  22554. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22555. *
  22556. * curve.type accepts centripetal(default), chordal and catmullrom
  22557. * curve.tension is used for catmullrom which defaults to 0.5
  22558. */
  22559. /*
  22560. Based on an optimized c++ solution in
  22561. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22562. - http://ideone.com/NoEbVM
  22563. This CubicPoly class could be used for reusing some variables and calculations,
  22564. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22565. which can be placed in CurveUtils.
  22566. */
  22567. function CubicPoly() {
  22568. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  22569. /*
  22570. * Compute coefficients for a cubic polynomial
  22571. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22572. * such that
  22573. * p(0) = x0, p(1) = x1
  22574. * and
  22575. * p'(0) = t0, p'(1) = t1.
  22576. */
  22577. function init( x0, x1, t0, t1 ) {
  22578. c0 = x0;
  22579. c1 = t0;
  22580. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  22581. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22582. }
  22583. return {
  22584. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  22585. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  22586. },
  22587. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  22588. // compute tangents when parameterized in [t1,t2]
  22589. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  22590. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  22591. // rescale tangents for parametrization in [0,1]
  22592. t1 *= dt1;
  22593. t2 *= dt1;
  22594. init( x1, x2, t1, t2 );
  22595. },
  22596. calc: function ( t ) {
  22597. const t2 = t * t;
  22598. const t3 = t2 * t;
  22599. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22600. }
  22601. };
  22602. }
  22603. //
  22604. const tmp = new Vector3();
  22605. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  22606. function CatmullRomCurve3( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  22607. Curve.call( this );
  22608. this.type = 'CatmullRomCurve3';
  22609. this.points = points;
  22610. this.closed = closed;
  22611. this.curveType = curveType;
  22612. this.tension = tension;
  22613. }
  22614. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  22615. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22616. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22617. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  22618. const point = optionalTarget;
  22619. const points = this.points;
  22620. const l = points.length;
  22621. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  22622. let intPoint = Math.floor( p );
  22623. let weight = p - intPoint;
  22624. if ( this.closed ) {
  22625. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  22626. } else if ( weight === 0 && intPoint === l - 1 ) {
  22627. intPoint = l - 2;
  22628. weight = 1;
  22629. }
  22630. let p0, p3; // 4 points (p1 & p2 defined below)
  22631. if ( this.closed || intPoint > 0 ) {
  22632. p0 = points[ ( intPoint - 1 ) % l ];
  22633. } else {
  22634. // extrapolate first point
  22635. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  22636. p0 = tmp;
  22637. }
  22638. const p1 = points[ intPoint % l ];
  22639. const p2 = points[ ( intPoint + 1 ) % l ];
  22640. if ( this.closed || intPoint + 2 < l ) {
  22641. p3 = points[ ( intPoint + 2 ) % l ];
  22642. } else {
  22643. // extrapolate last point
  22644. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  22645. p3 = tmp;
  22646. }
  22647. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  22648. // init Centripetal / Chordal Catmull-Rom
  22649. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22650. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  22651. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  22652. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  22653. // safety check for repeated points
  22654. if ( dt1 < 1e-4 ) dt1 = 1.0;
  22655. if ( dt0 < 1e-4 ) dt0 = dt1;
  22656. if ( dt2 < 1e-4 ) dt2 = dt1;
  22657. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  22658. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  22659. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  22660. } else if ( this.curveType === 'catmullrom' ) {
  22661. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  22662. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  22663. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  22664. }
  22665. point.set(
  22666. px.calc( weight ),
  22667. py.calc( weight ),
  22668. pz.calc( weight )
  22669. );
  22670. return point;
  22671. };
  22672. CatmullRomCurve3.prototype.copy = function ( source ) {
  22673. Curve.prototype.copy.call( this, source );
  22674. this.points = [];
  22675. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  22676. const point = source.points[ i ];
  22677. this.points.push( point.clone() );
  22678. }
  22679. this.closed = source.closed;
  22680. this.curveType = source.curveType;
  22681. this.tension = source.tension;
  22682. return this;
  22683. };
  22684. CatmullRomCurve3.prototype.toJSON = function () {
  22685. const data = Curve.prototype.toJSON.call( this );
  22686. data.points = [];
  22687. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  22688. const point = this.points[ i ];
  22689. data.points.push( point.toArray() );
  22690. }
  22691. data.closed = this.closed;
  22692. data.curveType = this.curveType;
  22693. data.tension = this.tension;
  22694. return data;
  22695. };
  22696. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  22697. Curve.prototype.fromJSON.call( this, json );
  22698. this.points = [];
  22699. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  22700. const point = json.points[ i ];
  22701. this.points.push( new Vector3().fromArray( point ) );
  22702. }
  22703. this.closed = json.closed;
  22704. this.curveType = json.curveType;
  22705. this.tension = json.tension;
  22706. return this;
  22707. };
  22708. /**
  22709. * Bezier Curves formulas obtained from
  22710. * http://en.wikipedia.org/wiki/Bézier_curve
  22711. */
  22712. function CatmullRom( t, p0, p1, p2, p3 ) {
  22713. const v0 = ( p2 - p0 ) * 0.5;
  22714. const v1 = ( p3 - p1 ) * 0.5;
  22715. const t2 = t * t;
  22716. const t3 = t * t2;
  22717. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  22718. }
  22719. //
  22720. function QuadraticBezierP0( t, p ) {
  22721. const k = 1 - t;
  22722. return k * k * p;
  22723. }
  22724. function QuadraticBezierP1( t, p ) {
  22725. return 2 * ( 1 - t ) * t * p;
  22726. }
  22727. function QuadraticBezierP2( t, p ) {
  22728. return t * t * p;
  22729. }
  22730. function QuadraticBezier( t, p0, p1, p2 ) {
  22731. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  22732. QuadraticBezierP2( t, p2 );
  22733. }
  22734. //
  22735. function CubicBezierP0( t, p ) {
  22736. const k = 1 - t;
  22737. return k * k * k * p;
  22738. }
  22739. function CubicBezierP1( t, p ) {
  22740. const k = 1 - t;
  22741. return 3 * k * k * t * p;
  22742. }
  22743. function CubicBezierP2( t, p ) {
  22744. return 3 * ( 1 - t ) * t * t * p;
  22745. }
  22746. function CubicBezierP3( t, p ) {
  22747. return t * t * t * p;
  22748. }
  22749. function CubicBezier( t, p0, p1, p2, p3 ) {
  22750. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  22751. CubicBezierP3( t, p3 );
  22752. }
  22753. function CubicBezierCurve( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  22754. Curve.call( this );
  22755. this.type = 'CubicBezierCurve';
  22756. this.v0 = v0;
  22757. this.v1 = v1;
  22758. this.v2 = v2;
  22759. this.v3 = v3;
  22760. }
  22761. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  22762. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22763. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22764. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2() ) {
  22765. const point = optionalTarget;
  22766. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  22767. point.set(
  22768. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  22769. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  22770. );
  22771. return point;
  22772. };
  22773. CubicBezierCurve.prototype.copy = function ( source ) {
  22774. Curve.prototype.copy.call( this, source );
  22775. this.v0.copy( source.v0 );
  22776. this.v1.copy( source.v1 );
  22777. this.v2.copy( source.v2 );
  22778. this.v3.copy( source.v3 );
  22779. return this;
  22780. };
  22781. CubicBezierCurve.prototype.toJSON = function () {
  22782. const data = Curve.prototype.toJSON.call( this );
  22783. data.v0 = this.v0.toArray();
  22784. data.v1 = this.v1.toArray();
  22785. data.v2 = this.v2.toArray();
  22786. data.v3 = this.v3.toArray();
  22787. return data;
  22788. };
  22789. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  22790. Curve.prototype.fromJSON.call( this, json );
  22791. this.v0.fromArray( json.v0 );
  22792. this.v1.fromArray( json.v1 );
  22793. this.v2.fromArray( json.v2 );
  22794. this.v3.fromArray( json.v3 );
  22795. return this;
  22796. };
  22797. function CubicBezierCurve3( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  22798. Curve.call( this );
  22799. this.type = 'CubicBezierCurve3';
  22800. this.v0 = v0;
  22801. this.v1 = v1;
  22802. this.v2 = v2;
  22803. this.v3 = v3;
  22804. }
  22805. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  22806. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  22807. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  22808. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  22809. const point = optionalTarget;
  22810. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  22811. point.set(
  22812. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  22813. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  22814. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  22815. );
  22816. return point;
  22817. };
  22818. CubicBezierCurve3.prototype.copy = function ( source ) {
  22819. Curve.prototype.copy.call( this, source );
  22820. this.v0.copy( source.v0 );
  22821. this.v1.copy( source.v1 );
  22822. this.v2.copy( source.v2 );
  22823. this.v3.copy( source.v3 );
  22824. return this;
  22825. };
  22826. CubicBezierCurve3.prototype.toJSON = function () {
  22827. const data = Curve.prototype.toJSON.call( this );
  22828. data.v0 = this.v0.toArray();
  22829. data.v1 = this.v1.toArray();
  22830. data.v2 = this.v2.toArray();
  22831. data.v3 = this.v3.toArray();
  22832. return data;
  22833. };
  22834. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  22835. Curve.prototype.fromJSON.call( this, json );
  22836. this.v0.fromArray( json.v0 );
  22837. this.v1.fromArray( json.v1 );
  22838. this.v2.fromArray( json.v2 );
  22839. this.v3.fromArray( json.v3 );
  22840. return this;
  22841. };
  22842. function LineCurve( v1 = new Vector2(), v2 = new Vector2() ) {
  22843. Curve.call( this );
  22844. this.type = 'LineCurve';
  22845. this.v1 = v1;
  22846. this.v2 = v2;
  22847. }
  22848. LineCurve.prototype = Object.create( Curve.prototype );
  22849. LineCurve.prototype.constructor = LineCurve;
  22850. LineCurve.prototype.isLineCurve = true;
  22851. LineCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2() ) {
  22852. const point = optionalTarget;
  22853. if ( t === 1 ) {
  22854. point.copy( this.v2 );
  22855. } else {
  22856. point.copy( this.v2 ).sub( this.v1 );
  22857. point.multiplyScalar( t ).add( this.v1 );
  22858. }
  22859. return point;
  22860. };
  22861. // Line curve is linear, so we can overwrite default getPointAt
  22862. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  22863. return this.getPoint( u, optionalTarget );
  22864. };
  22865. LineCurve.prototype.getTangent = function ( t, optionalTarget ) {
  22866. const tangent = optionalTarget || new Vector2();
  22867. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  22868. return tangent;
  22869. };
  22870. LineCurve.prototype.copy = function ( source ) {
  22871. Curve.prototype.copy.call( this, source );
  22872. this.v1.copy( source.v1 );
  22873. this.v2.copy( source.v2 );
  22874. return this;
  22875. };
  22876. LineCurve.prototype.toJSON = function () {
  22877. const data = Curve.prototype.toJSON.call( this );
  22878. data.v1 = this.v1.toArray();
  22879. data.v2 = this.v2.toArray();
  22880. return data;
  22881. };
  22882. LineCurve.prototype.fromJSON = function ( json ) {
  22883. Curve.prototype.fromJSON.call( this, json );
  22884. this.v1.fromArray( json.v1 );
  22885. this.v2.fromArray( json.v2 );
  22886. return this;
  22887. };
  22888. function LineCurve3( v1 = new Vector3(), v2 = new Vector3() ) {
  22889. Curve.call( this );
  22890. this.type = 'LineCurve3';
  22891. this.v1 = v1;
  22892. this.v2 = v2;
  22893. }
  22894. LineCurve3.prototype = Object.create( Curve.prototype );
  22895. LineCurve3.prototype.constructor = LineCurve3;
  22896. LineCurve3.prototype.isLineCurve3 = true;
  22897. LineCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  22898. const point = optionalTarget;
  22899. if ( t === 1 ) {
  22900. point.copy( this.v2 );
  22901. } else {
  22902. point.copy( this.v2 ).sub( this.v1 );
  22903. point.multiplyScalar( t ).add( this.v1 );
  22904. }
  22905. return point;
  22906. };
  22907. // Line curve is linear, so we can overwrite default getPointAt
  22908. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  22909. return this.getPoint( u, optionalTarget );
  22910. };
  22911. LineCurve3.prototype.copy = function ( source ) {
  22912. Curve.prototype.copy.call( this, source );
  22913. this.v1.copy( source.v1 );
  22914. this.v2.copy( source.v2 );
  22915. return this;
  22916. };
  22917. LineCurve3.prototype.toJSON = function () {
  22918. const data = Curve.prototype.toJSON.call( this );
  22919. data.v1 = this.v1.toArray();
  22920. data.v2 = this.v2.toArray();
  22921. return data;
  22922. };
  22923. LineCurve3.prototype.fromJSON = function ( json ) {
  22924. Curve.prototype.fromJSON.call( this, json );
  22925. this.v1.fromArray( json.v1 );
  22926. this.v2.fromArray( json.v2 );
  22927. return this;
  22928. };
  22929. function QuadraticBezierCurve( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  22930. Curve.call( this );
  22931. this.type = 'QuadraticBezierCurve';
  22932. this.v0 = v0;
  22933. this.v1 = v1;
  22934. this.v2 = v2;
  22935. }
  22936. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  22937. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  22938. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  22939. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2() ) {
  22940. const point = optionalTarget;
  22941. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  22942. point.set(
  22943. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  22944. QuadraticBezier( t, v0.y, v1.y, v2.y )
  22945. );
  22946. return point;
  22947. };
  22948. QuadraticBezierCurve.prototype.copy = function ( source ) {
  22949. Curve.prototype.copy.call( this, source );
  22950. this.v0.copy( source.v0 );
  22951. this.v1.copy( source.v1 );
  22952. this.v2.copy( source.v2 );
  22953. return this;
  22954. };
  22955. QuadraticBezierCurve.prototype.toJSON = function () {
  22956. const data = Curve.prototype.toJSON.call( this );
  22957. data.v0 = this.v0.toArray();
  22958. data.v1 = this.v1.toArray();
  22959. data.v2 = this.v2.toArray();
  22960. return data;
  22961. };
  22962. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  22963. Curve.prototype.fromJSON.call( this, json );
  22964. this.v0.fromArray( json.v0 );
  22965. this.v1.fromArray( json.v1 );
  22966. this.v2.fromArray( json.v2 );
  22967. return this;
  22968. };
  22969. function QuadraticBezierCurve3( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  22970. Curve.call( this );
  22971. this.type = 'QuadraticBezierCurve3';
  22972. this.v0 = v0;
  22973. this.v1 = v1;
  22974. this.v2 = v2;
  22975. }
  22976. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  22977. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  22978. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  22979. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  22980. const point = optionalTarget;
  22981. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  22982. point.set(
  22983. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  22984. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  22985. QuadraticBezier( t, v0.z, v1.z, v2.z )
  22986. );
  22987. return point;
  22988. };
  22989. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  22990. Curve.prototype.copy.call( this, source );
  22991. this.v0.copy( source.v0 );
  22992. this.v1.copy( source.v1 );
  22993. this.v2.copy( source.v2 );
  22994. return this;
  22995. };
  22996. QuadraticBezierCurve3.prototype.toJSON = function () {
  22997. const data = Curve.prototype.toJSON.call( this );
  22998. data.v0 = this.v0.toArray();
  22999. data.v1 = this.v1.toArray();
  23000. data.v2 = this.v2.toArray();
  23001. return data;
  23002. };
  23003. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  23004. Curve.prototype.fromJSON.call( this, json );
  23005. this.v0.fromArray( json.v0 );
  23006. this.v1.fromArray( json.v1 );
  23007. this.v2.fromArray( json.v2 );
  23008. return this;
  23009. };
  23010. function SplineCurve( points = [] ) {
  23011. Curve.call( this );
  23012. this.type = 'SplineCurve';
  23013. this.points = points;
  23014. }
  23015. SplineCurve.prototype = Object.create( Curve.prototype );
  23016. SplineCurve.prototype.constructor = SplineCurve;
  23017. SplineCurve.prototype.isSplineCurve = true;
  23018. SplineCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2() ) {
  23019. const point = optionalTarget;
  23020. const points = this.points;
  23021. const p = ( points.length - 1 ) * t;
  23022. const intPoint = Math.floor( p );
  23023. const weight = p - intPoint;
  23024. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23025. const p1 = points[ intPoint ];
  23026. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23027. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23028. point.set(
  23029. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23030. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23031. );
  23032. return point;
  23033. };
  23034. SplineCurve.prototype.copy = function ( source ) {
  23035. Curve.prototype.copy.call( this, source );
  23036. this.points = [];
  23037. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23038. const point = source.points[ i ];
  23039. this.points.push( point.clone() );
  23040. }
  23041. return this;
  23042. };
  23043. SplineCurve.prototype.toJSON = function () {
  23044. const data = Curve.prototype.toJSON.call( this );
  23045. data.points = [];
  23046. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23047. const point = this.points[ i ];
  23048. data.points.push( point.toArray() );
  23049. }
  23050. return data;
  23051. };
  23052. SplineCurve.prototype.fromJSON = function ( json ) {
  23053. Curve.prototype.fromJSON.call( this, json );
  23054. this.points = [];
  23055. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23056. const point = json.points[ i ];
  23057. this.points.push( new Vector2().fromArray( point ) );
  23058. }
  23059. return this;
  23060. };
  23061. var Curves = /*#__PURE__*/Object.freeze({
  23062. __proto__: null,
  23063. ArcCurve: ArcCurve,
  23064. CatmullRomCurve3: CatmullRomCurve3,
  23065. CubicBezierCurve: CubicBezierCurve,
  23066. CubicBezierCurve3: CubicBezierCurve3,
  23067. EllipseCurve: EllipseCurve,
  23068. LineCurve: LineCurve,
  23069. LineCurve3: LineCurve3,
  23070. QuadraticBezierCurve: QuadraticBezierCurve,
  23071. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23072. SplineCurve: SplineCurve
  23073. });
  23074. /**************************************************************
  23075. * Curved Path - a curve path is simply a array of connected
  23076. * curves, but retains the api of a curve
  23077. **************************************************************/
  23078. function CurvePath() {
  23079. Curve.call( this );
  23080. this.type = 'CurvePath';
  23081. this.curves = [];
  23082. this.autoClose = false; // Automatically closes the path
  23083. }
  23084. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  23085. constructor: CurvePath,
  23086. add: function ( curve ) {
  23087. this.curves.push( curve );
  23088. },
  23089. closePath: function () {
  23090. // Add a line curve if start and end of lines are not connected
  23091. const startPoint = this.curves[ 0 ].getPoint( 0 );
  23092. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  23093. if ( ! startPoint.equals( endPoint ) ) {
  23094. this.curves.push( new LineCurve( endPoint, startPoint ) );
  23095. }
  23096. },
  23097. // To get accurate point with reference to
  23098. // entire path distance at time t,
  23099. // following has to be done:
  23100. // 1. Length of each sub path have to be known
  23101. // 2. Locate and identify type of curve
  23102. // 3. Get t for the curve
  23103. // 4. Return curve.getPointAt(t')
  23104. getPoint: function ( t ) {
  23105. const d = t * this.getLength();
  23106. const curveLengths = this.getCurveLengths();
  23107. let i = 0;
  23108. // To think about boundaries points.
  23109. while ( i < curveLengths.length ) {
  23110. if ( curveLengths[ i ] >= d ) {
  23111. const diff = curveLengths[ i ] - d;
  23112. const curve = this.curves[ i ];
  23113. const segmentLength = curve.getLength();
  23114. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23115. return curve.getPointAt( u );
  23116. }
  23117. i ++;
  23118. }
  23119. return null;
  23120. // loop where sum != 0, sum > d , sum+1 <d
  23121. },
  23122. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23123. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23124. // getPoint() depends on getLength
  23125. getLength: function () {
  23126. const lens = this.getCurveLengths();
  23127. return lens[ lens.length - 1 ];
  23128. },
  23129. // cacheLengths must be recalculated.
  23130. updateArcLengths: function () {
  23131. this.needsUpdate = true;
  23132. this.cacheLengths = null;
  23133. this.getCurveLengths();
  23134. },
  23135. // Compute lengths and cache them
  23136. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23137. getCurveLengths: function () {
  23138. // We use cache values if curves and cache array are same length
  23139. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  23140. return this.cacheLengths;
  23141. }
  23142. // Get length of sub-curve
  23143. // Push sums into cached array
  23144. const lengths = [];
  23145. let sums = 0;
  23146. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23147. sums += this.curves[ i ].getLength();
  23148. lengths.push( sums );
  23149. }
  23150. this.cacheLengths = lengths;
  23151. return lengths;
  23152. },
  23153. getSpacedPoints: function ( divisions = 40 ) {
  23154. const points = [];
  23155. for ( let i = 0; i <= divisions; i ++ ) {
  23156. points.push( this.getPoint( i / divisions ) );
  23157. }
  23158. if ( this.autoClose ) {
  23159. points.push( points[ 0 ] );
  23160. }
  23161. return points;
  23162. },
  23163. getPoints: function ( divisions = 12 ) {
  23164. const points = [];
  23165. let last;
  23166. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  23167. const curve = curves[ i ];
  23168. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  23169. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  23170. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  23171. : divisions;
  23172. const pts = curve.getPoints( resolution );
  23173. for ( let j = 0; j < pts.length; j ++ ) {
  23174. const point = pts[ j ];
  23175. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  23176. points.push( point );
  23177. last = point;
  23178. }
  23179. }
  23180. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  23181. points.push( points[ 0 ] );
  23182. }
  23183. return points;
  23184. },
  23185. copy: function ( source ) {
  23186. Curve.prototype.copy.call( this, source );
  23187. this.curves = [];
  23188. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  23189. const curve = source.curves[ i ];
  23190. this.curves.push( curve.clone() );
  23191. }
  23192. this.autoClose = source.autoClose;
  23193. return this;
  23194. },
  23195. toJSON: function () {
  23196. const data = Curve.prototype.toJSON.call( this );
  23197. data.autoClose = this.autoClose;
  23198. data.curves = [];
  23199. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23200. const curve = this.curves[ i ];
  23201. data.curves.push( curve.toJSON() );
  23202. }
  23203. return data;
  23204. },
  23205. fromJSON: function ( json ) {
  23206. Curve.prototype.fromJSON.call( this, json );
  23207. this.autoClose = json.autoClose;
  23208. this.curves = [];
  23209. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  23210. const curve = json.curves[ i ];
  23211. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  23212. }
  23213. return this;
  23214. }
  23215. } );
  23216. function Path( points ) {
  23217. CurvePath.call( this );
  23218. this.type = 'Path';
  23219. this.currentPoint = new Vector2();
  23220. if ( points ) {
  23221. this.setFromPoints( points );
  23222. }
  23223. }
  23224. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  23225. constructor: Path,
  23226. setFromPoints: function ( points ) {
  23227. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  23228. for ( let i = 1, l = points.length; i < l; i ++ ) {
  23229. this.lineTo( points[ i ].x, points[ i ].y );
  23230. }
  23231. return this;
  23232. },
  23233. moveTo: function ( x, y ) {
  23234. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  23235. return this;
  23236. },
  23237. lineTo: function ( x, y ) {
  23238. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  23239. this.curves.push( curve );
  23240. this.currentPoint.set( x, y );
  23241. return this;
  23242. },
  23243. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  23244. const curve = new QuadraticBezierCurve(
  23245. this.currentPoint.clone(),
  23246. new Vector2( aCPx, aCPy ),
  23247. new Vector2( aX, aY )
  23248. );
  23249. this.curves.push( curve );
  23250. this.currentPoint.set( aX, aY );
  23251. return this;
  23252. },
  23253. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23254. const curve = new CubicBezierCurve(
  23255. this.currentPoint.clone(),
  23256. new Vector2( aCP1x, aCP1y ),
  23257. new Vector2( aCP2x, aCP2y ),
  23258. new Vector2( aX, aY )
  23259. );
  23260. this.curves.push( curve );
  23261. this.currentPoint.set( aX, aY );
  23262. return this;
  23263. },
  23264. splineThru: function ( pts /*Array of Vector*/ ) {
  23265. const npts = [ this.currentPoint.clone() ].concat( pts );
  23266. const curve = new SplineCurve( npts );
  23267. this.curves.push( curve );
  23268. this.currentPoint.copy( pts[ pts.length - 1 ] );
  23269. return this;
  23270. },
  23271. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23272. const x0 = this.currentPoint.x;
  23273. const y0 = this.currentPoint.y;
  23274. this.absarc( aX + x0, aY + y0, aRadius,
  23275. aStartAngle, aEndAngle, aClockwise );
  23276. return this;
  23277. },
  23278. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23279. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23280. return this;
  23281. },
  23282. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23283. const x0 = this.currentPoint.x;
  23284. const y0 = this.currentPoint.y;
  23285. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23286. return this;
  23287. },
  23288. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23289. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23290. if ( this.curves.length > 0 ) {
  23291. // if a previous curve is present, attempt to join
  23292. const firstPoint = curve.getPoint( 0 );
  23293. if ( ! firstPoint.equals( this.currentPoint ) ) {
  23294. this.lineTo( firstPoint.x, firstPoint.y );
  23295. }
  23296. }
  23297. this.curves.push( curve );
  23298. const lastPoint = curve.getPoint( 1 );
  23299. this.currentPoint.copy( lastPoint );
  23300. return this;
  23301. },
  23302. copy: function ( source ) {
  23303. CurvePath.prototype.copy.call( this, source );
  23304. this.currentPoint.copy( source.currentPoint );
  23305. return this;
  23306. },
  23307. toJSON: function () {
  23308. const data = CurvePath.prototype.toJSON.call( this );
  23309. data.currentPoint = this.currentPoint.toArray();
  23310. return data;
  23311. },
  23312. fromJSON: function ( json ) {
  23313. CurvePath.prototype.fromJSON.call( this, json );
  23314. this.currentPoint.fromArray( json.currentPoint );
  23315. return this;
  23316. }
  23317. } );
  23318. function Shape( points ) {
  23319. Path.call( this, points );
  23320. this.uuid = MathUtils.generateUUID();
  23321. this.type = 'Shape';
  23322. this.holes = [];
  23323. }
  23324. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  23325. constructor: Shape,
  23326. getPointsHoles: function ( divisions ) {
  23327. const holesPts = [];
  23328. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  23329. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  23330. }
  23331. return holesPts;
  23332. },
  23333. // get points of shape and holes (keypoints based on segments parameter)
  23334. extractPoints: function ( divisions ) {
  23335. return {
  23336. shape: this.getPoints( divisions ),
  23337. holes: this.getPointsHoles( divisions )
  23338. };
  23339. },
  23340. copy: function ( source ) {
  23341. Path.prototype.copy.call( this, source );
  23342. this.holes = [];
  23343. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  23344. const hole = source.holes[ i ];
  23345. this.holes.push( hole.clone() );
  23346. }
  23347. return this;
  23348. },
  23349. toJSON: function () {
  23350. const data = Path.prototype.toJSON.call( this );
  23351. data.uuid = this.uuid;
  23352. data.holes = [];
  23353. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  23354. const hole = this.holes[ i ];
  23355. data.holes.push( hole.toJSON() );
  23356. }
  23357. return data;
  23358. },
  23359. fromJSON: function ( json ) {
  23360. Path.prototype.fromJSON.call( this, json );
  23361. this.uuid = json.uuid;
  23362. this.holes = [];
  23363. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  23364. const hole = json.holes[ i ];
  23365. this.holes.push( new Path().fromJSON( hole ) );
  23366. }
  23367. return this;
  23368. }
  23369. } );
  23370. function Light( color, intensity = 1 ) {
  23371. Object3D.call( this );
  23372. this.type = 'Light';
  23373. this.color = new Color( color );
  23374. this.intensity = intensity;
  23375. }
  23376. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  23377. constructor: Light,
  23378. isLight: true,
  23379. copy: function ( source ) {
  23380. Object3D.prototype.copy.call( this, source );
  23381. this.color.copy( source.color );
  23382. this.intensity = source.intensity;
  23383. return this;
  23384. },
  23385. toJSON: function ( meta ) {
  23386. const data = Object3D.prototype.toJSON.call( this, meta );
  23387. data.object.color = this.color.getHex();
  23388. data.object.intensity = this.intensity;
  23389. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23390. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23391. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23392. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23393. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23394. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23395. return data;
  23396. }
  23397. } );
  23398. function HemisphereLight( skyColor, groundColor, intensity ) {
  23399. Light.call( this, skyColor, intensity );
  23400. this.type = 'HemisphereLight';
  23401. this.position.copy( Object3D.DefaultUp );
  23402. this.updateMatrix();
  23403. this.groundColor = new Color( groundColor );
  23404. }
  23405. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23406. constructor: HemisphereLight,
  23407. isHemisphereLight: true,
  23408. copy: function ( source ) {
  23409. Light.prototype.copy.call( this, source );
  23410. this.groundColor.copy( source.groundColor );
  23411. return this;
  23412. }
  23413. } );
  23414. function LightShadow( camera ) {
  23415. this.camera = camera;
  23416. this.bias = 0;
  23417. this.normalBias = 0;
  23418. this.radius = 1;
  23419. this.mapSize = new Vector2( 512, 512 );
  23420. this.map = null;
  23421. this.mapPass = null;
  23422. this.matrix = new Matrix4();
  23423. this.autoUpdate = true;
  23424. this.needsUpdate = false;
  23425. this._frustum = new Frustum();
  23426. this._frameExtents = new Vector2( 1, 1 );
  23427. this._viewportCount = 1;
  23428. this._viewports = [
  23429. new Vector4( 0, 0, 1, 1 )
  23430. ];
  23431. }
  23432. Object.assign( LightShadow.prototype, {
  23433. _projScreenMatrix: new Matrix4(),
  23434. _lightPositionWorld: new Vector3(),
  23435. _lookTarget: new Vector3(),
  23436. getViewportCount: function () {
  23437. return this._viewportCount;
  23438. },
  23439. getFrustum: function () {
  23440. return this._frustum;
  23441. },
  23442. updateMatrices: function ( light ) {
  23443. const shadowCamera = this.camera,
  23444. shadowMatrix = this.matrix,
  23445. projScreenMatrix = this._projScreenMatrix,
  23446. lookTarget = this._lookTarget,
  23447. lightPositionWorld = this._lightPositionWorld;
  23448. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23449. shadowCamera.position.copy( lightPositionWorld );
  23450. lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  23451. shadowCamera.lookAt( lookTarget );
  23452. shadowCamera.updateMatrixWorld();
  23453. projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  23454. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  23455. shadowMatrix.set(
  23456. 0.5, 0.0, 0.0, 0.5,
  23457. 0.0, 0.5, 0.0, 0.5,
  23458. 0.0, 0.0, 0.5, 0.5,
  23459. 0.0, 0.0, 0.0, 1.0
  23460. );
  23461. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  23462. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  23463. },
  23464. getViewport: function ( viewportIndex ) {
  23465. return this._viewports[ viewportIndex ];
  23466. },
  23467. getFrameExtents: function () {
  23468. return this._frameExtents;
  23469. },
  23470. copy: function ( source ) {
  23471. this.camera = source.camera.clone();
  23472. this.bias = source.bias;
  23473. this.radius = source.radius;
  23474. this.mapSize.copy( source.mapSize );
  23475. return this;
  23476. },
  23477. clone: function () {
  23478. return new this.constructor().copy( this );
  23479. },
  23480. toJSON: function () {
  23481. const object = {};
  23482. if ( this.bias !== 0 ) object.bias = this.bias;
  23483. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  23484. if ( this.radius !== 1 ) object.radius = this.radius;
  23485. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  23486. object.camera = this.camera.toJSON( false ).object;
  23487. delete object.camera.matrix;
  23488. return object;
  23489. }
  23490. } );
  23491. function SpotLightShadow() {
  23492. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  23493. this.focus = 1;
  23494. }
  23495. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  23496. constructor: SpotLightShadow,
  23497. isSpotLightShadow: true,
  23498. updateMatrices: function ( light ) {
  23499. const camera = this.camera;
  23500. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  23501. const aspect = this.mapSize.width / this.mapSize.height;
  23502. const far = light.distance || camera.far;
  23503. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  23504. camera.fov = fov;
  23505. camera.aspect = aspect;
  23506. camera.far = far;
  23507. camera.updateProjectionMatrix();
  23508. }
  23509. LightShadow.prototype.updateMatrices.call( this, light );
  23510. }
  23511. } );
  23512. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  23513. Light.call( this, color, intensity );
  23514. this.type = 'SpotLight';
  23515. this.position.copy( Object3D.DefaultUp );
  23516. this.updateMatrix();
  23517. this.target = new Object3D();
  23518. Object.defineProperty( this, 'power', {
  23519. get: function () {
  23520. // intensity = power per solid angle.
  23521. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23522. return this.intensity * Math.PI;
  23523. },
  23524. set: function ( power ) {
  23525. // intensity = power per solid angle.
  23526. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23527. this.intensity = power / Math.PI;
  23528. }
  23529. } );
  23530. this.distance = ( distance !== undefined ) ? distance : 0;
  23531. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  23532. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  23533. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  23534. this.shadow = new SpotLightShadow();
  23535. }
  23536. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23537. constructor: SpotLight,
  23538. isSpotLight: true,
  23539. copy: function ( source ) {
  23540. Light.prototype.copy.call( this, source );
  23541. this.distance = source.distance;
  23542. this.angle = source.angle;
  23543. this.penumbra = source.penumbra;
  23544. this.decay = source.decay;
  23545. this.target = source.target.clone();
  23546. this.shadow = source.shadow.clone();
  23547. return this;
  23548. }
  23549. } );
  23550. function PointLightShadow() {
  23551. LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  23552. this._frameExtents = new Vector2( 4, 2 );
  23553. this._viewportCount = 6;
  23554. this._viewports = [
  23555. // These viewports map a cube-map onto a 2D texture with the
  23556. // following orientation:
  23557. //
  23558. // xzXZ
  23559. // y Y
  23560. //
  23561. // X - Positive x direction
  23562. // x - Negative x direction
  23563. // Y - Positive y direction
  23564. // y - Negative y direction
  23565. // Z - Positive z direction
  23566. // z - Negative z direction
  23567. // positive X
  23568. new Vector4( 2, 1, 1, 1 ),
  23569. // negative X
  23570. new Vector4( 0, 1, 1, 1 ),
  23571. // positive Z
  23572. new Vector4( 3, 1, 1, 1 ),
  23573. // negative Z
  23574. new Vector4( 1, 1, 1, 1 ),
  23575. // positive Y
  23576. new Vector4( 3, 0, 1, 1 ),
  23577. // negative Y
  23578. new Vector4( 1, 0, 1, 1 )
  23579. ];
  23580. this._cubeDirections = [
  23581. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  23582. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  23583. ];
  23584. this._cubeUps = [
  23585. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  23586. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  23587. ];
  23588. }
  23589. PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  23590. constructor: PointLightShadow,
  23591. isPointLightShadow: true,
  23592. updateMatrices: function ( light, viewportIndex = 0 ) {
  23593. const camera = this.camera,
  23594. shadowMatrix = this.matrix,
  23595. lightPositionWorld = this._lightPositionWorld,
  23596. lookTarget = this._lookTarget,
  23597. projScreenMatrix = this._projScreenMatrix;
  23598. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  23599. camera.position.copy( lightPositionWorld );
  23600. lookTarget.copy( camera.position );
  23601. lookTarget.add( this._cubeDirections[ viewportIndex ] );
  23602. camera.up.copy( this._cubeUps[ viewportIndex ] );
  23603. camera.lookAt( lookTarget );
  23604. camera.updateMatrixWorld();
  23605. shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
  23606. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  23607. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  23608. }
  23609. } );
  23610. function PointLight( color, intensity, distance, decay ) {
  23611. Light.call( this, color, intensity );
  23612. this.type = 'PointLight';
  23613. Object.defineProperty( this, 'power', {
  23614. get: function () {
  23615. // intensity = power per solid angle.
  23616. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23617. return this.intensity * 4 * Math.PI;
  23618. },
  23619. set: function ( power ) {
  23620. // intensity = power per solid angle.
  23621. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23622. this.intensity = power / ( 4 * Math.PI );
  23623. }
  23624. } );
  23625. this.distance = ( distance !== undefined ) ? distance : 0;
  23626. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  23627. this.shadow = new PointLightShadow();
  23628. }
  23629. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23630. constructor: PointLight,
  23631. isPointLight: true,
  23632. copy: function ( source ) {
  23633. Light.prototype.copy.call( this, source );
  23634. this.distance = source.distance;
  23635. this.decay = source.decay;
  23636. this.shadow = source.shadow.clone();
  23637. return this;
  23638. }
  23639. } );
  23640. function OrthographicCamera( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  23641. Camera.call( this );
  23642. this.type = 'OrthographicCamera';
  23643. this.zoom = 1;
  23644. this.view = null;
  23645. this.left = left;
  23646. this.right = right;
  23647. this.top = top;
  23648. this.bottom = bottom;
  23649. this.near = near;
  23650. this.far = far;
  23651. this.updateProjectionMatrix();
  23652. }
  23653. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  23654. constructor: OrthographicCamera,
  23655. isOrthographicCamera: true,
  23656. copy: function ( source, recursive ) {
  23657. Camera.prototype.copy.call( this, source, recursive );
  23658. this.left = source.left;
  23659. this.right = source.right;
  23660. this.top = source.top;
  23661. this.bottom = source.bottom;
  23662. this.near = source.near;
  23663. this.far = source.far;
  23664. this.zoom = source.zoom;
  23665. this.view = source.view === null ? null : Object.assign( {}, source.view );
  23666. return this;
  23667. },
  23668. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  23669. if ( this.view === null ) {
  23670. this.view = {
  23671. enabled: true,
  23672. fullWidth: 1,
  23673. fullHeight: 1,
  23674. offsetX: 0,
  23675. offsetY: 0,
  23676. width: 1,
  23677. height: 1
  23678. };
  23679. }
  23680. this.view.enabled = true;
  23681. this.view.fullWidth = fullWidth;
  23682. this.view.fullHeight = fullHeight;
  23683. this.view.offsetX = x;
  23684. this.view.offsetY = y;
  23685. this.view.width = width;
  23686. this.view.height = height;
  23687. this.updateProjectionMatrix();
  23688. },
  23689. clearViewOffset: function () {
  23690. if ( this.view !== null ) {
  23691. this.view.enabled = false;
  23692. }
  23693. this.updateProjectionMatrix();
  23694. },
  23695. updateProjectionMatrix: function () {
  23696. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  23697. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  23698. const cx = ( this.right + this.left ) / 2;
  23699. const cy = ( this.top + this.bottom ) / 2;
  23700. let left = cx - dx;
  23701. let right = cx + dx;
  23702. let top = cy + dy;
  23703. let bottom = cy - dy;
  23704. if ( this.view !== null && this.view.enabled ) {
  23705. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  23706. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  23707. left += scaleW * this.view.offsetX;
  23708. right = left + scaleW * this.view.width;
  23709. top -= scaleH * this.view.offsetY;
  23710. bottom = top - scaleH * this.view.height;
  23711. }
  23712. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  23713. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  23714. },
  23715. toJSON: function ( meta ) {
  23716. const data = Object3D.prototype.toJSON.call( this, meta );
  23717. data.object.zoom = this.zoom;
  23718. data.object.left = this.left;
  23719. data.object.right = this.right;
  23720. data.object.top = this.top;
  23721. data.object.bottom = this.bottom;
  23722. data.object.near = this.near;
  23723. data.object.far = this.far;
  23724. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  23725. return data;
  23726. }
  23727. } );
  23728. function DirectionalLightShadow() {
  23729. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  23730. }
  23731. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  23732. constructor: DirectionalLightShadow,
  23733. isDirectionalLightShadow: true,
  23734. updateMatrices: function ( light ) {
  23735. LightShadow.prototype.updateMatrices.call( this, light );
  23736. }
  23737. } );
  23738. function DirectionalLight( color, intensity ) {
  23739. Light.call( this, color, intensity );
  23740. this.type = 'DirectionalLight';
  23741. this.position.copy( Object3D.DefaultUp );
  23742. this.updateMatrix();
  23743. this.target = new Object3D();
  23744. this.shadow = new DirectionalLightShadow();
  23745. }
  23746. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23747. constructor: DirectionalLight,
  23748. isDirectionalLight: true,
  23749. copy: function ( source ) {
  23750. Light.prototype.copy.call( this, source );
  23751. this.target = source.target.clone();
  23752. this.shadow = source.shadow.clone();
  23753. return this;
  23754. }
  23755. } );
  23756. function AmbientLight( color, intensity ) {
  23757. Light.call( this, color, intensity );
  23758. this.type = 'AmbientLight';
  23759. }
  23760. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23761. constructor: AmbientLight,
  23762. isAmbientLight: true
  23763. } );
  23764. function RectAreaLight( color, intensity, width, height ) {
  23765. Light.call( this, color, intensity );
  23766. this.type = 'RectAreaLight';
  23767. this.width = ( width !== undefined ) ? width : 10;
  23768. this.height = ( height !== undefined ) ? height : 10;
  23769. }
  23770. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23771. constructor: RectAreaLight,
  23772. isRectAreaLight: true,
  23773. copy: function ( source ) {
  23774. Light.prototype.copy.call( this, source );
  23775. this.width = source.width;
  23776. this.height = source.height;
  23777. return this;
  23778. },
  23779. toJSON: function ( meta ) {
  23780. const data = Light.prototype.toJSON.call( this, meta );
  23781. data.object.width = this.width;
  23782. data.object.height = this.height;
  23783. return data;
  23784. }
  23785. } );
  23786. /**
  23787. * Primary reference:
  23788. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23789. *
  23790. * Secondary reference:
  23791. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23792. */
  23793. // 3-band SH defined by 9 coefficients
  23794. class SphericalHarmonics3 {
  23795. constructor() {
  23796. Object.defineProperty( this, 'isSphericalHarmonics3', { value: true } );
  23797. this.coefficients = [];
  23798. for ( let i = 0; i < 9; i ++ ) {
  23799. this.coefficients.push( new Vector3() );
  23800. }
  23801. }
  23802. set( coefficients ) {
  23803. for ( let i = 0; i < 9; i ++ ) {
  23804. this.coefficients[ i ].copy( coefficients[ i ] );
  23805. }
  23806. return this;
  23807. }
  23808. zero() {
  23809. for ( let i = 0; i < 9; i ++ ) {
  23810. this.coefficients[ i ].set( 0, 0, 0 );
  23811. }
  23812. return this;
  23813. }
  23814. // get the radiance in the direction of the normal
  23815. // target is a Vector3
  23816. getAt( normal, target ) {
  23817. // normal is assumed to be unit length
  23818. const x = normal.x, y = normal.y, z = normal.z;
  23819. const coeff = this.coefficients;
  23820. // band 0
  23821. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  23822. // band 1
  23823. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  23824. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  23825. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  23826. // band 2
  23827. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  23828. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  23829. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  23830. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  23831. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  23832. return target;
  23833. }
  23834. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23835. // target is a Vector3
  23836. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23837. getIrradianceAt( normal, target ) {
  23838. // normal is assumed to be unit length
  23839. const x = normal.x, y = normal.y, z = normal.z;
  23840. const coeff = this.coefficients;
  23841. // band 0
  23842. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  23843. // band 1
  23844. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  23845. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  23846. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  23847. // band 2
  23848. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  23849. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  23850. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  23851. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  23852. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  23853. return target;
  23854. }
  23855. add( sh ) {
  23856. for ( let i = 0; i < 9; i ++ ) {
  23857. this.coefficients[ i ].add( sh.coefficients[ i ] );
  23858. }
  23859. return this;
  23860. }
  23861. addScaledSH( sh, s ) {
  23862. for ( let i = 0; i < 9; i ++ ) {
  23863. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  23864. }
  23865. return this;
  23866. }
  23867. scale( s ) {
  23868. for ( let i = 0; i < 9; i ++ ) {
  23869. this.coefficients[ i ].multiplyScalar( s );
  23870. }
  23871. return this;
  23872. }
  23873. lerp( sh, alpha ) {
  23874. for ( let i = 0; i < 9; i ++ ) {
  23875. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  23876. }
  23877. return this;
  23878. }
  23879. equals( sh ) {
  23880. for ( let i = 0; i < 9; i ++ ) {
  23881. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  23882. return false;
  23883. }
  23884. }
  23885. return true;
  23886. }
  23887. copy( sh ) {
  23888. return this.set( sh.coefficients );
  23889. }
  23890. clone() {
  23891. return new this.constructor().copy( this );
  23892. }
  23893. fromArray( array, offset = 0 ) {
  23894. const coefficients = this.coefficients;
  23895. for ( let i = 0; i < 9; i ++ ) {
  23896. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  23897. }
  23898. return this;
  23899. }
  23900. toArray( array = [], offset = 0 ) {
  23901. const coefficients = this.coefficients;
  23902. for ( let i = 0; i < 9; i ++ ) {
  23903. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  23904. }
  23905. return array;
  23906. }
  23907. // evaluate the basis functions
  23908. // shBasis is an Array[ 9 ]
  23909. static getBasisAt( normal, shBasis ) {
  23910. // normal is assumed to be unit length
  23911. const x = normal.x, y = normal.y, z = normal.z;
  23912. // band 0
  23913. shBasis[ 0 ] = 0.282095;
  23914. // band 1
  23915. shBasis[ 1 ] = 0.488603 * y;
  23916. shBasis[ 2 ] = 0.488603 * z;
  23917. shBasis[ 3 ] = 0.488603 * x;
  23918. // band 2
  23919. shBasis[ 4 ] = 1.092548 * x * y;
  23920. shBasis[ 5 ] = 1.092548 * y * z;
  23921. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  23922. shBasis[ 7 ] = 1.092548 * x * z;
  23923. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  23924. }
  23925. }
  23926. function LightProbe( sh, intensity ) {
  23927. Light.call( this, undefined, intensity );
  23928. this.type = 'LightProbe';
  23929. this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
  23930. }
  23931. LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
  23932. constructor: LightProbe,
  23933. isLightProbe: true,
  23934. copy: function ( source ) {
  23935. Light.prototype.copy.call( this, source );
  23936. this.sh.copy( source.sh );
  23937. return this;
  23938. },
  23939. fromJSON: function ( json ) {
  23940. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23941. this.sh.fromArray( json.sh );
  23942. return this;
  23943. },
  23944. toJSON: function ( meta ) {
  23945. const data = Light.prototype.toJSON.call( this, meta );
  23946. data.object.sh = this.sh.toArray();
  23947. return data;
  23948. }
  23949. } );
  23950. function MaterialLoader( manager ) {
  23951. Loader.call( this, manager );
  23952. this.textures = {};
  23953. }
  23954. MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  23955. constructor: MaterialLoader,
  23956. load: function ( url, onLoad, onProgress, onError ) {
  23957. const scope = this;
  23958. const loader = new FileLoader( scope.manager );
  23959. loader.setPath( scope.path );
  23960. loader.setRequestHeader( scope.requestHeader );
  23961. loader.setWithCredentials( scope.withCredentials );
  23962. loader.load( url, function ( text ) {
  23963. try {
  23964. onLoad( scope.parse( JSON.parse( text ) ) );
  23965. } catch ( e ) {
  23966. if ( onError ) {
  23967. onError( e );
  23968. } else {
  23969. console.error( e );
  23970. }
  23971. scope.manager.itemError( url );
  23972. }
  23973. }, onProgress, onError );
  23974. },
  23975. parse: function ( json ) {
  23976. const textures = this.textures;
  23977. function getTexture( name ) {
  23978. if ( textures[ name ] === undefined ) {
  23979. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  23980. }
  23981. return textures[ name ];
  23982. }
  23983. const material = new Materials[ json.type ]();
  23984. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  23985. if ( json.name !== undefined ) material.name = json.name;
  23986. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  23987. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  23988. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  23989. if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
  23990. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  23991. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  23992. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  23993. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  23994. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  23995. if ( json.fog !== undefined ) material.fog = json.fog;
  23996. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  23997. if ( json.blending !== undefined ) material.blending = json.blending;
  23998. if ( json.combine !== undefined ) material.combine = json.combine;
  23999. if ( json.side !== undefined ) material.side = json.side;
  24000. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24001. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24002. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24003. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24004. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24005. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24006. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24007. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24008. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24009. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24010. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24011. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24012. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24013. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24014. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24015. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24016. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24017. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24018. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24019. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24020. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24021. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24022. if ( json.scale !== undefined ) material.scale = json.scale;
  24023. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24024. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24025. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24026. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  24027. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  24028. if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
  24029. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24030. if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
  24031. if ( json.visible !== undefined ) material.visible = json.visible;
  24032. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24033. if ( json.userData !== undefined ) material.userData = json.userData;
  24034. if ( json.vertexColors !== undefined ) {
  24035. if ( typeof json.vertexColors === 'number' ) {
  24036. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24037. } else {
  24038. material.vertexColors = json.vertexColors;
  24039. }
  24040. }
  24041. // Shader Material
  24042. if ( json.uniforms !== undefined ) {
  24043. for ( const name in json.uniforms ) {
  24044. const uniform = json.uniforms[ name ];
  24045. material.uniforms[ name ] = {};
  24046. switch ( uniform.type ) {
  24047. case 't':
  24048. material.uniforms[ name ].value = getTexture( uniform.value );
  24049. break;
  24050. case 'c':
  24051. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24052. break;
  24053. case 'v2':
  24054. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24055. break;
  24056. case 'v3':
  24057. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24058. break;
  24059. case 'v4':
  24060. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24061. break;
  24062. case 'm3':
  24063. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24064. break;
  24065. case 'm4':
  24066. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24067. break;
  24068. default:
  24069. material.uniforms[ name ].value = uniform.value;
  24070. }
  24071. }
  24072. }
  24073. if ( json.defines !== undefined ) material.defines = json.defines;
  24074. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24075. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24076. if ( json.extensions !== undefined ) {
  24077. for ( const key in json.extensions ) {
  24078. material.extensions[ key ] = json.extensions[ key ];
  24079. }
  24080. }
  24081. // Deprecated
  24082. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24083. // for PointsMaterial
  24084. if ( json.size !== undefined ) material.size = json.size;
  24085. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24086. // maps
  24087. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24088. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24089. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24090. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24091. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24092. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24093. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24094. if ( json.normalScale !== undefined ) {
  24095. let normalScale = json.normalScale;
  24096. if ( Array.isArray( normalScale ) === false ) {
  24097. // Blender exporter used to export a scalar. See #7459
  24098. normalScale = [ normalScale, normalScale ];
  24099. }
  24100. material.normalScale = new Vector2().fromArray( normalScale );
  24101. }
  24102. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24103. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24104. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24105. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24106. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24107. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24108. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24109. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24110. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24111. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24112. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24113. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24114. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24115. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24116. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24117. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24118. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24119. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24120. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24121. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24122. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24123. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24124. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24125. return material;
  24126. },
  24127. setTextures: function ( value ) {
  24128. this.textures = value;
  24129. return this;
  24130. }
  24131. } );
  24132. const LoaderUtils = {
  24133. decodeText: function ( array ) {
  24134. if ( typeof TextDecoder !== 'undefined' ) {
  24135. return new TextDecoder().decode( array );
  24136. }
  24137. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24138. // throws a "maximum call stack size exceeded" error for large arrays.
  24139. let s = '';
  24140. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24141. // Implicitly assumes little-endian.
  24142. s += String.fromCharCode( array[ i ] );
  24143. }
  24144. try {
  24145. // merges multi-byte utf-8 characters.
  24146. return decodeURIComponent( escape( s ) );
  24147. } catch ( e ) { // see #16358
  24148. return s;
  24149. }
  24150. },
  24151. extractUrlBase: function ( url ) {
  24152. const index = url.lastIndexOf( '/' );
  24153. if ( index === - 1 ) return './';
  24154. return url.substr( 0, index + 1 );
  24155. }
  24156. };
  24157. function InstancedBufferGeometry() {
  24158. BufferGeometry.call( this );
  24159. this.type = 'InstancedBufferGeometry';
  24160. this.instanceCount = Infinity;
  24161. }
  24162. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  24163. constructor: InstancedBufferGeometry,
  24164. isInstancedBufferGeometry: true,
  24165. copy: function ( source ) {
  24166. BufferGeometry.prototype.copy.call( this, source );
  24167. this.instanceCount = source.instanceCount;
  24168. return this;
  24169. },
  24170. clone: function () {
  24171. return new this.constructor().copy( this );
  24172. },
  24173. toJSON: function () {
  24174. const data = BufferGeometry.prototype.toJSON.call( this );
  24175. data.instanceCount = this.instanceCount;
  24176. data.isInstancedBufferGeometry = true;
  24177. return data;
  24178. }
  24179. } );
  24180. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  24181. if ( typeof ( normalized ) === 'number' ) {
  24182. meshPerAttribute = normalized;
  24183. normalized = false;
  24184. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  24185. }
  24186. BufferAttribute.call( this, array, itemSize, normalized );
  24187. this.meshPerAttribute = meshPerAttribute || 1;
  24188. }
  24189. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  24190. constructor: InstancedBufferAttribute,
  24191. isInstancedBufferAttribute: true,
  24192. copy: function ( source ) {
  24193. BufferAttribute.prototype.copy.call( this, source );
  24194. this.meshPerAttribute = source.meshPerAttribute;
  24195. return this;
  24196. },
  24197. toJSON: function () {
  24198. const data = BufferAttribute.prototype.toJSON.call( this );
  24199. data.meshPerAttribute = this.meshPerAttribute;
  24200. data.isInstancedBufferAttribute = true;
  24201. return data;
  24202. }
  24203. } );
  24204. function BufferGeometryLoader( manager ) {
  24205. Loader.call( this, manager );
  24206. }
  24207. BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24208. constructor: BufferGeometryLoader,
  24209. load: function ( url, onLoad, onProgress, onError ) {
  24210. const scope = this;
  24211. const loader = new FileLoader( scope.manager );
  24212. loader.setPath( scope.path );
  24213. loader.setRequestHeader( scope.requestHeader );
  24214. loader.setWithCredentials( scope.withCredentials );
  24215. loader.load( url, function ( text ) {
  24216. try {
  24217. onLoad( scope.parse( JSON.parse( text ) ) );
  24218. } catch ( e ) {
  24219. if ( onError ) {
  24220. onError( e );
  24221. } else {
  24222. console.error( e );
  24223. }
  24224. scope.manager.itemError( url );
  24225. }
  24226. }, onProgress, onError );
  24227. },
  24228. parse: function ( json ) {
  24229. const interleavedBufferMap = {};
  24230. const arrayBufferMap = {};
  24231. function getInterleavedBuffer( json, uuid ) {
  24232. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24233. const interleavedBuffers = json.interleavedBuffers;
  24234. const interleavedBuffer = interleavedBuffers[ uuid ];
  24235. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24236. const array = getTypedArray( interleavedBuffer.type, buffer );
  24237. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24238. ib.uuid = interleavedBuffer.uuid;
  24239. interleavedBufferMap[ uuid ] = ib;
  24240. return ib;
  24241. }
  24242. function getArrayBuffer( json, uuid ) {
  24243. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24244. const arrayBuffers = json.arrayBuffers;
  24245. const arrayBuffer = arrayBuffers[ uuid ];
  24246. const ab = new Uint32Array( arrayBuffer ).buffer;
  24247. arrayBufferMap[ uuid ] = ab;
  24248. return ab;
  24249. }
  24250. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24251. const index = json.data.index;
  24252. if ( index !== undefined ) {
  24253. const typedArray = getTypedArray( index.type, index.array );
  24254. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24255. }
  24256. const attributes = json.data.attributes;
  24257. for ( const key in attributes ) {
  24258. const attribute = attributes[ key ];
  24259. let bufferAttribute;
  24260. if ( attribute.isInterleavedBufferAttribute ) {
  24261. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24262. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24263. } else {
  24264. const typedArray = getTypedArray( attribute.type, attribute.array );
  24265. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24266. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24267. }
  24268. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24269. geometry.setAttribute( key, bufferAttribute );
  24270. }
  24271. const morphAttributes = json.data.morphAttributes;
  24272. if ( morphAttributes ) {
  24273. for ( const key in morphAttributes ) {
  24274. const attributeArray = morphAttributes[ key ];
  24275. const array = [];
  24276. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24277. const attribute = attributeArray[ i ];
  24278. let bufferAttribute;
  24279. if ( attribute.isInterleavedBufferAttribute ) {
  24280. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24281. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24282. } else {
  24283. const typedArray = getTypedArray( attribute.type, attribute.array );
  24284. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24285. }
  24286. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24287. array.push( bufferAttribute );
  24288. }
  24289. geometry.morphAttributes[ key ] = array;
  24290. }
  24291. }
  24292. const morphTargetsRelative = json.data.morphTargetsRelative;
  24293. if ( morphTargetsRelative ) {
  24294. geometry.morphTargetsRelative = true;
  24295. }
  24296. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24297. if ( groups !== undefined ) {
  24298. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24299. const group = groups[ i ];
  24300. geometry.addGroup( group.start, group.count, group.materialIndex );
  24301. }
  24302. }
  24303. const boundingSphere = json.data.boundingSphere;
  24304. if ( boundingSphere !== undefined ) {
  24305. const center = new Vector3();
  24306. if ( boundingSphere.center !== undefined ) {
  24307. center.fromArray( boundingSphere.center );
  24308. }
  24309. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24310. }
  24311. if ( json.name ) geometry.name = json.name;
  24312. if ( json.userData ) geometry.userData = json.userData;
  24313. return geometry;
  24314. }
  24315. } );
  24316. class ObjectLoader extends Loader {
  24317. constructor( manager ) {
  24318. super( manager );
  24319. }
  24320. load( url, onLoad, onProgress, onError ) {
  24321. const scope = this;
  24322. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24323. this.resourcePath = this.resourcePath || path;
  24324. const loader = new FileLoader( this.manager );
  24325. loader.setPath( this.path );
  24326. loader.setRequestHeader( this.requestHeader );
  24327. loader.setWithCredentials( this.withCredentials );
  24328. loader.load( url, function ( text ) {
  24329. let json = null;
  24330. try {
  24331. json = JSON.parse( text );
  24332. } catch ( error ) {
  24333. if ( onError !== undefined ) onError( error );
  24334. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24335. return;
  24336. }
  24337. const metadata = json.metadata;
  24338. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24339. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24340. return;
  24341. }
  24342. scope.parse( json, onLoad );
  24343. }, onProgress, onError );
  24344. }
  24345. parse( json, onLoad ) {
  24346. const animations = this.parseAnimations( json.animations );
  24347. const shapes = this.parseShapes( json.shapes );
  24348. const geometries = this.parseGeometries( json.geometries, shapes );
  24349. const images = this.parseImages( json.images, function () {
  24350. if ( onLoad !== undefined ) onLoad( object );
  24351. } );
  24352. const textures = this.parseTextures( json.textures, images );
  24353. const materials = this.parseMaterials( json.materials, textures );
  24354. const object = this.parseObject( json.object, geometries, materials, animations );
  24355. const skeletons = this.parseSkeletons( json.skeletons, object );
  24356. this.bindSkeletons( object, skeletons );
  24357. //
  24358. if ( onLoad !== undefined ) {
  24359. let hasImages = false;
  24360. for ( const uuid in images ) {
  24361. if ( images[ uuid ] instanceof HTMLImageElement ) {
  24362. hasImages = true;
  24363. break;
  24364. }
  24365. }
  24366. if ( hasImages === false ) onLoad( object );
  24367. }
  24368. return object;
  24369. }
  24370. parseShapes( json ) {
  24371. const shapes = {};
  24372. if ( json !== undefined ) {
  24373. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24374. const shape = new Shape().fromJSON( json[ i ] );
  24375. shapes[ shape.uuid ] = shape;
  24376. }
  24377. }
  24378. return shapes;
  24379. }
  24380. parseSkeletons( json, object ) {
  24381. const skeletons = {};
  24382. const bones = {};
  24383. // generate bone lookup table
  24384. object.traverse( function ( child ) {
  24385. if ( child.isBone ) bones[ child.uuid ] = child;
  24386. } );
  24387. // create skeletons
  24388. if ( json !== undefined ) {
  24389. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24390. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24391. skeletons[ skeleton.uuid ] = skeleton;
  24392. }
  24393. }
  24394. return skeletons;
  24395. }
  24396. parseGeometries( json, shapes ) {
  24397. const geometries = {};
  24398. let geometryShapes;
  24399. if ( json !== undefined ) {
  24400. const bufferGeometryLoader = new BufferGeometryLoader();
  24401. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24402. let geometry;
  24403. const data = json[ i ];
  24404. switch ( data.type ) {
  24405. case 'PlaneGeometry':
  24406. case 'PlaneBufferGeometry':
  24407. geometry = new Geometries[ data.type ](
  24408. data.width,
  24409. data.height,
  24410. data.widthSegments,
  24411. data.heightSegments
  24412. );
  24413. break;
  24414. case 'BoxGeometry':
  24415. case 'BoxBufferGeometry':
  24416. case 'CubeGeometry': // backwards compatible
  24417. geometry = new Geometries[ data.type ](
  24418. data.width,
  24419. data.height,
  24420. data.depth,
  24421. data.widthSegments,
  24422. data.heightSegments,
  24423. data.depthSegments
  24424. );
  24425. break;
  24426. case 'CircleGeometry':
  24427. case 'CircleBufferGeometry':
  24428. geometry = new Geometries[ data.type ](
  24429. data.radius,
  24430. data.segments,
  24431. data.thetaStart,
  24432. data.thetaLength
  24433. );
  24434. break;
  24435. case 'CylinderGeometry':
  24436. case 'CylinderBufferGeometry':
  24437. geometry = new Geometries[ data.type ](
  24438. data.radiusTop,
  24439. data.radiusBottom,
  24440. data.height,
  24441. data.radialSegments,
  24442. data.heightSegments,
  24443. data.openEnded,
  24444. data.thetaStart,
  24445. data.thetaLength
  24446. );
  24447. break;
  24448. case 'ConeGeometry':
  24449. case 'ConeBufferGeometry':
  24450. geometry = new Geometries[ data.type ](
  24451. data.radius,
  24452. data.height,
  24453. data.radialSegments,
  24454. data.heightSegments,
  24455. data.openEnded,
  24456. data.thetaStart,
  24457. data.thetaLength
  24458. );
  24459. break;
  24460. case 'SphereGeometry':
  24461. case 'SphereBufferGeometry':
  24462. geometry = new Geometries[ data.type ](
  24463. data.radius,
  24464. data.widthSegments,
  24465. data.heightSegments,
  24466. data.phiStart,
  24467. data.phiLength,
  24468. data.thetaStart,
  24469. data.thetaLength
  24470. );
  24471. break;
  24472. case 'DodecahedronGeometry':
  24473. case 'DodecahedronBufferGeometry':
  24474. case 'IcosahedronGeometry':
  24475. case 'IcosahedronBufferGeometry':
  24476. case 'OctahedronGeometry':
  24477. case 'OctahedronBufferGeometry':
  24478. case 'TetrahedronGeometry':
  24479. case 'TetrahedronBufferGeometry':
  24480. geometry = new Geometries[ data.type ](
  24481. data.radius,
  24482. data.detail
  24483. );
  24484. break;
  24485. case 'RingGeometry':
  24486. case 'RingBufferGeometry':
  24487. geometry = new Geometries[ data.type ](
  24488. data.innerRadius,
  24489. data.outerRadius,
  24490. data.thetaSegments,
  24491. data.phiSegments,
  24492. data.thetaStart,
  24493. data.thetaLength
  24494. );
  24495. break;
  24496. case 'TorusGeometry':
  24497. case 'TorusBufferGeometry':
  24498. geometry = new Geometries[ data.type ](
  24499. data.radius,
  24500. data.tube,
  24501. data.radialSegments,
  24502. data.tubularSegments,
  24503. data.arc
  24504. );
  24505. break;
  24506. case 'TorusKnotGeometry':
  24507. case 'TorusKnotBufferGeometry':
  24508. geometry = new Geometries[ data.type ](
  24509. data.radius,
  24510. data.tube,
  24511. data.tubularSegments,
  24512. data.radialSegments,
  24513. data.p,
  24514. data.q
  24515. );
  24516. break;
  24517. case 'TubeGeometry':
  24518. case 'TubeBufferGeometry':
  24519. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24520. // User defined curves or instances of CurvePath will not be deserialized.
  24521. geometry = new Geometries[ data.type ](
  24522. new Curves[ data.path.type ]().fromJSON( data.path ),
  24523. data.tubularSegments,
  24524. data.radius,
  24525. data.radialSegments,
  24526. data.closed
  24527. );
  24528. break;
  24529. case 'LatheGeometry':
  24530. case 'LatheBufferGeometry':
  24531. geometry = new Geometries[ data.type ](
  24532. data.points,
  24533. data.segments,
  24534. data.phiStart,
  24535. data.phiLength
  24536. );
  24537. break;
  24538. case 'PolyhedronGeometry':
  24539. case 'PolyhedronBufferGeometry':
  24540. geometry = new Geometries[ data.type ](
  24541. data.vertices,
  24542. data.indices,
  24543. data.radius,
  24544. data.details
  24545. );
  24546. break;
  24547. case 'ShapeGeometry':
  24548. case 'ShapeBufferGeometry':
  24549. geometryShapes = [];
  24550. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  24551. const shape = shapes[ data.shapes[ j ] ];
  24552. geometryShapes.push( shape );
  24553. }
  24554. geometry = new Geometries[ data.type ](
  24555. geometryShapes,
  24556. data.curveSegments
  24557. );
  24558. break;
  24559. case 'ExtrudeGeometry':
  24560. case 'ExtrudeBufferGeometry':
  24561. geometryShapes = [];
  24562. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  24563. const shape = shapes[ data.shapes[ j ] ];
  24564. geometryShapes.push( shape );
  24565. }
  24566. const extrudePath = data.options.extrudePath;
  24567. if ( extrudePath !== undefined ) {
  24568. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  24569. }
  24570. geometry = new Geometries[ data.type ](
  24571. geometryShapes,
  24572. data.options
  24573. );
  24574. break;
  24575. case 'BufferGeometry':
  24576. case 'InstancedBufferGeometry':
  24577. geometry = bufferGeometryLoader.parse( data );
  24578. break;
  24579. case 'Geometry':
  24580. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  24581. break;
  24582. default:
  24583. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  24584. continue;
  24585. }
  24586. geometry.uuid = data.uuid;
  24587. if ( data.name !== undefined ) geometry.name = data.name;
  24588. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  24589. geometries[ data.uuid ] = geometry;
  24590. }
  24591. }
  24592. return geometries;
  24593. }
  24594. parseMaterials( json, textures ) {
  24595. const cache = {}; // MultiMaterial
  24596. const materials = {};
  24597. if ( json !== undefined ) {
  24598. const loader = new MaterialLoader();
  24599. loader.setTextures( textures );
  24600. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24601. const data = json[ i ];
  24602. if ( data.type === 'MultiMaterial' ) {
  24603. // Deprecated
  24604. const array = [];
  24605. for ( let j = 0; j < data.materials.length; j ++ ) {
  24606. const material = data.materials[ j ];
  24607. if ( cache[ material.uuid ] === undefined ) {
  24608. cache[ material.uuid ] = loader.parse( material );
  24609. }
  24610. array.push( cache[ material.uuid ] );
  24611. }
  24612. materials[ data.uuid ] = array;
  24613. } else {
  24614. if ( cache[ data.uuid ] === undefined ) {
  24615. cache[ data.uuid ] = loader.parse( data );
  24616. }
  24617. materials[ data.uuid ] = cache[ data.uuid ];
  24618. }
  24619. }
  24620. }
  24621. return materials;
  24622. }
  24623. parseAnimations( json ) {
  24624. const animations = {};
  24625. if ( json !== undefined ) {
  24626. for ( let i = 0; i < json.length; i ++ ) {
  24627. const data = json[ i ];
  24628. const clip = AnimationClip.parse( data );
  24629. animations[ clip.uuid ] = clip;
  24630. }
  24631. }
  24632. return animations;
  24633. }
  24634. parseImages( json, onLoad ) {
  24635. const scope = this;
  24636. const images = {};
  24637. let loader;
  24638. function loadImage( url ) {
  24639. scope.manager.itemStart( url );
  24640. return loader.load( url, function () {
  24641. scope.manager.itemEnd( url );
  24642. }, undefined, function () {
  24643. scope.manager.itemError( url );
  24644. scope.manager.itemEnd( url );
  24645. } );
  24646. }
  24647. function deserializeImage( image ) {
  24648. if ( typeof image === 'string' ) {
  24649. const url = image;
  24650. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  24651. return loadImage( path );
  24652. } else {
  24653. if ( image.data ) {
  24654. return {
  24655. data: getTypedArray( image.type, image.data ),
  24656. width: image.width,
  24657. height: image.height
  24658. };
  24659. } else {
  24660. return null;
  24661. }
  24662. }
  24663. }
  24664. if ( json !== undefined && json.length > 0 ) {
  24665. const manager = new LoadingManager( onLoad );
  24666. loader = new ImageLoader( manager );
  24667. loader.setCrossOrigin( this.crossOrigin );
  24668. for ( let i = 0, il = json.length; i < il; i ++ ) {
  24669. const image = json[ i ];
  24670. const url = image.url;
  24671. if ( Array.isArray( url ) ) {
  24672. // load array of images e.g CubeTexture
  24673. images[ image.uuid ] = [];
  24674. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  24675. const currentUrl = url[ j ];
  24676. const deserializedImage = deserializeImage( currentUrl );
  24677. if ( deserializedImage !== null ) {
  24678. if ( deserializedImage instanceof HTMLImageElement ) {
  24679. images[ image.uuid ].push( deserializedImage );
  24680. } else {
  24681. // special case: handle array of data textures for cube textures
  24682. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  24683. }
  24684. }
  24685. }
  24686. } else {
  24687. // load single image
  24688. const deserializedImage = deserializeImage( image.url );
  24689. if ( deserializedImage !== null ) {
  24690. images[ image.uuid ] = deserializedImage;
  24691. }
  24692. }
  24693. }
  24694. }
  24695. return images;
  24696. }
  24697. parseTextures( json, images ) {
  24698. function parseConstant( value, type ) {
  24699. if ( typeof value === 'number' ) return value;
  24700. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24701. return type[ value ];
  24702. }
  24703. const textures = {};
  24704. if ( json !== undefined ) {
  24705. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24706. const data = json[ i ];
  24707. if ( data.image === undefined ) {
  24708. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24709. }
  24710. if ( images[ data.image ] === undefined ) {
  24711. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24712. }
  24713. let texture;
  24714. const image = images[ data.image ];
  24715. if ( Array.isArray( image ) ) {
  24716. texture = new CubeTexture( image );
  24717. if ( image.length === 6 ) texture.needsUpdate = true;
  24718. } else {
  24719. if ( image && image.data ) {
  24720. texture = new DataTexture( image.data, image.width, image.height );
  24721. } else {
  24722. texture = new Texture( image );
  24723. }
  24724. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  24725. }
  24726. texture.uuid = data.uuid;
  24727. if ( data.name !== undefined ) texture.name = data.name;
  24728. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  24729. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24730. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24731. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  24732. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  24733. if ( data.wrap !== undefined ) {
  24734. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  24735. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  24736. }
  24737. if ( data.format !== undefined ) texture.format = data.format;
  24738. if ( data.type !== undefined ) texture.type = data.type;
  24739. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  24740. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  24741. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  24742. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24743. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24744. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  24745. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  24746. textures[ data.uuid ] = texture;
  24747. }
  24748. }
  24749. return textures;
  24750. }
  24751. parseObject( data, geometries, materials, animations ) {
  24752. let object;
  24753. function getGeometry( name ) {
  24754. if ( geometries[ name ] === undefined ) {
  24755. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24756. }
  24757. return geometries[ name ];
  24758. }
  24759. function getMaterial( name ) {
  24760. if ( name === undefined ) return undefined;
  24761. if ( Array.isArray( name ) ) {
  24762. const array = [];
  24763. for ( let i = 0, l = name.length; i < l; i ++ ) {
  24764. const uuid = name[ i ];
  24765. if ( materials[ uuid ] === undefined ) {
  24766. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  24767. }
  24768. array.push( materials[ uuid ] );
  24769. }
  24770. return array;
  24771. }
  24772. if ( materials[ name ] === undefined ) {
  24773. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24774. }
  24775. return materials[ name ];
  24776. }
  24777. let geometry, material;
  24778. switch ( data.type ) {
  24779. case 'Scene':
  24780. object = new Scene();
  24781. if ( data.background !== undefined ) {
  24782. if ( Number.isInteger( data.background ) ) {
  24783. object.background = new Color( data.background );
  24784. }
  24785. }
  24786. if ( data.fog !== undefined ) {
  24787. if ( data.fog.type === 'Fog' ) {
  24788. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24789. } else if ( data.fog.type === 'FogExp2' ) {
  24790. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24791. }
  24792. }
  24793. break;
  24794. case 'PerspectiveCamera':
  24795. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24796. if ( data.focus !== undefined ) object.focus = data.focus;
  24797. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24798. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24799. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24800. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24801. break;
  24802. case 'OrthographicCamera':
  24803. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24804. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24805. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24806. break;
  24807. case 'AmbientLight':
  24808. object = new AmbientLight( data.color, data.intensity );
  24809. break;
  24810. case 'DirectionalLight':
  24811. object = new DirectionalLight( data.color, data.intensity );
  24812. break;
  24813. case 'PointLight':
  24814. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24815. break;
  24816. case 'RectAreaLight':
  24817. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  24818. break;
  24819. case 'SpotLight':
  24820. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24821. break;
  24822. case 'HemisphereLight':
  24823. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24824. break;
  24825. case 'LightProbe':
  24826. object = new LightProbe().fromJSON( data );
  24827. break;
  24828. case 'SkinnedMesh':
  24829. geometry = getGeometry( data.geometry );
  24830. material = getMaterial( data.material );
  24831. object = new SkinnedMesh( geometry, material );
  24832. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  24833. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  24834. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  24835. break;
  24836. case 'Mesh':
  24837. geometry = getGeometry( data.geometry );
  24838. material = getMaterial( data.material );
  24839. object = new Mesh( geometry, material );
  24840. break;
  24841. case 'InstancedMesh':
  24842. geometry = getGeometry( data.geometry );
  24843. material = getMaterial( data.material );
  24844. const count = data.count;
  24845. const instanceMatrix = data.instanceMatrix;
  24846. object = new InstancedMesh( geometry, material, count );
  24847. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  24848. break;
  24849. case 'LOD':
  24850. object = new LOD();
  24851. break;
  24852. case 'Line':
  24853. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  24854. break;
  24855. case 'LineLoop':
  24856. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  24857. break;
  24858. case 'LineSegments':
  24859. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  24860. break;
  24861. case 'PointCloud':
  24862. case 'Points':
  24863. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  24864. break;
  24865. case 'Sprite':
  24866. object = new Sprite$1( getMaterial( data.material ) );
  24867. break;
  24868. case 'Group':
  24869. object = new Group();
  24870. break;
  24871. case 'Bone':
  24872. object = new Bone();
  24873. break;
  24874. default:
  24875. object = new Object3D();
  24876. }
  24877. object.uuid = data.uuid;
  24878. if ( data.name !== undefined ) object.name = data.name;
  24879. if ( data.matrix !== undefined ) {
  24880. object.matrix.fromArray( data.matrix );
  24881. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24882. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  24883. } else {
  24884. if ( data.position !== undefined ) object.position.fromArray( data.position );
  24885. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  24886. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  24887. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  24888. }
  24889. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  24890. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  24891. if ( data.shadow ) {
  24892. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  24893. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  24894. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  24895. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  24896. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  24897. }
  24898. if ( data.visible !== undefined ) object.visible = data.visible;
  24899. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  24900. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  24901. if ( data.userData !== undefined ) object.userData = data.userData;
  24902. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  24903. if ( data.children !== undefined ) {
  24904. const children = data.children;
  24905. for ( let i = 0; i < children.length; i ++ ) {
  24906. object.add( this.parseObject( children[ i ], geometries, materials, animations ) );
  24907. }
  24908. }
  24909. if ( data.animations !== undefined ) {
  24910. const objectAnimations = data.animations;
  24911. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  24912. const uuid = objectAnimations[ i ];
  24913. object.animations.push( animations[ uuid ] );
  24914. }
  24915. }
  24916. if ( data.type === 'LOD' ) {
  24917. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  24918. const levels = data.levels;
  24919. for ( let l = 0; l < levels.length; l ++ ) {
  24920. const level = levels[ l ];
  24921. const child = object.getObjectByProperty( 'uuid', level.object );
  24922. if ( child !== undefined ) {
  24923. object.addLevel( child, level.distance );
  24924. }
  24925. }
  24926. }
  24927. return object;
  24928. }
  24929. bindSkeletons( object, skeletons ) {
  24930. if ( Object.keys( skeletons ).length === 0 ) return;
  24931. object.traverse( function ( child ) {
  24932. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  24933. const skeleton = skeletons[ child.skeleton ];
  24934. if ( skeleton === undefined ) {
  24935. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  24936. } else {
  24937. child.bind( skeleton, child.bindMatrix );
  24938. }
  24939. }
  24940. } );
  24941. }
  24942. /* DEPRECATED */
  24943. setTexturePath( value ) {
  24944. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  24945. return this.setResourcePath( value );
  24946. }
  24947. }
  24948. const TEXTURE_MAPPING = {
  24949. UVMapping: UVMapping,
  24950. CubeReflectionMapping: CubeReflectionMapping,
  24951. CubeRefractionMapping: CubeRefractionMapping,
  24952. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24953. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24954. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24955. CubeUVRefractionMapping: CubeUVRefractionMapping
  24956. };
  24957. const TEXTURE_WRAPPING = {
  24958. RepeatWrapping: RepeatWrapping,
  24959. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24960. MirroredRepeatWrapping: MirroredRepeatWrapping
  24961. };
  24962. const TEXTURE_FILTER = {
  24963. NearestFilter: NearestFilter,
  24964. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24965. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24966. LinearFilter: LinearFilter,
  24967. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24968. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24969. };
  24970. function ImageBitmapLoader( manager ) {
  24971. if ( typeof createImageBitmap === 'undefined' ) {
  24972. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  24973. }
  24974. if ( typeof fetch === 'undefined' ) {
  24975. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  24976. }
  24977. Loader.call( this, manager );
  24978. this.options = { premultiplyAlpha: 'none' };
  24979. }
  24980. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24981. constructor: ImageBitmapLoader,
  24982. isImageBitmapLoader: true,
  24983. setOptions: function setOptions( options ) {
  24984. this.options = options;
  24985. return this;
  24986. },
  24987. load: function ( url, onLoad, onProgress, onError ) {
  24988. if ( url === undefined ) url = '';
  24989. if ( this.path !== undefined ) url = this.path + url;
  24990. url = this.manager.resolveURL( url );
  24991. const scope = this;
  24992. const cached = Cache.get( url );
  24993. if ( cached !== undefined ) {
  24994. scope.manager.itemStart( url );
  24995. setTimeout( function () {
  24996. if ( onLoad ) onLoad( cached );
  24997. scope.manager.itemEnd( url );
  24998. }, 0 );
  24999. return cached;
  25000. }
  25001. const fetchOptions = {};
  25002. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25003. fetch( url, fetchOptions ).then( function ( res ) {
  25004. return res.blob();
  25005. } ).then( function ( blob ) {
  25006. //console.log('getBlob', url )
  25007. return createImageBitmap( blob, scope.options );
  25008. } ).then( function ( imageBitmap ) {
  25009. Cache.add( url, imageBitmap );
  25010. if ( onLoad ) onLoad( imageBitmap );
  25011. scope.manager.itemEnd( url );
  25012. } ).catch( function ( e ) {
  25013. //console.log('error', url, e)
  25014. if ( onError ) onError( e, url );
  25015. scope.manager.itemError( url );
  25016. scope.manager.itemEnd( url );
  25017. } );
  25018. scope.manager.itemStart( url );
  25019. }
  25020. } );
  25021. function ShapePath() {
  25022. this.type = 'ShapePath';
  25023. this.color = new Color();
  25024. this.subPaths = [];
  25025. this.currentPath = null;
  25026. }
  25027. Object.assign( ShapePath.prototype, {
  25028. moveTo: function ( x, y ) {
  25029. this.currentPath = new Path();
  25030. this.subPaths.push( this.currentPath );
  25031. this.currentPath.moveTo( x, y );
  25032. return this;
  25033. },
  25034. lineTo: function ( x, y ) {
  25035. this.currentPath.lineTo( x, y );
  25036. return this;
  25037. },
  25038. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25039. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  25040. return this;
  25041. },
  25042. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25043. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  25044. return this;
  25045. },
  25046. splineThru: function ( pts ) {
  25047. this.currentPath.splineThru( pts );
  25048. return this;
  25049. },
  25050. toShapes: function ( isCCW, noHoles ) {
  25051. function toShapesNoHoles( inSubpaths ) {
  25052. const shapes = [];
  25053. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  25054. const tmpPath = inSubpaths[ i ];
  25055. const tmpShape = new Shape();
  25056. tmpShape.curves = tmpPath.curves;
  25057. shapes.push( tmpShape );
  25058. }
  25059. return shapes;
  25060. }
  25061. function isPointInsidePolygon( inPt, inPolygon ) {
  25062. const polyLen = inPolygon.length;
  25063. // inPt on polygon contour => immediate success or
  25064. // toggling of inside/outside at every single! intersection point of an edge
  25065. // with the horizontal line through inPt, left of inPt
  25066. // not counting lowerY endpoints of edges and whole edges on that line
  25067. let inside = false;
  25068. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  25069. let edgeLowPt = inPolygon[ p ];
  25070. let edgeHighPt = inPolygon[ q ];
  25071. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  25072. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  25073. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  25074. // not parallel
  25075. if ( edgeDy < 0 ) {
  25076. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  25077. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  25078. }
  25079. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  25080. if ( inPt.y === edgeLowPt.y ) {
  25081. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  25082. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25083. } else {
  25084. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  25085. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  25086. if ( perpEdge < 0 ) continue;
  25087. inside = ! inside; // true intersection left of inPt
  25088. }
  25089. } else {
  25090. // parallel or collinear
  25091. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  25092. // edge lies on the same horizontal line as inPt
  25093. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  25094. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  25095. // continue;
  25096. }
  25097. }
  25098. return inside;
  25099. }
  25100. const isClockWise = ShapeUtils.isClockWise;
  25101. const subPaths = this.subPaths;
  25102. if ( subPaths.length === 0 ) return [];
  25103. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  25104. let solid, tmpPath, tmpShape;
  25105. const shapes = [];
  25106. if ( subPaths.length === 1 ) {
  25107. tmpPath = subPaths[ 0 ];
  25108. tmpShape = new Shape();
  25109. tmpShape.curves = tmpPath.curves;
  25110. shapes.push( tmpShape );
  25111. return shapes;
  25112. }
  25113. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  25114. holesFirst = isCCW ? ! holesFirst : holesFirst;
  25115. // console.log("Holes first", holesFirst);
  25116. const betterShapeHoles = [];
  25117. const newShapes = [];
  25118. let newShapeHoles = [];
  25119. let mainIdx = 0;
  25120. let tmpPoints;
  25121. newShapes[ mainIdx ] = undefined;
  25122. newShapeHoles[ mainIdx ] = [];
  25123. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  25124. tmpPath = subPaths[ i ];
  25125. tmpPoints = tmpPath.getPoints();
  25126. solid = isClockWise( tmpPoints );
  25127. solid = isCCW ? ! solid : solid;
  25128. if ( solid ) {
  25129. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25130. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25131. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  25132. if ( holesFirst ) mainIdx ++;
  25133. newShapeHoles[ mainIdx ] = [];
  25134. //console.log('cw', i);
  25135. } else {
  25136. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  25137. //console.log('ccw', i);
  25138. }
  25139. }
  25140. // only Holes? -> probably all Shapes with wrong orientation
  25141. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  25142. if ( newShapes.length > 1 ) {
  25143. let ambiguous = false;
  25144. const toChange = [];
  25145. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25146. betterShapeHoles[ sIdx ] = [];
  25147. }
  25148. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25149. const sho = newShapeHoles[ sIdx ];
  25150. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  25151. const ho = sho[ hIdx ];
  25152. let hole_unassigned = true;
  25153. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  25154. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  25155. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  25156. if ( hole_unassigned ) {
  25157. hole_unassigned = false;
  25158. betterShapeHoles[ s2Idx ].push( ho );
  25159. } else {
  25160. ambiguous = true;
  25161. }
  25162. }
  25163. }
  25164. if ( hole_unassigned ) {
  25165. betterShapeHoles[ sIdx ].push( ho );
  25166. }
  25167. }
  25168. }
  25169. // console.log("ambiguous: ", ambiguous);
  25170. if ( toChange.length > 0 ) {
  25171. // console.log("to change: ", toChange);
  25172. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  25173. }
  25174. }
  25175. let tmpHoles;
  25176. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  25177. tmpShape = newShapes[ i ].s;
  25178. shapes.push( tmpShape );
  25179. tmpHoles = newShapeHoles[ i ];
  25180. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  25181. tmpShape.holes.push( tmpHoles[ j ].h );
  25182. }
  25183. }
  25184. //console.log("shape", shapes);
  25185. return shapes;
  25186. }
  25187. } );
  25188. function Font( data ) {
  25189. this.type = 'Font';
  25190. this.data = data;
  25191. }
  25192. Object.assign( Font.prototype, {
  25193. isFont: true,
  25194. generateShapes: function ( text, size = 100 ) {
  25195. const shapes = [];
  25196. const paths = createPaths( text, size, this.data );
  25197. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  25198. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  25199. }
  25200. return shapes;
  25201. }
  25202. } );
  25203. function createPaths( text, size, data ) {
  25204. const chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
  25205. const scale = size / data.resolution;
  25206. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  25207. const paths = [];
  25208. let offsetX = 0, offsetY = 0;
  25209. for ( let i = 0; i < chars.length; i ++ ) {
  25210. const char = chars[ i ];
  25211. if ( char === '\n' ) {
  25212. offsetX = 0;
  25213. offsetY -= line_height;
  25214. } else {
  25215. const ret = createPath( char, scale, offsetX, offsetY, data );
  25216. offsetX += ret.offsetX;
  25217. paths.push( ret.path );
  25218. }
  25219. }
  25220. return paths;
  25221. }
  25222. function createPath( char, scale, offsetX, offsetY, data ) {
  25223. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  25224. if ( ! glyph ) {
  25225. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  25226. return;
  25227. }
  25228. const path = new ShapePath();
  25229. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25230. if ( glyph.o ) {
  25231. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25232. for ( let i = 0, l = outline.length; i < l; ) {
  25233. const action = outline[ i ++ ];
  25234. switch ( action ) {
  25235. case 'm': // moveTo
  25236. x = outline[ i ++ ] * scale + offsetX;
  25237. y = outline[ i ++ ] * scale + offsetY;
  25238. path.moveTo( x, y );
  25239. break;
  25240. case 'l': // lineTo
  25241. x = outline[ i ++ ] * scale + offsetX;
  25242. y = outline[ i ++ ] * scale + offsetY;
  25243. path.lineTo( x, y );
  25244. break;
  25245. case 'q': // quadraticCurveTo
  25246. cpx = outline[ i ++ ] * scale + offsetX;
  25247. cpy = outline[ i ++ ] * scale + offsetY;
  25248. cpx1 = outline[ i ++ ] * scale + offsetX;
  25249. cpy1 = outline[ i ++ ] * scale + offsetY;
  25250. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  25251. break;
  25252. case 'b': // bezierCurveTo
  25253. cpx = outline[ i ++ ] * scale + offsetX;
  25254. cpy = outline[ i ++ ] * scale + offsetY;
  25255. cpx1 = outline[ i ++ ] * scale + offsetX;
  25256. cpy1 = outline[ i ++ ] * scale + offsetY;
  25257. cpx2 = outline[ i ++ ] * scale + offsetX;
  25258. cpy2 = outline[ i ++ ] * scale + offsetY;
  25259. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  25260. break;
  25261. }
  25262. }
  25263. }
  25264. return { offsetX: glyph.ha * scale, path: path };
  25265. }
  25266. function FontLoader( manager ) {
  25267. Loader.call( this, manager );
  25268. }
  25269. FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  25270. constructor: FontLoader,
  25271. load: function ( url, onLoad, onProgress, onError ) {
  25272. const scope = this;
  25273. const loader = new FileLoader( this.manager );
  25274. loader.setPath( this.path );
  25275. loader.setRequestHeader( this.requestHeader );
  25276. loader.setWithCredentials( scope.withCredentials );
  25277. loader.load( url, function ( text ) {
  25278. let json;
  25279. try {
  25280. json = JSON.parse( text );
  25281. } catch ( e ) {
  25282. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  25283. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  25284. }
  25285. const font = scope.parse( json );
  25286. if ( onLoad ) onLoad( font );
  25287. }, onProgress, onError );
  25288. },
  25289. parse: function ( json ) {
  25290. return new Font( json );
  25291. }
  25292. } );
  25293. let _context;
  25294. const AudioContext = {
  25295. getContext: function () {
  25296. if ( _context === undefined ) {
  25297. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25298. }
  25299. return _context;
  25300. },
  25301. setContext: function ( value ) {
  25302. _context = value;
  25303. }
  25304. };
  25305. function AudioLoader( manager ) {
  25306. Loader.call( this, manager );
  25307. }
  25308. AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  25309. constructor: AudioLoader,
  25310. load: function ( url, onLoad, onProgress, onError ) {
  25311. const scope = this;
  25312. const loader = new FileLoader( scope.manager );
  25313. loader.setResponseType( 'arraybuffer' );
  25314. loader.setPath( scope.path );
  25315. loader.setRequestHeader( scope.requestHeader );
  25316. loader.setWithCredentials( scope.withCredentials );
  25317. loader.load( url, function ( buffer ) {
  25318. try {
  25319. // Create a copy of the buffer. The `decodeAudioData` method
  25320. // detaches the buffer when complete, preventing reuse.
  25321. const bufferCopy = buffer.slice( 0 );
  25322. const context = AudioContext.getContext();
  25323. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25324. onLoad( audioBuffer );
  25325. } );
  25326. } catch ( e ) {
  25327. if ( onError ) {
  25328. onError( e );
  25329. } else {
  25330. console.error( e );
  25331. }
  25332. scope.manager.itemError( url );
  25333. }
  25334. }, onProgress, onError );
  25335. }
  25336. } );
  25337. function HemisphereLightProbe( skyColor, groundColor, intensity ) {
  25338. LightProbe.call( this, undefined, intensity );
  25339. const color1 = new Color().set( skyColor );
  25340. const color2 = new Color().set( groundColor );
  25341. const sky = new Vector3( color1.r, color1.g, color1.b );
  25342. const ground = new Vector3( color2.r, color2.g, color2.b );
  25343. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25344. const c0 = Math.sqrt( Math.PI );
  25345. const c1 = c0 * Math.sqrt( 0.75 );
  25346. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25347. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25348. }
  25349. HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  25350. constructor: HemisphereLightProbe,
  25351. isHemisphereLightProbe: true,
  25352. copy: function ( source ) { // modifying colors not currently supported
  25353. LightProbe.prototype.copy.call( this, source );
  25354. return this;
  25355. },
  25356. toJSON: function ( meta ) {
  25357. const data = LightProbe.prototype.toJSON.call( this, meta );
  25358. // data.sh = this.sh.toArray(); // todo
  25359. return data;
  25360. }
  25361. } );
  25362. function AmbientLightProbe( color, intensity ) {
  25363. LightProbe.call( this, undefined, intensity );
  25364. const color1 = new Color().set( color );
  25365. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25366. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25367. }
  25368. AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  25369. constructor: AmbientLightProbe,
  25370. isAmbientLightProbe: true,
  25371. copy: function ( source ) { // modifying color not currently supported
  25372. LightProbe.prototype.copy.call( this, source );
  25373. return this;
  25374. },
  25375. toJSON: function ( meta ) {
  25376. const data = LightProbe.prototype.toJSON.call( this, meta );
  25377. // data.sh = this.sh.toArray(); // todo
  25378. return data;
  25379. }
  25380. } );
  25381. const _eyeRight = new Matrix4();
  25382. const _eyeLeft = new Matrix4();
  25383. function StereoCamera() {
  25384. this.type = 'StereoCamera';
  25385. this.aspect = 1;
  25386. this.eyeSep = 0.064;
  25387. this.cameraL = new PerspectiveCamera();
  25388. this.cameraL.layers.enable( 1 );
  25389. this.cameraL.matrixAutoUpdate = false;
  25390. this.cameraR = new PerspectiveCamera();
  25391. this.cameraR.layers.enable( 2 );
  25392. this.cameraR.matrixAutoUpdate = false;
  25393. this._cache = {
  25394. focus: null,
  25395. fov: null,
  25396. aspect: null,
  25397. near: null,
  25398. far: null,
  25399. zoom: null,
  25400. eyeSep: null
  25401. };
  25402. }
  25403. Object.assign( StereoCamera.prototype, {
  25404. update: function ( camera ) {
  25405. const cache = this._cache;
  25406. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25407. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25408. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25409. if ( needsUpdate ) {
  25410. cache.focus = camera.focus;
  25411. cache.fov = camera.fov;
  25412. cache.aspect = camera.aspect * this.aspect;
  25413. cache.near = camera.near;
  25414. cache.far = camera.far;
  25415. cache.zoom = camera.zoom;
  25416. cache.eyeSep = this.eyeSep;
  25417. // Off-axis stereoscopic effect based on
  25418. // http://paulbourke.net/stereographics/stereorender/
  25419. const projectionMatrix = camera.projectionMatrix.clone();
  25420. const eyeSepHalf = cache.eyeSep / 2;
  25421. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25422. const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25423. let xmin, xmax;
  25424. // translate xOffset
  25425. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25426. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25427. // for left eye
  25428. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25429. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25430. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25431. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25432. this.cameraL.projectionMatrix.copy( projectionMatrix );
  25433. // for right eye
  25434. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25435. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25436. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25437. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25438. this.cameraR.projectionMatrix.copy( projectionMatrix );
  25439. }
  25440. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25441. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25442. }
  25443. } );
  25444. class Clock {
  25445. constructor( autoStart ) {
  25446. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  25447. this.startTime = 0;
  25448. this.oldTime = 0;
  25449. this.elapsedTime = 0;
  25450. this.running = false;
  25451. }
  25452. start() {
  25453. this.startTime = now();
  25454. this.oldTime = this.startTime;
  25455. this.elapsedTime = 0;
  25456. this.running = true;
  25457. }
  25458. stop() {
  25459. this.getElapsedTime();
  25460. this.running = false;
  25461. this.autoStart = false;
  25462. }
  25463. getElapsedTime() {
  25464. this.getDelta();
  25465. return this.elapsedTime;
  25466. }
  25467. getDelta() {
  25468. let diff = 0;
  25469. if ( this.autoStart && ! this.running ) {
  25470. this.start();
  25471. return 0;
  25472. }
  25473. if ( this.running ) {
  25474. const newTime = now();
  25475. diff = ( newTime - this.oldTime ) / 1000;
  25476. this.oldTime = newTime;
  25477. this.elapsedTime += diff;
  25478. }
  25479. return diff;
  25480. }
  25481. }
  25482. function now() {
  25483. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25484. }
  25485. const _position$2 = /*@__PURE__*/ new Vector3();
  25486. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  25487. const _scale$1 = /*@__PURE__*/ new Vector3();
  25488. const _orientation = /*@__PURE__*/ new Vector3();
  25489. class AudioListener extends Object3D {
  25490. constructor() {
  25491. super();
  25492. this.type = 'AudioListener';
  25493. this.context = AudioContext.getContext();
  25494. this.gain = this.context.createGain();
  25495. this.gain.connect( this.context.destination );
  25496. this.filter = null;
  25497. this.timeDelta = 0;
  25498. // private
  25499. this._clock = new Clock();
  25500. }
  25501. getInput() {
  25502. return this.gain;
  25503. }
  25504. removeFilter() {
  25505. if ( this.filter !== null ) {
  25506. this.gain.disconnect( this.filter );
  25507. this.filter.disconnect( this.context.destination );
  25508. this.gain.connect( this.context.destination );
  25509. this.filter = null;
  25510. }
  25511. return this;
  25512. }
  25513. getFilter() {
  25514. return this.filter;
  25515. }
  25516. setFilter( value ) {
  25517. if ( this.filter !== null ) {
  25518. this.gain.disconnect( this.filter );
  25519. this.filter.disconnect( this.context.destination );
  25520. } else {
  25521. this.gain.disconnect( this.context.destination );
  25522. }
  25523. this.filter = value;
  25524. this.gain.connect( this.filter );
  25525. this.filter.connect( this.context.destination );
  25526. return this;
  25527. }
  25528. getMasterVolume() {
  25529. return this.gain.gain.value;
  25530. }
  25531. setMasterVolume( value ) {
  25532. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25533. return this;
  25534. }
  25535. updateMatrixWorld( force ) {
  25536. super.updateMatrixWorld( force );
  25537. const listener = this.context.listener;
  25538. const up = this.up;
  25539. this.timeDelta = this._clock.getDelta();
  25540. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  25541. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  25542. if ( listener.positionX ) {
  25543. // code path for Chrome (see #14393)
  25544. const endTime = this.context.currentTime + this.timeDelta;
  25545. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  25546. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  25547. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  25548. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  25549. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  25550. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  25551. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25552. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25553. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25554. } else {
  25555. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  25556. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  25557. }
  25558. }
  25559. }
  25560. class Audio extends Object3D {
  25561. constructor( listener ) {
  25562. super();
  25563. this.type = 'Audio';
  25564. this.listener = listener;
  25565. this.context = listener.context;
  25566. this.gain = this.context.createGain();
  25567. this.gain.connect( listener.getInput() );
  25568. this.autoplay = false;
  25569. this.buffer = null;
  25570. this.detune = 0;
  25571. this.loop = false;
  25572. this.loopStart = 0;
  25573. this.loopEnd = 0;
  25574. this.offset = 0;
  25575. this.duration = undefined;
  25576. this.playbackRate = 1;
  25577. this.isPlaying = false;
  25578. this.hasPlaybackControl = true;
  25579. this.source = null;
  25580. this.sourceType = 'empty';
  25581. this._startedAt = 0;
  25582. this._progress = 0;
  25583. this._connected = false;
  25584. this.filters = [];
  25585. }
  25586. getOutput() {
  25587. return this.gain;
  25588. }
  25589. setNodeSource( audioNode ) {
  25590. this.hasPlaybackControl = false;
  25591. this.sourceType = 'audioNode';
  25592. this.source = audioNode;
  25593. this.connect();
  25594. return this;
  25595. }
  25596. setMediaElementSource( mediaElement ) {
  25597. this.hasPlaybackControl = false;
  25598. this.sourceType = 'mediaNode';
  25599. this.source = this.context.createMediaElementSource( mediaElement );
  25600. this.connect();
  25601. return this;
  25602. }
  25603. setMediaStreamSource( mediaStream ) {
  25604. this.hasPlaybackControl = false;
  25605. this.sourceType = 'mediaStreamNode';
  25606. this.source = this.context.createMediaStreamSource( mediaStream );
  25607. this.connect();
  25608. return this;
  25609. }
  25610. setBuffer( audioBuffer ) {
  25611. this.buffer = audioBuffer;
  25612. this.sourceType = 'buffer';
  25613. if ( this.autoplay ) this.play();
  25614. return this;
  25615. }
  25616. play( delay = 0 ) {
  25617. if ( this.isPlaying === true ) {
  25618. console.warn( 'THREE.Audio: Audio is already playing.' );
  25619. return;
  25620. }
  25621. if ( this.hasPlaybackControl === false ) {
  25622. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25623. return;
  25624. }
  25625. this._startedAt = this.context.currentTime + delay;
  25626. const source = this.context.createBufferSource();
  25627. source.buffer = this.buffer;
  25628. source.loop = this.loop;
  25629. source.loopStart = this.loopStart;
  25630. source.loopEnd = this.loopEnd;
  25631. source.onended = this.onEnded.bind( this );
  25632. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25633. this.isPlaying = true;
  25634. this.source = source;
  25635. this.setDetune( this.detune );
  25636. this.setPlaybackRate( this.playbackRate );
  25637. return this.connect();
  25638. }
  25639. pause() {
  25640. if ( this.hasPlaybackControl === false ) {
  25641. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25642. return;
  25643. }
  25644. if ( this.isPlaying === true ) {
  25645. // update current progress
  25646. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25647. if ( this.loop === true ) {
  25648. // ensure _progress does not exceed duration with looped audios
  25649. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25650. }
  25651. this.source.stop();
  25652. this.source.onended = null;
  25653. this.isPlaying = false;
  25654. }
  25655. return this;
  25656. }
  25657. stop() {
  25658. if ( this.hasPlaybackControl === false ) {
  25659. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25660. return;
  25661. }
  25662. this._progress = 0;
  25663. this.source.stop();
  25664. this.source.onended = null;
  25665. this.isPlaying = false;
  25666. return this;
  25667. }
  25668. connect() {
  25669. if ( this.filters.length > 0 ) {
  25670. this.source.connect( this.filters[ 0 ] );
  25671. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25672. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25673. }
  25674. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25675. } else {
  25676. this.source.connect( this.getOutput() );
  25677. }
  25678. this._connected = true;
  25679. return this;
  25680. }
  25681. disconnect() {
  25682. if ( this.filters.length > 0 ) {
  25683. this.source.disconnect( this.filters[ 0 ] );
  25684. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25685. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25686. }
  25687. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25688. } else {
  25689. this.source.disconnect( this.getOutput() );
  25690. }
  25691. this._connected = false;
  25692. return this;
  25693. }
  25694. getFilters() {
  25695. return this.filters;
  25696. }
  25697. setFilters( value ) {
  25698. if ( ! value ) value = [];
  25699. if ( this._connected === true ) {
  25700. this.disconnect();
  25701. this.filters = value.slice();
  25702. this.connect();
  25703. } else {
  25704. this.filters = value.slice();
  25705. }
  25706. return this;
  25707. }
  25708. setDetune( value ) {
  25709. this.detune = value;
  25710. if ( this.source.detune === undefined ) return; // only set detune when available
  25711. if ( this.isPlaying === true ) {
  25712. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25713. }
  25714. return this;
  25715. }
  25716. getDetune() {
  25717. return this.detune;
  25718. }
  25719. getFilter() {
  25720. return this.getFilters()[ 0 ];
  25721. }
  25722. setFilter( filter ) {
  25723. return this.setFilters( filter ? [ filter ] : [] );
  25724. }
  25725. setPlaybackRate( value ) {
  25726. if ( this.hasPlaybackControl === false ) {
  25727. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25728. return;
  25729. }
  25730. this.playbackRate = value;
  25731. if ( this.isPlaying === true ) {
  25732. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25733. }
  25734. return this;
  25735. }
  25736. getPlaybackRate() {
  25737. return this.playbackRate;
  25738. }
  25739. onEnded() {
  25740. this.isPlaying = false;
  25741. }
  25742. getLoop() {
  25743. if ( this.hasPlaybackControl === false ) {
  25744. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25745. return false;
  25746. }
  25747. return this.loop;
  25748. }
  25749. setLoop( value ) {
  25750. if ( this.hasPlaybackControl === false ) {
  25751. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25752. return;
  25753. }
  25754. this.loop = value;
  25755. if ( this.isPlaying === true ) {
  25756. this.source.loop = this.loop;
  25757. }
  25758. return this;
  25759. }
  25760. setLoopStart( value ) {
  25761. this.loopStart = value;
  25762. return this;
  25763. }
  25764. setLoopEnd( value ) {
  25765. this.loopEnd = value;
  25766. return this;
  25767. }
  25768. getVolume() {
  25769. return this.gain.gain.value;
  25770. }
  25771. setVolume( value ) {
  25772. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25773. return this;
  25774. }
  25775. }
  25776. const _position$3 = /*@__PURE__*/ new Vector3();
  25777. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  25778. const _scale$2 = /*@__PURE__*/ new Vector3();
  25779. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25780. class PositionalAudio extends Audio {
  25781. constructor( listener ) {
  25782. super( listener );
  25783. this.panner = this.context.createPanner();
  25784. this.panner.panningModel = 'HRTF';
  25785. this.panner.connect( this.gain );
  25786. }
  25787. getOutput() {
  25788. return this.panner;
  25789. }
  25790. getRefDistance() {
  25791. return this.panner.refDistance;
  25792. }
  25793. setRefDistance( value ) {
  25794. this.panner.refDistance = value;
  25795. return this;
  25796. }
  25797. getRolloffFactor() {
  25798. return this.panner.rolloffFactor;
  25799. }
  25800. setRolloffFactor( value ) {
  25801. this.panner.rolloffFactor = value;
  25802. return this;
  25803. }
  25804. getDistanceModel() {
  25805. return this.panner.distanceModel;
  25806. }
  25807. setDistanceModel( value ) {
  25808. this.panner.distanceModel = value;
  25809. return this;
  25810. }
  25811. getMaxDistance() {
  25812. return this.panner.maxDistance;
  25813. }
  25814. setMaxDistance( value ) {
  25815. this.panner.maxDistance = value;
  25816. return this;
  25817. }
  25818. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25819. this.panner.coneInnerAngle = coneInnerAngle;
  25820. this.panner.coneOuterAngle = coneOuterAngle;
  25821. this.panner.coneOuterGain = coneOuterGain;
  25822. return this;
  25823. }
  25824. updateMatrixWorld( force ) {
  25825. super.updateMatrixWorld( force );
  25826. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25827. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  25828. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  25829. const panner = this.panner;
  25830. if ( panner.positionX ) {
  25831. // code path for Chrome and Firefox (see #14393)
  25832. const endTime = this.context.currentTime + this.listener.timeDelta;
  25833. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  25834. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  25835. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  25836. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25837. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25838. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25839. } else {
  25840. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  25841. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  25842. }
  25843. }
  25844. }
  25845. class AudioAnalyser {
  25846. constructor( audio, fftSize = 2048 ) {
  25847. this.analyser = audio.context.createAnalyser();
  25848. this.analyser.fftSize = fftSize;
  25849. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25850. audio.getOutput().connect( this.analyser );
  25851. }
  25852. getFrequencyData() {
  25853. this.analyser.getByteFrequencyData( this.data );
  25854. return this.data;
  25855. }
  25856. getAverageFrequency() {
  25857. let value = 0;
  25858. const data = this.getFrequencyData();
  25859. for ( let i = 0; i < data.length; i ++ ) {
  25860. value += data[ i ];
  25861. }
  25862. return value / data.length;
  25863. }
  25864. }
  25865. function PropertyMixer( binding, typeName, valueSize ) {
  25866. this.binding = binding;
  25867. this.valueSize = valueSize;
  25868. let mixFunction,
  25869. mixFunctionAdditive,
  25870. setIdentity;
  25871. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25872. //
  25873. // interpolators can use .buffer as their .result
  25874. // the data then goes to 'incoming'
  25875. //
  25876. // 'accu0' and 'accu1' are used frame-interleaved for
  25877. // the cumulative result and are compared to detect
  25878. // changes
  25879. //
  25880. // 'orig' stores the original state of the property
  25881. //
  25882. // 'add' is used for additive cumulative results
  25883. //
  25884. // 'work' is optional and is only present for quaternion types. It is used
  25885. // to store intermediate quaternion multiplication results
  25886. switch ( typeName ) {
  25887. case 'quaternion':
  25888. mixFunction = this._slerp;
  25889. mixFunctionAdditive = this._slerpAdditive;
  25890. setIdentity = this._setAdditiveIdentityQuaternion;
  25891. this.buffer = new Float64Array( valueSize * 6 );
  25892. this._workIndex = 5;
  25893. break;
  25894. case 'string':
  25895. case 'bool':
  25896. mixFunction = this._select;
  25897. // Use the regular mix function and for additive on these types,
  25898. // additive is not relevant for non-numeric types
  25899. mixFunctionAdditive = this._select;
  25900. setIdentity = this._setAdditiveIdentityOther;
  25901. this.buffer = new Array( valueSize * 5 );
  25902. break;
  25903. default:
  25904. mixFunction = this._lerp;
  25905. mixFunctionAdditive = this._lerpAdditive;
  25906. setIdentity = this._setAdditiveIdentityNumeric;
  25907. this.buffer = new Float64Array( valueSize * 5 );
  25908. }
  25909. this._mixBufferRegion = mixFunction;
  25910. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25911. this._setIdentity = setIdentity;
  25912. this._origIndex = 3;
  25913. this._addIndex = 4;
  25914. this.cumulativeWeight = 0;
  25915. this.cumulativeWeightAdditive = 0;
  25916. this.useCount = 0;
  25917. this.referenceCount = 0;
  25918. }
  25919. Object.assign( PropertyMixer.prototype, {
  25920. // accumulate data in the 'incoming' region into 'accu<i>'
  25921. accumulate: function ( accuIndex, weight ) {
  25922. // note: happily accumulating nothing when weight = 0, the caller knows
  25923. // the weight and shouldn't have made the call in the first place
  25924. const buffer = this.buffer,
  25925. stride = this.valueSize,
  25926. offset = accuIndex * stride + stride;
  25927. let currentWeight = this.cumulativeWeight;
  25928. if ( currentWeight === 0 ) {
  25929. // accuN := incoming * weight
  25930. for ( let i = 0; i !== stride; ++ i ) {
  25931. buffer[ offset + i ] = buffer[ i ];
  25932. }
  25933. currentWeight = weight;
  25934. } else {
  25935. // accuN := accuN + incoming * weight
  25936. currentWeight += weight;
  25937. const mix = weight / currentWeight;
  25938. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  25939. }
  25940. this.cumulativeWeight = currentWeight;
  25941. },
  25942. // accumulate data in the 'incoming' region into 'add'
  25943. accumulateAdditive: function ( weight ) {
  25944. const buffer = this.buffer,
  25945. stride = this.valueSize,
  25946. offset = stride * this._addIndex;
  25947. if ( this.cumulativeWeightAdditive === 0 ) {
  25948. // add = identity
  25949. this._setIdentity();
  25950. }
  25951. // add := add + incoming * weight
  25952. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  25953. this.cumulativeWeightAdditive += weight;
  25954. },
  25955. // apply the state of 'accu<i>' to the binding when accus differ
  25956. apply: function ( accuIndex ) {
  25957. const stride = this.valueSize,
  25958. buffer = this.buffer,
  25959. offset = accuIndex * stride + stride,
  25960. weight = this.cumulativeWeight,
  25961. weightAdditive = this.cumulativeWeightAdditive,
  25962. binding = this.binding;
  25963. this.cumulativeWeight = 0;
  25964. this.cumulativeWeightAdditive = 0;
  25965. if ( weight < 1 ) {
  25966. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25967. const originalValueOffset = stride * this._origIndex;
  25968. this._mixBufferRegion(
  25969. buffer, offset, originalValueOffset, 1 - weight, stride );
  25970. }
  25971. if ( weightAdditive > 0 ) {
  25972. // accuN := accuN + additive accuN
  25973. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  25974. }
  25975. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  25976. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  25977. // value has changed -> update scene graph
  25978. binding.setValue( buffer, offset );
  25979. break;
  25980. }
  25981. }
  25982. },
  25983. // remember the state of the bound property and copy it to both accus
  25984. saveOriginalState: function () {
  25985. const binding = this.binding;
  25986. const buffer = this.buffer,
  25987. stride = this.valueSize,
  25988. originalValueOffset = stride * this._origIndex;
  25989. binding.getValue( buffer, originalValueOffset );
  25990. // accu[0..1] := orig -- initially detect changes against the original
  25991. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  25992. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  25993. }
  25994. // Add to identity for additive
  25995. this._setIdentity();
  25996. this.cumulativeWeight = 0;
  25997. this.cumulativeWeightAdditive = 0;
  25998. },
  25999. // apply the state previously taken via 'saveOriginalState' to the binding
  26000. restoreOriginalState: function () {
  26001. const originalValueOffset = this.valueSize * 3;
  26002. this.binding.setValue( this.buffer, originalValueOffset );
  26003. },
  26004. _setAdditiveIdentityNumeric: function () {
  26005. const startIndex = this._addIndex * this.valueSize;
  26006. const endIndex = startIndex + this.valueSize;
  26007. for ( let i = startIndex; i < endIndex; i ++ ) {
  26008. this.buffer[ i ] = 0;
  26009. }
  26010. },
  26011. _setAdditiveIdentityQuaternion: function () {
  26012. this._setAdditiveIdentityNumeric();
  26013. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26014. },
  26015. _setAdditiveIdentityOther: function () {
  26016. const startIndex = this._origIndex * this.valueSize;
  26017. const targetIndex = this._addIndex * this.valueSize;
  26018. for ( let i = 0; i < this.valueSize; i ++ ) {
  26019. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26020. }
  26021. },
  26022. // mix functions
  26023. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26024. if ( t >= 0.5 ) {
  26025. for ( let i = 0; i !== stride; ++ i ) {
  26026. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26027. }
  26028. }
  26029. },
  26030. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  26031. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26032. },
  26033. _slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26034. const workOffset = this._workIndex * stride;
  26035. // Store result in intermediate buffer offset
  26036. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26037. // Slerp to the intermediate result
  26038. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26039. },
  26040. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26041. const s = 1 - t;
  26042. for ( let i = 0; i !== stride; ++ i ) {
  26043. const j = dstOffset + i;
  26044. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26045. }
  26046. },
  26047. _lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26048. for ( let i = 0; i !== stride; ++ i ) {
  26049. const j = dstOffset + i;
  26050. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26051. }
  26052. }
  26053. } );
  26054. // Characters [].:/ are reserved for track binding syntax.
  26055. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26056. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26057. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26058. // only latin characters, and the unicode \p{L} is not yet supported. So
  26059. // instead, we exclude reserved characters and match everything else.
  26060. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26061. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26062. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26063. // be matched to parse the rest of the track name.
  26064. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26065. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26066. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26067. // Object on target node, and accessor. May not contain reserved
  26068. // characters. Accessor may contain any character except closing bracket.
  26069. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26070. // Property and accessor. May not contain reserved characters. Accessor may
  26071. // contain any non-bracket characters.
  26072. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26073. const _trackRe = new RegExp( ''
  26074. + '^'
  26075. + _directoryRe
  26076. + _nodeRe
  26077. + _objectRe
  26078. + _propertyRe
  26079. + '$'
  26080. );
  26081. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  26082. function Composite( targetGroup, path, optionalParsedPath ) {
  26083. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26084. this._targetGroup = targetGroup;
  26085. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26086. }
  26087. Object.assign( Composite.prototype, {
  26088. getValue: function ( array, offset ) {
  26089. this.bind(); // bind all binding
  26090. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26091. binding = this._bindings[ firstValidIndex ];
  26092. // and only call .getValue on the first
  26093. if ( binding !== undefined ) binding.getValue( array, offset );
  26094. },
  26095. setValue: function ( array, offset ) {
  26096. const bindings = this._bindings;
  26097. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26098. bindings[ i ].setValue( array, offset );
  26099. }
  26100. },
  26101. bind: function () {
  26102. const bindings = this._bindings;
  26103. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26104. bindings[ i ].bind();
  26105. }
  26106. },
  26107. unbind: function () {
  26108. const bindings = this._bindings;
  26109. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26110. bindings[ i ].unbind();
  26111. }
  26112. }
  26113. } );
  26114. function PropertyBinding( rootNode, path, parsedPath ) {
  26115. this.path = path;
  26116. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26117. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26118. this.rootNode = rootNode;
  26119. }
  26120. Object.assign( PropertyBinding, {
  26121. Composite: Composite,
  26122. create: function ( root, path, parsedPath ) {
  26123. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26124. return new PropertyBinding( root, path, parsedPath );
  26125. } else {
  26126. return new PropertyBinding.Composite( root, path, parsedPath );
  26127. }
  26128. },
  26129. /**
  26130. * Replaces spaces with underscores and removes unsupported characters from
  26131. * node names, to ensure compatibility with parseTrackName().
  26132. *
  26133. * @param {string} name Node name to be sanitized.
  26134. * @return {string}
  26135. */
  26136. sanitizeNodeName: function ( name ) {
  26137. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26138. },
  26139. parseTrackName: function ( trackName ) {
  26140. const matches = _trackRe.exec( trackName );
  26141. if ( ! matches ) {
  26142. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26143. }
  26144. const results = {
  26145. // directoryName: matches[ 1 ], // (tschw) currently unused
  26146. nodeName: matches[ 2 ],
  26147. objectName: matches[ 3 ],
  26148. objectIndex: matches[ 4 ],
  26149. propertyName: matches[ 5 ], // required
  26150. propertyIndex: matches[ 6 ]
  26151. };
  26152. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26153. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26154. const objectName = results.nodeName.substring( lastDot + 1 );
  26155. // Object names must be checked against an allowlist. Otherwise, there
  26156. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26157. // 'bar' could be the objectName, or part of a nodeName (which can
  26158. // include '.' characters).
  26159. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26160. results.nodeName = results.nodeName.substring( 0, lastDot );
  26161. results.objectName = objectName;
  26162. }
  26163. }
  26164. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26165. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26166. }
  26167. return results;
  26168. },
  26169. findNode: function ( root, nodeName ) {
  26170. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26171. return root;
  26172. }
  26173. // search into skeleton bones.
  26174. if ( root.skeleton ) {
  26175. const bone = root.skeleton.getBoneByName( nodeName );
  26176. if ( bone !== undefined ) {
  26177. return bone;
  26178. }
  26179. }
  26180. // search into node subtree.
  26181. if ( root.children ) {
  26182. const searchNodeSubtree = function ( children ) {
  26183. for ( let i = 0; i < children.length; i ++ ) {
  26184. const childNode = children[ i ];
  26185. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26186. return childNode;
  26187. }
  26188. const result = searchNodeSubtree( childNode.children );
  26189. if ( result ) return result;
  26190. }
  26191. return null;
  26192. };
  26193. const subTreeNode = searchNodeSubtree( root.children );
  26194. if ( subTreeNode ) {
  26195. return subTreeNode;
  26196. }
  26197. }
  26198. return null;
  26199. }
  26200. } );
  26201. Object.assign( PropertyBinding.prototype, { // prototype, continued
  26202. // these are used to "bind" a nonexistent property
  26203. _getValue_unavailable: function () {},
  26204. _setValue_unavailable: function () {},
  26205. BindingType: {
  26206. Direct: 0,
  26207. EntireArray: 1,
  26208. ArrayElement: 2,
  26209. HasFromToArray: 3
  26210. },
  26211. Versioning: {
  26212. None: 0,
  26213. NeedsUpdate: 1,
  26214. MatrixWorldNeedsUpdate: 2
  26215. },
  26216. GetterByBindingType: [
  26217. function getValue_direct( buffer, offset ) {
  26218. buffer[ offset ] = this.node[ this.propertyName ];
  26219. },
  26220. function getValue_array( buffer, offset ) {
  26221. const source = this.resolvedProperty;
  26222. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26223. buffer[ offset ++ ] = source[ i ];
  26224. }
  26225. },
  26226. function getValue_arrayElement( buffer, offset ) {
  26227. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26228. },
  26229. function getValue_toArray( buffer, offset ) {
  26230. this.resolvedProperty.toArray( buffer, offset );
  26231. }
  26232. ],
  26233. SetterByBindingTypeAndVersioning: [
  26234. [
  26235. // Direct
  26236. function setValue_direct( buffer, offset ) {
  26237. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26238. },
  26239. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26240. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26241. this.targetObject.needsUpdate = true;
  26242. },
  26243. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26244. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26245. this.targetObject.matrixWorldNeedsUpdate = true;
  26246. }
  26247. ], [
  26248. // EntireArray
  26249. function setValue_array( buffer, offset ) {
  26250. const dest = this.resolvedProperty;
  26251. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26252. dest[ i ] = buffer[ offset ++ ];
  26253. }
  26254. },
  26255. function setValue_array_setNeedsUpdate( buffer, offset ) {
  26256. const dest = this.resolvedProperty;
  26257. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26258. dest[ i ] = buffer[ offset ++ ];
  26259. }
  26260. this.targetObject.needsUpdate = true;
  26261. },
  26262. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26263. const dest = this.resolvedProperty;
  26264. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26265. dest[ i ] = buffer[ offset ++ ];
  26266. }
  26267. this.targetObject.matrixWorldNeedsUpdate = true;
  26268. }
  26269. ], [
  26270. // ArrayElement
  26271. function setValue_arrayElement( buffer, offset ) {
  26272. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26273. },
  26274. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26275. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26276. this.targetObject.needsUpdate = true;
  26277. },
  26278. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26279. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26280. this.targetObject.matrixWorldNeedsUpdate = true;
  26281. }
  26282. ], [
  26283. // HasToFromArray
  26284. function setValue_fromArray( buffer, offset ) {
  26285. this.resolvedProperty.fromArray( buffer, offset );
  26286. },
  26287. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26288. this.resolvedProperty.fromArray( buffer, offset );
  26289. this.targetObject.needsUpdate = true;
  26290. },
  26291. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26292. this.resolvedProperty.fromArray( buffer, offset );
  26293. this.targetObject.matrixWorldNeedsUpdate = true;
  26294. }
  26295. ]
  26296. ],
  26297. getValue: function getValue_unbound( targetArray, offset ) {
  26298. this.bind();
  26299. this.getValue( targetArray, offset );
  26300. // Note: This class uses a State pattern on a per-method basis:
  26301. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26302. // prototype version of these methods with one that represents
  26303. // the bound state. When the property is not found, the methods
  26304. // become no-ops.
  26305. },
  26306. setValue: function getValue_unbound( sourceArray, offset ) {
  26307. this.bind();
  26308. this.setValue( sourceArray, offset );
  26309. },
  26310. // create getter / setter pair for a property in the scene graph
  26311. bind: function () {
  26312. let targetObject = this.node;
  26313. const parsedPath = this.parsedPath;
  26314. const objectName = parsedPath.objectName;
  26315. const propertyName = parsedPath.propertyName;
  26316. let propertyIndex = parsedPath.propertyIndex;
  26317. if ( ! targetObject ) {
  26318. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26319. this.node = targetObject;
  26320. }
  26321. // set fail state so we can just 'return' on error
  26322. this.getValue = this._getValue_unavailable;
  26323. this.setValue = this._setValue_unavailable;
  26324. // ensure there is a value node
  26325. if ( ! targetObject ) {
  26326. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26327. return;
  26328. }
  26329. if ( objectName ) {
  26330. let objectIndex = parsedPath.objectIndex;
  26331. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26332. switch ( objectName ) {
  26333. case 'materials':
  26334. if ( ! targetObject.material ) {
  26335. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26336. return;
  26337. }
  26338. if ( ! targetObject.material.materials ) {
  26339. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26340. return;
  26341. }
  26342. targetObject = targetObject.material.materials;
  26343. break;
  26344. case 'bones':
  26345. if ( ! targetObject.skeleton ) {
  26346. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26347. return;
  26348. }
  26349. // potential future optimization: skip this if propertyIndex is already an integer
  26350. // and convert the integer string to a true integer.
  26351. targetObject = targetObject.skeleton.bones;
  26352. // support resolving morphTarget names into indices.
  26353. for ( let i = 0; i < targetObject.length; i ++ ) {
  26354. if ( targetObject[ i ].name === objectIndex ) {
  26355. objectIndex = i;
  26356. break;
  26357. }
  26358. }
  26359. break;
  26360. default:
  26361. if ( targetObject[ objectName ] === undefined ) {
  26362. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26363. return;
  26364. }
  26365. targetObject = targetObject[ objectName ];
  26366. }
  26367. if ( objectIndex !== undefined ) {
  26368. if ( targetObject[ objectIndex ] === undefined ) {
  26369. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26370. return;
  26371. }
  26372. targetObject = targetObject[ objectIndex ];
  26373. }
  26374. }
  26375. // resolve property
  26376. const nodeProperty = targetObject[ propertyName ];
  26377. if ( nodeProperty === undefined ) {
  26378. const nodeName = parsedPath.nodeName;
  26379. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26380. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26381. return;
  26382. }
  26383. // determine versioning scheme
  26384. let versioning = this.Versioning.None;
  26385. this.targetObject = targetObject;
  26386. if ( targetObject.needsUpdate !== undefined ) { // material
  26387. versioning = this.Versioning.NeedsUpdate;
  26388. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26389. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26390. }
  26391. // determine how the property gets bound
  26392. let bindingType = this.BindingType.Direct;
  26393. if ( propertyIndex !== undefined ) {
  26394. // access a sub element of the property array (only primitives are supported right now)
  26395. if ( propertyName === 'morphTargetInfluences' ) {
  26396. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26397. // support resolving morphTarget names into indices.
  26398. if ( ! targetObject.geometry ) {
  26399. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26400. return;
  26401. }
  26402. if ( targetObject.geometry.isBufferGeometry ) {
  26403. if ( ! targetObject.geometry.morphAttributes ) {
  26404. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26405. return;
  26406. }
  26407. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26408. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26409. }
  26410. } else {
  26411. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  26412. return;
  26413. }
  26414. }
  26415. bindingType = this.BindingType.ArrayElement;
  26416. this.resolvedProperty = nodeProperty;
  26417. this.propertyIndex = propertyIndex;
  26418. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26419. // must use copy for Object3D.Euler/Quaternion
  26420. bindingType = this.BindingType.HasFromToArray;
  26421. this.resolvedProperty = nodeProperty;
  26422. } else if ( Array.isArray( nodeProperty ) ) {
  26423. bindingType = this.BindingType.EntireArray;
  26424. this.resolvedProperty = nodeProperty;
  26425. } else {
  26426. this.propertyName = propertyName;
  26427. }
  26428. // select getter / setter
  26429. this.getValue = this.GetterByBindingType[ bindingType ];
  26430. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26431. },
  26432. unbind: function () {
  26433. this.node = null;
  26434. // back to the prototype version of getValue / setValue
  26435. // note: avoiding to mutate the shape of 'this' via 'delete'
  26436. this.getValue = this._getValue_unbound;
  26437. this.setValue = this._setValue_unbound;
  26438. }
  26439. } );
  26440. // DECLARE ALIAS AFTER assign prototype
  26441. Object.assign( PropertyBinding.prototype, {
  26442. // initial state of these methods that calls 'bind'
  26443. _getValue_unbound: PropertyBinding.prototype.getValue,
  26444. _setValue_unbound: PropertyBinding.prototype.setValue,
  26445. } );
  26446. /**
  26447. *
  26448. * A group of objects that receives a shared animation state.
  26449. *
  26450. * Usage:
  26451. *
  26452. * - Add objects you would otherwise pass as 'root' to the
  26453. * constructor or the .clipAction method of AnimationMixer.
  26454. *
  26455. * - Instead pass this object as 'root'.
  26456. *
  26457. * - You can also add and remove objects later when the mixer
  26458. * is running.
  26459. *
  26460. * Note:
  26461. *
  26462. * Objects of this class appear as one object to the mixer,
  26463. * so cache control of the individual objects must be done
  26464. * on the group.
  26465. *
  26466. * Limitation:
  26467. *
  26468. * - The animated properties must be compatible among the
  26469. * all objects in the group.
  26470. *
  26471. * - A single property can either be controlled through a
  26472. * target group or directly, but not both.
  26473. */
  26474. function AnimationObjectGroup() {
  26475. this.uuid = MathUtils.generateUUID();
  26476. // cached objects followed by the active ones
  26477. this._objects = Array.prototype.slice.call( arguments );
  26478. this.nCachedObjects_ = 0; // threshold
  26479. // note: read by PropertyBinding.Composite
  26480. const indices = {};
  26481. this._indicesByUUID = indices; // for bookkeeping
  26482. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26483. indices[ arguments[ i ].uuid ] = i;
  26484. }
  26485. this._paths = []; // inside: string
  26486. this._parsedPaths = []; // inside: { we don't care, here }
  26487. this._bindings = []; // inside: Array< PropertyBinding >
  26488. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26489. const scope = this;
  26490. this.stats = {
  26491. objects: {
  26492. get total() {
  26493. return scope._objects.length;
  26494. },
  26495. get inUse() {
  26496. return this.total - scope.nCachedObjects_;
  26497. }
  26498. },
  26499. get bindingsPerObject() {
  26500. return scope._bindings.length;
  26501. }
  26502. };
  26503. }
  26504. Object.assign( AnimationObjectGroup.prototype, {
  26505. isAnimationObjectGroup: true,
  26506. add: function () {
  26507. const objects = this._objects,
  26508. indicesByUUID = this._indicesByUUID,
  26509. paths = this._paths,
  26510. parsedPaths = this._parsedPaths,
  26511. bindings = this._bindings,
  26512. nBindings = bindings.length;
  26513. let knownObject = undefined,
  26514. nObjects = objects.length,
  26515. nCachedObjects = this.nCachedObjects_;
  26516. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26517. const object = arguments[ i ],
  26518. uuid = object.uuid;
  26519. let index = indicesByUUID[ uuid ];
  26520. if ( index === undefined ) {
  26521. // unknown object -> add it to the ACTIVE region
  26522. index = nObjects ++;
  26523. indicesByUUID[ uuid ] = index;
  26524. objects.push( object );
  26525. // accounting is done, now do the same for all bindings
  26526. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26527. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26528. }
  26529. } else if ( index < nCachedObjects ) {
  26530. knownObject = objects[ index ];
  26531. // move existing object to the ACTIVE region
  26532. const firstActiveIndex = -- nCachedObjects,
  26533. lastCachedObject = objects[ firstActiveIndex ];
  26534. indicesByUUID[ lastCachedObject.uuid ] = index;
  26535. objects[ index ] = lastCachedObject;
  26536. indicesByUUID[ uuid ] = firstActiveIndex;
  26537. objects[ firstActiveIndex ] = object;
  26538. // accounting is done, now do the same for all bindings
  26539. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26540. const bindingsForPath = bindings[ j ],
  26541. lastCached = bindingsForPath[ firstActiveIndex ];
  26542. let binding = bindingsForPath[ index ];
  26543. bindingsForPath[ index ] = lastCached;
  26544. if ( binding === undefined ) {
  26545. // since we do not bother to create new bindings
  26546. // for objects that are cached, the binding may
  26547. // or may not exist
  26548. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26549. }
  26550. bindingsForPath[ firstActiveIndex ] = binding;
  26551. }
  26552. } else if ( objects[ index ] !== knownObject ) {
  26553. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26554. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26555. } // else the object is already where we want it to be
  26556. } // for arguments
  26557. this.nCachedObjects_ = nCachedObjects;
  26558. },
  26559. remove: function () {
  26560. const objects = this._objects,
  26561. indicesByUUID = this._indicesByUUID,
  26562. bindings = this._bindings,
  26563. nBindings = bindings.length;
  26564. let nCachedObjects = this.nCachedObjects_;
  26565. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26566. const object = arguments[ i ],
  26567. uuid = object.uuid,
  26568. index = indicesByUUID[ uuid ];
  26569. if ( index !== undefined && index >= nCachedObjects ) {
  26570. // move existing object into the CACHED region
  26571. const lastCachedIndex = nCachedObjects ++,
  26572. firstActiveObject = objects[ lastCachedIndex ];
  26573. indicesByUUID[ firstActiveObject.uuid ] = index;
  26574. objects[ index ] = firstActiveObject;
  26575. indicesByUUID[ uuid ] = lastCachedIndex;
  26576. objects[ lastCachedIndex ] = object;
  26577. // accounting is done, now do the same for all bindings
  26578. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26579. const bindingsForPath = bindings[ j ],
  26580. firstActive = bindingsForPath[ lastCachedIndex ],
  26581. binding = bindingsForPath[ index ];
  26582. bindingsForPath[ index ] = firstActive;
  26583. bindingsForPath[ lastCachedIndex ] = binding;
  26584. }
  26585. }
  26586. } // for arguments
  26587. this.nCachedObjects_ = nCachedObjects;
  26588. },
  26589. // remove & forget
  26590. uncache: function () {
  26591. const objects = this._objects,
  26592. indicesByUUID = this._indicesByUUID,
  26593. bindings = this._bindings,
  26594. nBindings = bindings.length;
  26595. let nCachedObjects = this.nCachedObjects_,
  26596. nObjects = objects.length;
  26597. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26598. const object = arguments[ i ],
  26599. uuid = object.uuid,
  26600. index = indicesByUUID[ uuid ];
  26601. if ( index !== undefined ) {
  26602. delete indicesByUUID[ uuid ];
  26603. if ( index < nCachedObjects ) {
  26604. // object is cached, shrink the CACHED region
  26605. const firstActiveIndex = -- nCachedObjects,
  26606. lastCachedObject = objects[ firstActiveIndex ],
  26607. lastIndex = -- nObjects,
  26608. lastObject = objects[ lastIndex ];
  26609. // last cached object takes this object's place
  26610. indicesByUUID[ lastCachedObject.uuid ] = index;
  26611. objects[ index ] = lastCachedObject;
  26612. // last object goes to the activated slot and pop
  26613. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26614. objects[ firstActiveIndex ] = lastObject;
  26615. objects.pop();
  26616. // accounting is done, now do the same for all bindings
  26617. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26618. const bindingsForPath = bindings[ j ],
  26619. lastCached = bindingsForPath[ firstActiveIndex ],
  26620. last = bindingsForPath[ lastIndex ];
  26621. bindingsForPath[ index ] = lastCached;
  26622. bindingsForPath[ firstActiveIndex ] = last;
  26623. bindingsForPath.pop();
  26624. }
  26625. } else {
  26626. // object is active, just swap with the last and pop
  26627. const lastIndex = -- nObjects,
  26628. lastObject = objects[ lastIndex ];
  26629. if ( lastIndex > 0 ) {
  26630. indicesByUUID[ lastObject.uuid ] = index;
  26631. }
  26632. objects[ index ] = lastObject;
  26633. objects.pop();
  26634. // accounting is done, now do the same for all bindings
  26635. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26636. const bindingsForPath = bindings[ j ];
  26637. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26638. bindingsForPath.pop();
  26639. }
  26640. } // cached or active
  26641. } // if object is known
  26642. } // for arguments
  26643. this.nCachedObjects_ = nCachedObjects;
  26644. },
  26645. // Internal interface used by befriended PropertyBinding.Composite:
  26646. subscribe_: function ( path, parsedPath ) {
  26647. // returns an array of bindings for the given path that is changed
  26648. // according to the contained objects in the group
  26649. const indicesByPath = this._bindingsIndicesByPath;
  26650. let index = indicesByPath[ path ];
  26651. const bindings = this._bindings;
  26652. if ( index !== undefined ) return bindings[ index ];
  26653. const paths = this._paths,
  26654. parsedPaths = this._parsedPaths,
  26655. objects = this._objects,
  26656. nObjects = objects.length,
  26657. nCachedObjects = this.nCachedObjects_,
  26658. bindingsForPath = new Array( nObjects );
  26659. index = bindings.length;
  26660. indicesByPath[ path ] = index;
  26661. paths.push( path );
  26662. parsedPaths.push( parsedPath );
  26663. bindings.push( bindingsForPath );
  26664. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26665. const object = objects[ i ];
  26666. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26667. }
  26668. return bindingsForPath;
  26669. },
  26670. unsubscribe_: function ( path ) {
  26671. // tells the group to forget about a property path and no longer
  26672. // update the array previously obtained with 'subscribe_'
  26673. const indicesByPath = this._bindingsIndicesByPath,
  26674. index = indicesByPath[ path ];
  26675. if ( index !== undefined ) {
  26676. const paths = this._paths,
  26677. parsedPaths = this._parsedPaths,
  26678. bindings = this._bindings,
  26679. lastBindingsIndex = bindings.length - 1,
  26680. lastBindings = bindings[ lastBindingsIndex ],
  26681. lastBindingsPath = path[ lastBindingsIndex ];
  26682. indicesByPath[ lastBindingsPath ] = index;
  26683. bindings[ index ] = lastBindings;
  26684. bindings.pop();
  26685. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26686. parsedPaths.pop();
  26687. paths[ index ] = paths[ lastBindingsIndex ];
  26688. paths.pop();
  26689. }
  26690. }
  26691. } );
  26692. class AnimationAction {
  26693. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26694. this._mixer = mixer;
  26695. this._clip = clip;
  26696. this._localRoot = localRoot;
  26697. this.blendMode = blendMode;
  26698. const tracks = clip.tracks,
  26699. nTracks = tracks.length,
  26700. interpolants = new Array( nTracks );
  26701. const interpolantSettings = {
  26702. endingStart: ZeroCurvatureEnding,
  26703. endingEnd: ZeroCurvatureEnding
  26704. };
  26705. for ( let i = 0; i !== nTracks; ++ i ) {
  26706. const interpolant = tracks[ i ].createInterpolant( null );
  26707. interpolants[ i ] = interpolant;
  26708. interpolant.settings = interpolantSettings;
  26709. }
  26710. this._interpolantSettings = interpolantSettings;
  26711. this._interpolants = interpolants; // bound by the mixer
  26712. // inside: PropertyMixer (managed by the mixer)
  26713. this._propertyBindings = new Array( nTracks );
  26714. this._cacheIndex = null; // for the memory manager
  26715. this._byClipCacheIndex = null; // for the memory manager
  26716. this._timeScaleInterpolant = null;
  26717. this._weightInterpolant = null;
  26718. this.loop = LoopRepeat;
  26719. this._loopCount = - 1;
  26720. // global mixer time when the action is to be started
  26721. // it's set back to 'null' upon start of the action
  26722. this._startTime = null;
  26723. // scaled local time of the action
  26724. // gets clamped or wrapped to 0..clip.duration according to loop
  26725. this.time = 0;
  26726. this.timeScale = 1;
  26727. this._effectiveTimeScale = 1;
  26728. this.weight = 1;
  26729. this._effectiveWeight = 1;
  26730. this.repetitions = Infinity; // no. of repetitions when looping
  26731. this.paused = false; // true -> zero effective time scale
  26732. this.enabled = true; // false -> zero effective weight
  26733. this.clampWhenFinished = false;// keep feeding the last frame?
  26734. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26735. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26736. }
  26737. // State & Scheduling
  26738. play() {
  26739. this._mixer._activateAction( this );
  26740. return this;
  26741. }
  26742. stop() {
  26743. this._mixer._deactivateAction( this );
  26744. return this.reset();
  26745. }
  26746. reset() {
  26747. this.paused = false;
  26748. this.enabled = true;
  26749. this.time = 0; // restart clip
  26750. this._loopCount = - 1;// forget previous loops
  26751. this._startTime = null;// forget scheduling
  26752. return this.stopFading().stopWarping();
  26753. }
  26754. isRunning() {
  26755. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26756. this._startTime === null && this._mixer._isActiveAction( this );
  26757. }
  26758. // return true when play has been called
  26759. isScheduled() {
  26760. return this._mixer._isActiveAction( this );
  26761. }
  26762. startAt( time ) {
  26763. this._startTime = time;
  26764. return this;
  26765. }
  26766. setLoop( mode, repetitions ) {
  26767. this.loop = mode;
  26768. this.repetitions = repetitions;
  26769. return this;
  26770. }
  26771. // Weight
  26772. // set the weight stopping any scheduled fading
  26773. // although .enabled = false yields an effective weight of zero, this
  26774. // method does *not* change .enabled, because it would be confusing
  26775. setEffectiveWeight( weight ) {
  26776. this.weight = weight;
  26777. // note: same logic as when updated at runtime
  26778. this._effectiveWeight = this.enabled ? weight : 0;
  26779. return this.stopFading();
  26780. }
  26781. // return the weight considering fading and .enabled
  26782. getEffectiveWeight() {
  26783. return this._effectiveWeight;
  26784. }
  26785. fadeIn( duration ) {
  26786. return this._scheduleFading( duration, 0, 1 );
  26787. }
  26788. fadeOut( duration ) {
  26789. return this._scheduleFading( duration, 1, 0 );
  26790. }
  26791. crossFadeFrom( fadeOutAction, duration, warp ) {
  26792. fadeOutAction.fadeOut( duration );
  26793. this.fadeIn( duration );
  26794. if ( warp ) {
  26795. const fadeInDuration = this._clip.duration,
  26796. fadeOutDuration = fadeOutAction._clip.duration,
  26797. startEndRatio = fadeOutDuration / fadeInDuration,
  26798. endStartRatio = fadeInDuration / fadeOutDuration;
  26799. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26800. this.warp( endStartRatio, 1.0, duration );
  26801. }
  26802. return this;
  26803. }
  26804. crossFadeTo( fadeInAction, duration, warp ) {
  26805. return fadeInAction.crossFadeFrom( this, duration, warp );
  26806. }
  26807. stopFading() {
  26808. const weightInterpolant = this._weightInterpolant;
  26809. if ( weightInterpolant !== null ) {
  26810. this._weightInterpolant = null;
  26811. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26812. }
  26813. return this;
  26814. }
  26815. // Time Scale Control
  26816. // set the time scale stopping any scheduled warping
  26817. // although .paused = true yields an effective time scale of zero, this
  26818. // method does *not* change .paused, because it would be confusing
  26819. setEffectiveTimeScale( timeScale ) {
  26820. this.timeScale = timeScale;
  26821. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26822. return this.stopWarping();
  26823. }
  26824. // return the time scale considering warping and .paused
  26825. getEffectiveTimeScale() {
  26826. return this._effectiveTimeScale;
  26827. }
  26828. setDuration( duration ) {
  26829. this.timeScale = this._clip.duration / duration;
  26830. return this.stopWarping();
  26831. }
  26832. syncWith( action ) {
  26833. this.time = action.time;
  26834. this.timeScale = action.timeScale;
  26835. return this.stopWarping();
  26836. }
  26837. halt( duration ) {
  26838. return this.warp( this._effectiveTimeScale, 0, duration );
  26839. }
  26840. warp( startTimeScale, endTimeScale, duration ) {
  26841. const mixer = this._mixer,
  26842. now = mixer.time,
  26843. timeScale = this.timeScale;
  26844. let interpolant = this._timeScaleInterpolant;
  26845. if ( interpolant === null ) {
  26846. interpolant = mixer._lendControlInterpolant();
  26847. this._timeScaleInterpolant = interpolant;
  26848. }
  26849. const times = interpolant.parameterPositions,
  26850. values = interpolant.sampleValues;
  26851. times[ 0 ] = now;
  26852. times[ 1 ] = now + duration;
  26853. values[ 0 ] = startTimeScale / timeScale;
  26854. values[ 1 ] = endTimeScale / timeScale;
  26855. return this;
  26856. }
  26857. stopWarping() {
  26858. const timeScaleInterpolant = this._timeScaleInterpolant;
  26859. if ( timeScaleInterpolant !== null ) {
  26860. this._timeScaleInterpolant = null;
  26861. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26862. }
  26863. return this;
  26864. }
  26865. // Object Accessors
  26866. getMixer() {
  26867. return this._mixer;
  26868. }
  26869. getClip() {
  26870. return this._clip;
  26871. }
  26872. getRoot() {
  26873. return this._localRoot || this._mixer._root;
  26874. }
  26875. // Interna
  26876. _update( time, deltaTime, timeDirection, accuIndex ) {
  26877. // called by the mixer
  26878. if ( ! this.enabled ) {
  26879. // call ._updateWeight() to update ._effectiveWeight
  26880. this._updateWeight( time );
  26881. return;
  26882. }
  26883. const startTime = this._startTime;
  26884. if ( startTime !== null ) {
  26885. // check for scheduled start of action
  26886. const timeRunning = ( time - startTime ) * timeDirection;
  26887. if ( timeRunning < 0 || timeDirection === 0 ) {
  26888. return; // yet to come / don't decide when delta = 0
  26889. }
  26890. // start
  26891. this._startTime = null; // unschedule
  26892. deltaTime = timeDirection * timeRunning;
  26893. }
  26894. // apply time scale and advance time
  26895. deltaTime *= this._updateTimeScale( time );
  26896. const clipTime = this._updateTime( deltaTime );
  26897. // note: _updateTime may disable the action resulting in
  26898. // an effective weight of 0
  26899. const weight = this._updateWeight( time );
  26900. if ( weight > 0 ) {
  26901. const interpolants = this._interpolants;
  26902. const propertyMixers = this._propertyBindings;
  26903. switch ( this.blendMode ) {
  26904. case AdditiveAnimationBlendMode:
  26905. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26906. interpolants[ j ].evaluate( clipTime );
  26907. propertyMixers[ j ].accumulateAdditive( weight );
  26908. }
  26909. break;
  26910. case NormalAnimationBlendMode:
  26911. default:
  26912. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  26913. interpolants[ j ].evaluate( clipTime );
  26914. propertyMixers[ j ].accumulate( accuIndex, weight );
  26915. }
  26916. }
  26917. }
  26918. }
  26919. _updateWeight( time ) {
  26920. let weight = 0;
  26921. if ( this.enabled ) {
  26922. weight = this.weight;
  26923. const interpolant = this._weightInterpolant;
  26924. if ( interpolant !== null ) {
  26925. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26926. weight *= interpolantValue;
  26927. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26928. this.stopFading();
  26929. if ( interpolantValue === 0 ) {
  26930. // faded out, disable
  26931. this.enabled = false;
  26932. }
  26933. }
  26934. }
  26935. }
  26936. this._effectiveWeight = weight;
  26937. return weight;
  26938. }
  26939. _updateTimeScale( time ) {
  26940. let timeScale = 0;
  26941. if ( ! this.paused ) {
  26942. timeScale = this.timeScale;
  26943. const interpolant = this._timeScaleInterpolant;
  26944. if ( interpolant !== null ) {
  26945. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  26946. timeScale *= interpolantValue;
  26947. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26948. this.stopWarping();
  26949. if ( timeScale === 0 ) {
  26950. // motion has halted, pause
  26951. this.paused = true;
  26952. } else {
  26953. // warp done - apply final time scale
  26954. this.timeScale = timeScale;
  26955. }
  26956. }
  26957. }
  26958. }
  26959. this._effectiveTimeScale = timeScale;
  26960. return timeScale;
  26961. }
  26962. _updateTime( deltaTime ) {
  26963. const duration = this._clip.duration;
  26964. const loop = this.loop;
  26965. let time = this.time + deltaTime;
  26966. let loopCount = this._loopCount;
  26967. const pingPong = ( loop === LoopPingPong );
  26968. if ( deltaTime === 0 ) {
  26969. if ( loopCount === - 1 ) return time;
  26970. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  26971. }
  26972. if ( loop === LoopOnce ) {
  26973. if ( loopCount === - 1 ) {
  26974. // just started
  26975. this._loopCount = 0;
  26976. this._setEndings( true, true, false );
  26977. }
  26978. handle_stop: {
  26979. if ( time >= duration ) {
  26980. time = duration;
  26981. } else if ( time < 0 ) {
  26982. time = 0;
  26983. } else {
  26984. this.time = time;
  26985. break handle_stop;
  26986. }
  26987. if ( this.clampWhenFinished ) this.paused = true;
  26988. else this.enabled = false;
  26989. this.time = time;
  26990. this._mixer.dispatchEvent( {
  26991. type: 'finished', action: this,
  26992. direction: deltaTime < 0 ? - 1 : 1
  26993. } );
  26994. }
  26995. } else { // repetitive Repeat or PingPong
  26996. if ( loopCount === - 1 ) {
  26997. // just started
  26998. if ( deltaTime >= 0 ) {
  26999. loopCount = 0;
  27000. this._setEndings( true, this.repetitions === 0, pingPong );
  27001. } else {
  27002. // when looping in reverse direction, the initial
  27003. // transition through zero counts as a repetition,
  27004. // so leave loopCount at -1
  27005. this._setEndings( this.repetitions === 0, true, pingPong );
  27006. }
  27007. }
  27008. if ( time >= duration || time < 0 ) {
  27009. // wrap around
  27010. const loopDelta = Math.floor( time / duration ); // signed
  27011. time -= duration * loopDelta;
  27012. loopCount += Math.abs( loopDelta );
  27013. const pending = this.repetitions - loopCount;
  27014. if ( pending <= 0 ) {
  27015. // have to stop (switch state, clamp time, fire event)
  27016. if ( this.clampWhenFinished ) this.paused = true;
  27017. else this.enabled = false;
  27018. time = deltaTime > 0 ? duration : 0;
  27019. this.time = time;
  27020. this._mixer.dispatchEvent( {
  27021. type: 'finished', action: this,
  27022. direction: deltaTime > 0 ? 1 : - 1
  27023. } );
  27024. } else {
  27025. // keep running
  27026. if ( pending === 1 ) {
  27027. // entering the last round
  27028. const atStart = deltaTime < 0;
  27029. this._setEndings( atStart, ! atStart, pingPong );
  27030. } else {
  27031. this._setEndings( false, false, pingPong );
  27032. }
  27033. this._loopCount = loopCount;
  27034. this.time = time;
  27035. this._mixer.dispatchEvent( {
  27036. type: 'loop', action: this, loopDelta: loopDelta
  27037. } );
  27038. }
  27039. } else {
  27040. this.time = time;
  27041. }
  27042. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27043. // invert time for the "pong round"
  27044. return duration - time;
  27045. }
  27046. }
  27047. return time;
  27048. }
  27049. _setEndings( atStart, atEnd, pingPong ) {
  27050. const settings = this._interpolantSettings;
  27051. if ( pingPong ) {
  27052. settings.endingStart = ZeroSlopeEnding;
  27053. settings.endingEnd = ZeroSlopeEnding;
  27054. } else {
  27055. // assuming for LoopOnce atStart == atEnd == true
  27056. if ( atStart ) {
  27057. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27058. } else {
  27059. settings.endingStart = WrapAroundEnding;
  27060. }
  27061. if ( atEnd ) {
  27062. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27063. } else {
  27064. settings.endingEnd = WrapAroundEnding;
  27065. }
  27066. }
  27067. }
  27068. _scheduleFading( duration, weightNow, weightThen ) {
  27069. const mixer = this._mixer, now = mixer.time;
  27070. let interpolant = this._weightInterpolant;
  27071. if ( interpolant === null ) {
  27072. interpolant = mixer._lendControlInterpolant();
  27073. this._weightInterpolant = interpolant;
  27074. }
  27075. const times = interpolant.parameterPositions,
  27076. values = interpolant.sampleValues;
  27077. times[ 0 ] = now;
  27078. values[ 0 ] = weightNow;
  27079. times[ 1 ] = now + duration;
  27080. values[ 1 ] = weightThen;
  27081. return this;
  27082. }
  27083. }
  27084. function AnimationMixer( root ) {
  27085. this._root = root;
  27086. this._initMemoryManager();
  27087. this._accuIndex = 0;
  27088. this.time = 0;
  27089. this.timeScale = 1.0;
  27090. }
  27091. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  27092. constructor: AnimationMixer,
  27093. _bindAction: function ( action, prototypeAction ) {
  27094. const root = action._localRoot || this._root,
  27095. tracks = action._clip.tracks,
  27096. nTracks = tracks.length,
  27097. bindings = action._propertyBindings,
  27098. interpolants = action._interpolants,
  27099. rootUuid = root.uuid,
  27100. bindingsByRoot = this._bindingsByRootAndName;
  27101. let bindingsByName = bindingsByRoot[ rootUuid ];
  27102. if ( bindingsByName === undefined ) {
  27103. bindingsByName = {};
  27104. bindingsByRoot[ rootUuid ] = bindingsByName;
  27105. }
  27106. for ( let i = 0; i !== nTracks; ++ i ) {
  27107. const track = tracks[ i ],
  27108. trackName = track.name;
  27109. let binding = bindingsByName[ trackName ];
  27110. if ( binding !== undefined ) {
  27111. bindings[ i ] = binding;
  27112. } else {
  27113. binding = bindings[ i ];
  27114. if ( binding !== undefined ) {
  27115. // existing binding, make sure the cache knows
  27116. if ( binding._cacheIndex === null ) {
  27117. ++ binding.referenceCount;
  27118. this._addInactiveBinding( binding, rootUuid, trackName );
  27119. }
  27120. continue;
  27121. }
  27122. const path = prototypeAction && prototypeAction.
  27123. _propertyBindings[ i ].binding.parsedPath;
  27124. binding = new PropertyMixer(
  27125. PropertyBinding.create( root, trackName, path ),
  27126. track.ValueTypeName, track.getValueSize() );
  27127. ++ binding.referenceCount;
  27128. this._addInactiveBinding( binding, rootUuid, trackName );
  27129. bindings[ i ] = binding;
  27130. }
  27131. interpolants[ i ].resultBuffer = binding.buffer;
  27132. }
  27133. },
  27134. _activateAction: function ( action ) {
  27135. if ( ! this._isActiveAction( action ) ) {
  27136. if ( action._cacheIndex === null ) {
  27137. // this action has been forgotten by the cache, but the user
  27138. // appears to be still using it -> rebind
  27139. const rootUuid = ( action._localRoot || this._root ).uuid,
  27140. clipUuid = action._clip.uuid,
  27141. actionsForClip = this._actionsByClip[ clipUuid ];
  27142. this._bindAction( action,
  27143. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27144. this._addInactiveAction( action, clipUuid, rootUuid );
  27145. }
  27146. const bindings = action._propertyBindings;
  27147. // increment reference counts / sort out state
  27148. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27149. const binding = bindings[ i ];
  27150. if ( binding.useCount ++ === 0 ) {
  27151. this._lendBinding( binding );
  27152. binding.saveOriginalState();
  27153. }
  27154. }
  27155. this._lendAction( action );
  27156. }
  27157. },
  27158. _deactivateAction: function ( action ) {
  27159. if ( this._isActiveAction( action ) ) {
  27160. const bindings = action._propertyBindings;
  27161. // decrement reference counts / sort out state
  27162. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27163. const binding = bindings[ i ];
  27164. if ( -- binding.useCount === 0 ) {
  27165. binding.restoreOriginalState();
  27166. this._takeBackBinding( binding );
  27167. }
  27168. }
  27169. this._takeBackAction( action );
  27170. }
  27171. },
  27172. // Memory manager
  27173. _initMemoryManager: function () {
  27174. this._actions = []; // 'nActiveActions' followed by inactive ones
  27175. this._nActiveActions = 0;
  27176. this._actionsByClip = {};
  27177. // inside:
  27178. // {
  27179. // knownActions: Array< AnimationAction > - used as prototypes
  27180. // actionByRoot: AnimationAction - lookup
  27181. // }
  27182. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27183. this._nActiveBindings = 0;
  27184. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27185. this._controlInterpolants = []; // same game as above
  27186. this._nActiveControlInterpolants = 0;
  27187. const scope = this;
  27188. this.stats = {
  27189. actions: {
  27190. get total() {
  27191. return scope._actions.length;
  27192. },
  27193. get inUse() {
  27194. return scope._nActiveActions;
  27195. }
  27196. },
  27197. bindings: {
  27198. get total() {
  27199. return scope._bindings.length;
  27200. },
  27201. get inUse() {
  27202. return scope._nActiveBindings;
  27203. }
  27204. },
  27205. controlInterpolants: {
  27206. get total() {
  27207. return scope._controlInterpolants.length;
  27208. },
  27209. get inUse() {
  27210. return scope._nActiveControlInterpolants;
  27211. }
  27212. }
  27213. };
  27214. },
  27215. // Memory management for AnimationAction objects
  27216. _isActiveAction: function ( action ) {
  27217. const index = action._cacheIndex;
  27218. return index !== null && index < this._nActiveActions;
  27219. },
  27220. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  27221. const actions = this._actions,
  27222. actionsByClip = this._actionsByClip;
  27223. let actionsForClip = actionsByClip[ clipUuid ];
  27224. if ( actionsForClip === undefined ) {
  27225. actionsForClip = {
  27226. knownActions: [ action ],
  27227. actionByRoot: {}
  27228. };
  27229. action._byClipCacheIndex = 0;
  27230. actionsByClip[ clipUuid ] = actionsForClip;
  27231. } else {
  27232. const knownActions = actionsForClip.knownActions;
  27233. action._byClipCacheIndex = knownActions.length;
  27234. knownActions.push( action );
  27235. }
  27236. action._cacheIndex = actions.length;
  27237. actions.push( action );
  27238. actionsForClip.actionByRoot[ rootUuid ] = action;
  27239. },
  27240. _removeInactiveAction: function ( action ) {
  27241. const actions = this._actions,
  27242. lastInactiveAction = actions[ actions.length - 1 ],
  27243. cacheIndex = action._cacheIndex;
  27244. lastInactiveAction._cacheIndex = cacheIndex;
  27245. actions[ cacheIndex ] = lastInactiveAction;
  27246. actions.pop();
  27247. action._cacheIndex = null;
  27248. const clipUuid = action._clip.uuid,
  27249. actionsByClip = this._actionsByClip,
  27250. actionsForClip = actionsByClip[ clipUuid ],
  27251. knownActionsForClip = actionsForClip.knownActions,
  27252. lastKnownAction =
  27253. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27254. byClipCacheIndex = action._byClipCacheIndex;
  27255. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27256. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27257. knownActionsForClip.pop();
  27258. action._byClipCacheIndex = null;
  27259. const actionByRoot = actionsForClip.actionByRoot,
  27260. rootUuid = ( action._localRoot || this._root ).uuid;
  27261. delete actionByRoot[ rootUuid ];
  27262. if ( knownActionsForClip.length === 0 ) {
  27263. delete actionsByClip[ clipUuid ];
  27264. }
  27265. this._removeInactiveBindingsForAction( action );
  27266. },
  27267. _removeInactiveBindingsForAction: function ( action ) {
  27268. const bindings = action._propertyBindings;
  27269. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27270. const binding = bindings[ i ];
  27271. if ( -- binding.referenceCount === 0 ) {
  27272. this._removeInactiveBinding( binding );
  27273. }
  27274. }
  27275. },
  27276. _lendAction: function ( action ) {
  27277. // [ active actions | inactive actions ]
  27278. // [ active actions >| inactive actions ]
  27279. // s a
  27280. // <-swap->
  27281. // a s
  27282. const actions = this._actions,
  27283. prevIndex = action._cacheIndex,
  27284. lastActiveIndex = this._nActiveActions ++,
  27285. firstInactiveAction = actions[ lastActiveIndex ];
  27286. action._cacheIndex = lastActiveIndex;
  27287. actions[ lastActiveIndex ] = action;
  27288. firstInactiveAction._cacheIndex = prevIndex;
  27289. actions[ prevIndex ] = firstInactiveAction;
  27290. },
  27291. _takeBackAction: function ( action ) {
  27292. // [ active actions | inactive actions ]
  27293. // [ active actions |< inactive actions ]
  27294. // a s
  27295. // <-swap->
  27296. // s a
  27297. const actions = this._actions,
  27298. prevIndex = action._cacheIndex,
  27299. firstInactiveIndex = -- this._nActiveActions,
  27300. lastActiveAction = actions[ firstInactiveIndex ];
  27301. action._cacheIndex = firstInactiveIndex;
  27302. actions[ firstInactiveIndex ] = action;
  27303. lastActiveAction._cacheIndex = prevIndex;
  27304. actions[ prevIndex ] = lastActiveAction;
  27305. },
  27306. // Memory management for PropertyMixer objects
  27307. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  27308. const bindingsByRoot = this._bindingsByRootAndName,
  27309. bindings = this._bindings;
  27310. let bindingByName = bindingsByRoot[ rootUuid ];
  27311. if ( bindingByName === undefined ) {
  27312. bindingByName = {};
  27313. bindingsByRoot[ rootUuid ] = bindingByName;
  27314. }
  27315. bindingByName[ trackName ] = binding;
  27316. binding._cacheIndex = bindings.length;
  27317. bindings.push( binding );
  27318. },
  27319. _removeInactiveBinding: function ( binding ) {
  27320. const bindings = this._bindings,
  27321. propBinding = binding.binding,
  27322. rootUuid = propBinding.rootNode.uuid,
  27323. trackName = propBinding.path,
  27324. bindingsByRoot = this._bindingsByRootAndName,
  27325. bindingByName = bindingsByRoot[ rootUuid ],
  27326. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27327. cacheIndex = binding._cacheIndex;
  27328. lastInactiveBinding._cacheIndex = cacheIndex;
  27329. bindings[ cacheIndex ] = lastInactiveBinding;
  27330. bindings.pop();
  27331. delete bindingByName[ trackName ];
  27332. if ( Object.keys( bindingByName ).length === 0 ) {
  27333. delete bindingsByRoot[ rootUuid ];
  27334. }
  27335. },
  27336. _lendBinding: function ( binding ) {
  27337. const bindings = this._bindings,
  27338. prevIndex = binding._cacheIndex,
  27339. lastActiveIndex = this._nActiveBindings ++,
  27340. firstInactiveBinding = bindings[ lastActiveIndex ];
  27341. binding._cacheIndex = lastActiveIndex;
  27342. bindings[ lastActiveIndex ] = binding;
  27343. firstInactiveBinding._cacheIndex = prevIndex;
  27344. bindings[ prevIndex ] = firstInactiveBinding;
  27345. },
  27346. _takeBackBinding: function ( binding ) {
  27347. const bindings = this._bindings,
  27348. prevIndex = binding._cacheIndex,
  27349. firstInactiveIndex = -- this._nActiveBindings,
  27350. lastActiveBinding = bindings[ firstInactiveIndex ];
  27351. binding._cacheIndex = firstInactiveIndex;
  27352. bindings[ firstInactiveIndex ] = binding;
  27353. lastActiveBinding._cacheIndex = prevIndex;
  27354. bindings[ prevIndex ] = lastActiveBinding;
  27355. },
  27356. // Memory management of Interpolants for weight and time scale
  27357. _lendControlInterpolant: function () {
  27358. const interpolants = this._controlInterpolants,
  27359. lastActiveIndex = this._nActiveControlInterpolants ++;
  27360. let interpolant = interpolants[ lastActiveIndex ];
  27361. if ( interpolant === undefined ) {
  27362. interpolant = new LinearInterpolant(
  27363. new Float32Array( 2 ), new Float32Array( 2 ),
  27364. 1, this._controlInterpolantsResultBuffer );
  27365. interpolant.__cacheIndex = lastActiveIndex;
  27366. interpolants[ lastActiveIndex ] = interpolant;
  27367. }
  27368. return interpolant;
  27369. },
  27370. _takeBackControlInterpolant: function ( interpolant ) {
  27371. const interpolants = this._controlInterpolants,
  27372. prevIndex = interpolant.__cacheIndex,
  27373. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27374. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27375. interpolant.__cacheIndex = firstInactiveIndex;
  27376. interpolants[ firstInactiveIndex ] = interpolant;
  27377. lastActiveInterpolant.__cacheIndex = prevIndex;
  27378. interpolants[ prevIndex ] = lastActiveInterpolant;
  27379. },
  27380. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  27381. // return an action for a clip optionally using a custom root target
  27382. // object (this method allocates a lot of dynamic memory in case a
  27383. // previously unknown clip/root combination is specified)
  27384. clipAction: function ( clip, optionalRoot, blendMode ) {
  27385. const root = optionalRoot || this._root,
  27386. rootUuid = root.uuid;
  27387. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27388. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27389. const actionsForClip = this._actionsByClip[ clipUuid ];
  27390. let prototypeAction = null;
  27391. if ( blendMode === undefined ) {
  27392. if ( clipObject !== null ) {
  27393. blendMode = clipObject.blendMode;
  27394. } else {
  27395. blendMode = NormalAnimationBlendMode;
  27396. }
  27397. }
  27398. if ( actionsForClip !== undefined ) {
  27399. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27400. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27401. return existingAction;
  27402. }
  27403. // we know the clip, so we don't have to parse all
  27404. // the bindings again but can just copy
  27405. prototypeAction = actionsForClip.knownActions[ 0 ];
  27406. // also, take the clip from the prototype action
  27407. if ( clipObject === null )
  27408. clipObject = prototypeAction._clip;
  27409. }
  27410. // clip must be known when specified via string
  27411. if ( clipObject === null ) return null;
  27412. // allocate all resources required to run it
  27413. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27414. this._bindAction( newAction, prototypeAction );
  27415. // and make the action known to the memory manager
  27416. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27417. return newAction;
  27418. },
  27419. // get an existing action
  27420. existingAction: function ( clip, optionalRoot ) {
  27421. const root = optionalRoot || this._root,
  27422. rootUuid = root.uuid,
  27423. clipObject = typeof clip === 'string' ?
  27424. AnimationClip.findByName( root, clip ) : clip,
  27425. clipUuid = clipObject ? clipObject.uuid : clip,
  27426. actionsForClip = this._actionsByClip[ clipUuid ];
  27427. if ( actionsForClip !== undefined ) {
  27428. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27429. }
  27430. return null;
  27431. },
  27432. // deactivates all previously scheduled actions
  27433. stopAllAction: function () {
  27434. const actions = this._actions,
  27435. nActions = this._nActiveActions;
  27436. for ( let i = nActions - 1; i >= 0; -- i ) {
  27437. actions[ i ].stop();
  27438. }
  27439. return this;
  27440. },
  27441. // advance the time and update apply the animation
  27442. update: function ( deltaTime ) {
  27443. deltaTime *= this.timeScale;
  27444. const actions = this._actions,
  27445. nActions = this._nActiveActions,
  27446. time = this.time += deltaTime,
  27447. timeDirection = Math.sign( deltaTime ),
  27448. accuIndex = this._accuIndex ^= 1;
  27449. // run active actions
  27450. for ( let i = 0; i !== nActions; ++ i ) {
  27451. const action = actions[ i ];
  27452. action._update( time, deltaTime, timeDirection, accuIndex );
  27453. }
  27454. // update scene graph
  27455. const bindings = this._bindings,
  27456. nBindings = this._nActiveBindings;
  27457. for ( let i = 0; i !== nBindings; ++ i ) {
  27458. bindings[ i ].apply( accuIndex );
  27459. }
  27460. return this;
  27461. },
  27462. // Allows you to seek to a specific time in an animation.
  27463. setTime: function ( timeInSeconds ) {
  27464. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27465. for ( let i = 0; i < this._actions.length; i ++ ) {
  27466. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27467. }
  27468. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27469. },
  27470. // return this mixer's root target object
  27471. getRoot: function () {
  27472. return this._root;
  27473. },
  27474. // free all resources specific to a particular clip
  27475. uncacheClip: function ( clip ) {
  27476. const actions = this._actions,
  27477. clipUuid = clip.uuid,
  27478. actionsByClip = this._actionsByClip,
  27479. actionsForClip = actionsByClip[ clipUuid ];
  27480. if ( actionsForClip !== undefined ) {
  27481. // note: just calling _removeInactiveAction would mess up the
  27482. // iteration state and also require updating the state we can
  27483. // just throw away
  27484. const actionsToRemove = actionsForClip.knownActions;
  27485. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27486. const action = actionsToRemove[ i ];
  27487. this._deactivateAction( action );
  27488. const cacheIndex = action._cacheIndex,
  27489. lastInactiveAction = actions[ actions.length - 1 ];
  27490. action._cacheIndex = null;
  27491. action._byClipCacheIndex = null;
  27492. lastInactiveAction._cacheIndex = cacheIndex;
  27493. actions[ cacheIndex ] = lastInactiveAction;
  27494. actions.pop();
  27495. this._removeInactiveBindingsForAction( action );
  27496. }
  27497. delete actionsByClip[ clipUuid ];
  27498. }
  27499. },
  27500. // free all resources specific to a particular root target object
  27501. uncacheRoot: function ( root ) {
  27502. const rootUuid = root.uuid,
  27503. actionsByClip = this._actionsByClip;
  27504. for ( const clipUuid in actionsByClip ) {
  27505. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27506. action = actionByRoot[ rootUuid ];
  27507. if ( action !== undefined ) {
  27508. this._deactivateAction( action );
  27509. this._removeInactiveAction( action );
  27510. }
  27511. }
  27512. const bindingsByRoot = this._bindingsByRootAndName,
  27513. bindingByName = bindingsByRoot[ rootUuid ];
  27514. if ( bindingByName !== undefined ) {
  27515. for ( const trackName in bindingByName ) {
  27516. const binding = bindingByName[ trackName ];
  27517. binding.restoreOriginalState();
  27518. this._removeInactiveBinding( binding );
  27519. }
  27520. }
  27521. },
  27522. // remove a targeted clip from the cache
  27523. uncacheAction: function ( clip, optionalRoot ) {
  27524. const action = this.existingAction( clip, optionalRoot );
  27525. if ( action !== null ) {
  27526. this._deactivateAction( action );
  27527. this._removeInactiveAction( action );
  27528. }
  27529. }
  27530. } );
  27531. class Uniform {
  27532. constructor( value ) {
  27533. if ( typeof value === 'string' ) {
  27534. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27535. value = arguments[ 1 ];
  27536. }
  27537. this.value = value;
  27538. }
  27539. clone() {
  27540. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27541. }
  27542. }
  27543. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  27544. InterleavedBuffer.call( this, array, stride );
  27545. this.meshPerAttribute = meshPerAttribute || 1;
  27546. }
  27547. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  27548. constructor: InstancedInterleavedBuffer,
  27549. isInstancedInterleavedBuffer: true,
  27550. copy: function ( source ) {
  27551. InterleavedBuffer.prototype.copy.call( this, source );
  27552. this.meshPerAttribute = source.meshPerAttribute;
  27553. return this;
  27554. },
  27555. clone: function ( data ) {
  27556. const ib = InterleavedBuffer.prototype.clone.call( this, data );
  27557. ib.meshPerAttribute = this.meshPerAttribute;
  27558. return ib;
  27559. },
  27560. toJSON: function ( data ) {
  27561. const json = InterleavedBuffer.prototype.toJSON.call( this, data );
  27562. json.isInstancedInterleavedBuffer = true;
  27563. json.meshPerAttribute = this.meshPerAttribute;
  27564. return json;
  27565. }
  27566. } );
  27567. function GLBufferAttribute( buffer, type, itemSize, elementSize, count ) {
  27568. this.buffer = buffer;
  27569. this.type = type;
  27570. this.itemSize = itemSize;
  27571. this.elementSize = elementSize;
  27572. this.count = count;
  27573. this.version = 0;
  27574. }
  27575. Object.defineProperty( GLBufferAttribute.prototype, 'needsUpdate', {
  27576. set: function ( value ) {
  27577. if ( value === true ) this.version ++;
  27578. }
  27579. } );
  27580. Object.assign( GLBufferAttribute.prototype, {
  27581. isGLBufferAttribute: true,
  27582. setBuffer: function ( buffer ) {
  27583. this.buffer = buffer;
  27584. return this;
  27585. },
  27586. setType: function ( type, elementSize ) {
  27587. this.type = type;
  27588. this.elementSize = elementSize;
  27589. return this;
  27590. },
  27591. setItemSize: function ( itemSize ) {
  27592. this.itemSize = itemSize;
  27593. return this;
  27594. },
  27595. setCount: function ( count ) {
  27596. this.count = count;
  27597. return this;
  27598. },
  27599. } );
  27600. function Raycaster( origin, direction, near, far ) {
  27601. this.ray = new Ray( origin, direction );
  27602. // direction is assumed to be normalized (for accurate distance calculations)
  27603. this.near = near || 0;
  27604. this.far = far || Infinity;
  27605. this.camera = null;
  27606. this.layers = new Layers();
  27607. this.params = {
  27608. Mesh: {},
  27609. Line: { threshold: 1 },
  27610. LOD: {},
  27611. Points: { threshold: 1 },
  27612. Sprite: {}
  27613. };
  27614. Object.defineProperties( this.params, {
  27615. PointCloud: {
  27616. get: function () {
  27617. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  27618. return this.Points;
  27619. }
  27620. }
  27621. } );
  27622. }
  27623. function ascSort( a, b ) {
  27624. return a.distance - b.distance;
  27625. }
  27626. function intersectObject( object, raycaster, intersects, recursive ) {
  27627. if ( object.layers.test( raycaster.layers ) ) {
  27628. object.raycast( raycaster, intersects );
  27629. }
  27630. if ( recursive === true ) {
  27631. const children = object.children;
  27632. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27633. intersectObject( children[ i ], raycaster, intersects, true );
  27634. }
  27635. }
  27636. }
  27637. Object.assign( Raycaster.prototype, {
  27638. set: function ( origin, direction ) {
  27639. // direction is assumed to be normalized (for accurate distance calculations)
  27640. this.ray.set( origin, direction );
  27641. },
  27642. setFromCamera: function ( coords, camera ) {
  27643. if ( camera && camera.isPerspectiveCamera ) {
  27644. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27645. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27646. this.camera = camera;
  27647. } else if ( camera && camera.isOrthographicCamera ) {
  27648. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27649. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27650. this.camera = camera;
  27651. } else {
  27652. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27653. }
  27654. },
  27655. intersectObject: function ( object, recursive, optionalTarget ) {
  27656. const intersects = optionalTarget || [];
  27657. intersectObject( object, this, intersects, recursive );
  27658. intersects.sort( ascSort );
  27659. return intersects;
  27660. },
  27661. intersectObjects: function ( objects, recursive, optionalTarget ) {
  27662. const intersects = optionalTarget || [];
  27663. if ( Array.isArray( objects ) === false ) {
  27664. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  27665. return intersects;
  27666. }
  27667. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27668. intersectObject( objects[ i ], this, intersects, recursive );
  27669. }
  27670. intersects.sort( ascSort );
  27671. return intersects;
  27672. }
  27673. } );
  27674. /**
  27675. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27676. *
  27677. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27678. * The azimuthal angle (theta) is measured from the positive z-axis.
  27679. */
  27680. class Spherical {
  27681. constructor( radius = 1, phi = 0, theta = 0 ) {
  27682. this.radius = radius;
  27683. this.phi = phi; // polar angle
  27684. this.theta = theta; // azimuthal angle
  27685. return this;
  27686. }
  27687. set( radius, phi, theta ) {
  27688. this.radius = radius;
  27689. this.phi = phi;
  27690. this.theta = theta;
  27691. return this;
  27692. }
  27693. clone() {
  27694. return new this.constructor().copy( this );
  27695. }
  27696. copy( other ) {
  27697. this.radius = other.radius;
  27698. this.phi = other.phi;
  27699. this.theta = other.theta;
  27700. return this;
  27701. }
  27702. // restrict phi to be betwee EPS and PI-EPS
  27703. makeSafe() {
  27704. const EPS = 0.000001;
  27705. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27706. return this;
  27707. }
  27708. setFromVector3( v ) {
  27709. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27710. }
  27711. setFromCartesianCoords( x, y, z ) {
  27712. this.radius = Math.sqrt( x * x + y * y + z * z );
  27713. if ( this.radius === 0 ) {
  27714. this.theta = 0;
  27715. this.phi = 0;
  27716. } else {
  27717. this.theta = Math.atan2( x, z );
  27718. this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
  27719. }
  27720. return this;
  27721. }
  27722. }
  27723. /**
  27724. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27725. */
  27726. class Cylindrical {
  27727. constructor( radius, theta, y ) {
  27728. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27729. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27730. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  27731. return this;
  27732. }
  27733. set( radius, theta, y ) {
  27734. this.radius = radius;
  27735. this.theta = theta;
  27736. this.y = y;
  27737. return this;
  27738. }
  27739. clone() {
  27740. return new this.constructor().copy( this );
  27741. }
  27742. copy( other ) {
  27743. this.radius = other.radius;
  27744. this.theta = other.theta;
  27745. this.y = other.y;
  27746. return this;
  27747. }
  27748. setFromVector3( v ) {
  27749. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27750. }
  27751. setFromCartesianCoords( x, y, z ) {
  27752. this.radius = Math.sqrt( x * x + z * z );
  27753. this.theta = Math.atan2( x, z );
  27754. this.y = y;
  27755. return this;
  27756. }
  27757. }
  27758. const _vector$8 = /*@__PURE__*/ new Vector2();
  27759. class Box2 {
  27760. constructor( min, max ) {
  27761. Object.defineProperty( this, 'isBox2', { value: true } );
  27762. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  27763. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  27764. }
  27765. set( min, max ) {
  27766. this.min.copy( min );
  27767. this.max.copy( max );
  27768. return this;
  27769. }
  27770. setFromPoints( points ) {
  27771. this.makeEmpty();
  27772. for ( let i = 0, il = points.length; i < il; i ++ ) {
  27773. this.expandByPoint( points[ i ] );
  27774. }
  27775. return this;
  27776. }
  27777. setFromCenterAndSize( center, size ) {
  27778. const halfSize = _vector$8.copy( size ).multiplyScalar( 0.5 );
  27779. this.min.copy( center ).sub( halfSize );
  27780. this.max.copy( center ).add( halfSize );
  27781. return this;
  27782. }
  27783. clone() {
  27784. return new this.constructor().copy( this );
  27785. }
  27786. copy( box ) {
  27787. this.min.copy( box.min );
  27788. this.max.copy( box.max );
  27789. return this;
  27790. }
  27791. makeEmpty() {
  27792. this.min.x = this.min.y = + Infinity;
  27793. this.max.x = this.max.y = - Infinity;
  27794. return this;
  27795. }
  27796. isEmpty() {
  27797. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27798. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  27799. }
  27800. getCenter( target ) {
  27801. if ( target === undefined ) {
  27802. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  27803. target = new Vector2();
  27804. }
  27805. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  27806. }
  27807. getSize( target ) {
  27808. if ( target === undefined ) {
  27809. console.warn( 'THREE.Box2: .getSize() target is now required' );
  27810. target = new Vector2();
  27811. }
  27812. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  27813. }
  27814. expandByPoint( point ) {
  27815. this.min.min( point );
  27816. this.max.max( point );
  27817. return this;
  27818. }
  27819. expandByVector( vector ) {
  27820. this.min.sub( vector );
  27821. this.max.add( vector );
  27822. return this;
  27823. }
  27824. expandByScalar( scalar ) {
  27825. this.min.addScalar( - scalar );
  27826. this.max.addScalar( scalar );
  27827. return this;
  27828. }
  27829. containsPoint( point ) {
  27830. return point.x < this.min.x || point.x > this.max.x ||
  27831. point.y < this.min.y || point.y > this.max.y ? false : true;
  27832. }
  27833. containsBox( box ) {
  27834. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  27835. this.min.y <= box.min.y && box.max.y <= this.max.y;
  27836. }
  27837. getParameter( point, target ) {
  27838. // This can potentially have a divide by zero if the box
  27839. // has a size dimension of 0.
  27840. if ( target === undefined ) {
  27841. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  27842. target = new Vector2();
  27843. }
  27844. return target.set(
  27845. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  27846. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  27847. );
  27848. }
  27849. intersectsBox( box ) {
  27850. // using 4 splitting planes to rule out intersections
  27851. return box.max.x < this.min.x || box.min.x > this.max.x ||
  27852. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27853. }
  27854. clampPoint( point, target ) {
  27855. if ( target === undefined ) {
  27856. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  27857. target = new Vector2();
  27858. }
  27859. return target.copy( point ).clamp( this.min, this.max );
  27860. }
  27861. distanceToPoint( point ) {
  27862. const clampedPoint = _vector$8.copy( point ).clamp( this.min, this.max );
  27863. return clampedPoint.sub( point ).length();
  27864. }
  27865. intersect( box ) {
  27866. this.min.max( box.min );
  27867. this.max.min( box.max );
  27868. return this;
  27869. }
  27870. union( box ) {
  27871. this.min.min( box.min );
  27872. this.max.max( box.max );
  27873. return this;
  27874. }
  27875. translate( offset ) {
  27876. this.min.add( offset );
  27877. this.max.add( offset );
  27878. return this;
  27879. }
  27880. equals( box ) {
  27881. return box.min.equals( this.min ) && box.max.equals( this.max );
  27882. }
  27883. }
  27884. const _startP = /*@__PURE__*/ new Vector3();
  27885. const _startEnd = /*@__PURE__*/ new Vector3();
  27886. class Line3 {
  27887. constructor( start, end ) {
  27888. this.start = ( start !== undefined ) ? start : new Vector3();
  27889. this.end = ( end !== undefined ) ? end : new Vector3();
  27890. }
  27891. set( start, end ) {
  27892. this.start.copy( start );
  27893. this.end.copy( end );
  27894. return this;
  27895. }
  27896. clone() {
  27897. return new this.constructor().copy( this );
  27898. }
  27899. copy( line ) {
  27900. this.start.copy( line.start );
  27901. this.end.copy( line.end );
  27902. return this;
  27903. }
  27904. getCenter( target ) {
  27905. if ( target === undefined ) {
  27906. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  27907. target = new Vector3();
  27908. }
  27909. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  27910. }
  27911. delta( target ) {
  27912. if ( target === undefined ) {
  27913. console.warn( 'THREE.Line3: .delta() target is now required' );
  27914. target = new Vector3();
  27915. }
  27916. return target.subVectors( this.end, this.start );
  27917. }
  27918. distanceSq() {
  27919. return this.start.distanceToSquared( this.end );
  27920. }
  27921. distance() {
  27922. return this.start.distanceTo( this.end );
  27923. }
  27924. at( t, target ) {
  27925. if ( target === undefined ) {
  27926. console.warn( 'THREE.Line3: .at() target is now required' );
  27927. target = new Vector3();
  27928. }
  27929. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27930. }
  27931. closestPointToPointParameter( point, clampToLine ) {
  27932. _startP.subVectors( point, this.start );
  27933. _startEnd.subVectors( this.end, this.start );
  27934. const startEnd2 = _startEnd.dot( _startEnd );
  27935. const startEnd_startP = _startEnd.dot( _startP );
  27936. let t = startEnd_startP / startEnd2;
  27937. if ( clampToLine ) {
  27938. t = MathUtils.clamp( t, 0, 1 );
  27939. }
  27940. return t;
  27941. }
  27942. closestPointToPoint( point, clampToLine, target ) {
  27943. const t = this.closestPointToPointParameter( point, clampToLine );
  27944. if ( target === undefined ) {
  27945. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  27946. target = new Vector3();
  27947. }
  27948. return this.delta( target ).multiplyScalar( t ).add( this.start );
  27949. }
  27950. applyMatrix4( matrix ) {
  27951. this.start.applyMatrix4( matrix );
  27952. this.end.applyMatrix4( matrix );
  27953. return this;
  27954. }
  27955. equals( line ) {
  27956. return line.start.equals( this.start ) && line.end.equals( this.end );
  27957. }
  27958. }
  27959. function ImmediateRenderObject( material ) {
  27960. Object3D.call( this );
  27961. this.material = material;
  27962. this.render = function ( /* renderCallback */ ) {};
  27963. this.hasPositions = false;
  27964. this.hasNormals = false;
  27965. this.hasColors = false;
  27966. this.hasUvs = false;
  27967. this.positionArray = null;
  27968. this.normalArray = null;
  27969. this.colorArray = null;
  27970. this.uvArray = null;
  27971. this.count = 0;
  27972. }
  27973. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  27974. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  27975. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27976. const _vector$9 = /*@__PURE__*/ new Vector3();
  27977. class SpotLightHelper extends Object3D {
  27978. constructor( light, color ) {
  27979. super();
  27980. this.light = light;
  27981. this.light.updateMatrixWorld();
  27982. this.matrix = light.matrixWorld;
  27983. this.matrixAutoUpdate = false;
  27984. this.color = color;
  27985. const geometry = new BufferGeometry();
  27986. const positions = [
  27987. 0, 0, 0, 0, 0, 1,
  27988. 0, 0, 0, 1, 0, 1,
  27989. 0, 0, 0, - 1, 0, 1,
  27990. 0, 0, 0, 0, 1, 1,
  27991. 0, 0, 0, 0, - 1, 1
  27992. ];
  27993. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  27994. const p1 = ( i / l ) * Math.PI * 2;
  27995. const p2 = ( j / l ) * Math.PI * 2;
  27996. positions.push(
  27997. Math.cos( p1 ), Math.sin( p1 ), 1,
  27998. Math.cos( p2 ), Math.sin( p2 ), 1
  27999. );
  28000. }
  28001. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28002. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28003. this.cone = new LineSegments( geometry, material );
  28004. this.add( this.cone );
  28005. this.update();
  28006. }
  28007. dispose() {
  28008. this.cone.geometry.dispose();
  28009. this.cone.material.dispose();
  28010. }
  28011. update() {
  28012. this.light.updateMatrixWorld();
  28013. const coneLength = this.light.distance ? this.light.distance : 1000;
  28014. const coneWidth = coneLength * Math.tan( this.light.angle );
  28015. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28016. _vector$9.setFromMatrixPosition( this.light.target.matrixWorld );
  28017. this.cone.lookAt( _vector$9 );
  28018. if ( this.color !== undefined ) {
  28019. this.cone.material.color.set( this.color );
  28020. } else {
  28021. this.cone.material.color.copy( this.light.color );
  28022. }
  28023. }
  28024. }
  28025. const _vector$a = /*@__PURE__*/ new Vector3();
  28026. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28027. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28028. class SkeletonHelper extends LineSegments {
  28029. constructor( object ) {
  28030. const bones = getBoneList( object );
  28031. const geometry = new BufferGeometry();
  28032. const vertices = [];
  28033. const colors = [];
  28034. const color1 = new Color( 0, 0, 1 );
  28035. const color2 = new Color( 0, 1, 0 );
  28036. for ( let i = 0; i < bones.length; i ++ ) {
  28037. const bone = bones[ i ];
  28038. if ( bone.parent && bone.parent.isBone ) {
  28039. vertices.push( 0, 0, 0 );
  28040. vertices.push( 0, 0, 0 );
  28041. colors.push( color1.r, color1.g, color1.b );
  28042. colors.push( color2.r, color2.g, color2.b );
  28043. }
  28044. }
  28045. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28046. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28047. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28048. super( geometry, material );
  28049. this.type = 'SkeletonHelper';
  28050. this.isSkeletonHelper = true;
  28051. this.root = object;
  28052. this.bones = bones;
  28053. this.matrix = object.matrixWorld;
  28054. this.matrixAutoUpdate = false;
  28055. }
  28056. updateMatrixWorld( force ) {
  28057. const bones = this.bones;
  28058. const geometry = this.geometry;
  28059. const position = geometry.getAttribute( 'position' );
  28060. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28061. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28062. const bone = bones[ i ];
  28063. if ( bone.parent && bone.parent.isBone ) {
  28064. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28065. _vector$a.setFromMatrixPosition( _boneMatrix );
  28066. position.setXYZ( j, _vector$a.x, _vector$a.y, _vector$a.z );
  28067. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28068. _vector$a.setFromMatrixPosition( _boneMatrix );
  28069. position.setXYZ( j + 1, _vector$a.x, _vector$a.y, _vector$a.z );
  28070. j += 2;
  28071. }
  28072. }
  28073. geometry.getAttribute( 'position' ).needsUpdate = true;
  28074. super.updateMatrixWorld( force );
  28075. }
  28076. }
  28077. function getBoneList( object ) {
  28078. const boneList = [];
  28079. if ( object && object.isBone ) {
  28080. boneList.push( object );
  28081. }
  28082. for ( let i = 0; i < object.children.length; i ++ ) {
  28083. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28084. }
  28085. return boneList;
  28086. }
  28087. class PointLightHelper extends Mesh {
  28088. constructor( light, sphereSize, color ) {
  28089. const geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  28090. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28091. super( geometry, material );
  28092. this.light = light;
  28093. this.light.updateMatrixWorld();
  28094. this.color = color;
  28095. this.type = 'PointLightHelper';
  28096. this.matrix = this.light.matrixWorld;
  28097. this.matrixAutoUpdate = false;
  28098. this.update();
  28099. /*
  28100. // TODO: delete this comment?
  28101. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28102. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28103. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28104. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28105. const d = light.distance;
  28106. if ( d === 0.0 ) {
  28107. this.lightDistance.visible = false;
  28108. } else {
  28109. this.lightDistance.scale.set( d, d, d );
  28110. }
  28111. this.add( this.lightDistance );
  28112. */
  28113. }
  28114. dispose() {
  28115. this.geometry.dispose();
  28116. this.material.dispose();
  28117. }
  28118. update() {
  28119. if ( this.color !== undefined ) {
  28120. this.material.color.set( this.color );
  28121. } else {
  28122. this.material.color.copy( this.light.color );
  28123. }
  28124. /*
  28125. const d = this.light.distance;
  28126. if ( d === 0.0 ) {
  28127. this.lightDistance.visible = false;
  28128. } else {
  28129. this.lightDistance.visible = true;
  28130. this.lightDistance.scale.set( d, d, d );
  28131. }
  28132. */
  28133. }
  28134. }
  28135. const _vector$b = /*@__PURE__*/ new Vector3();
  28136. const _color1 = /*@__PURE__*/ new Color();
  28137. const _color2 = /*@__PURE__*/ new Color();
  28138. class HemisphereLightHelper extends Object3D {
  28139. constructor( light, size, color ) {
  28140. super();
  28141. this.light = light;
  28142. this.light.updateMatrixWorld();
  28143. this.matrix = light.matrixWorld;
  28144. this.matrixAutoUpdate = false;
  28145. this.color = color;
  28146. const geometry = new OctahedronBufferGeometry( size );
  28147. geometry.rotateY( Math.PI * 0.5 );
  28148. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28149. if ( this.color === undefined ) this.material.vertexColors = true;
  28150. const position = geometry.getAttribute( 'position' );
  28151. const colors = new Float32Array( position.count * 3 );
  28152. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28153. this.add( new Mesh( geometry, this.material ) );
  28154. this.update();
  28155. }
  28156. dispose() {
  28157. this.children[ 0 ].geometry.dispose();
  28158. this.children[ 0 ].material.dispose();
  28159. }
  28160. update() {
  28161. const mesh = this.children[ 0 ];
  28162. if ( this.color !== undefined ) {
  28163. this.material.color.set( this.color );
  28164. } else {
  28165. const colors = mesh.geometry.getAttribute( 'color' );
  28166. _color1.copy( this.light.color );
  28167. _color2.copy( this.light.groundColor );
  28168. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28169. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28170. colors.setXYZ( i, color.r, color.g, color.b );
  28171. }
  28172. colors.needsUpdate = true;
  28173. }
  28174. mesh.lookAt( _vector$b.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28175. }
  28176. }
  28177. class GridHelper extends LineSegments {
  28178. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28179. color1 = new Color( color1 );
  28180. color2 = new Color( color2 );
  28181. const center = divisions / 2;
  28182. const step = size / divisions;
  28183. const halfSize = size / 2;
  28184. const vertices = [], colors = [];
  28185. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28186. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28187. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28188. const color = i === center ? color1 : color2;
  28189. color.toArray( colors, j ); j += 3;
  28190. color.toArray( colors, j ); j += 3;
  28191. color.toArray( colors, j ); j += 3;
  28192. color.toArray( colors, j ); j += 3;
  28193. }
  28194. const geometry = new BufferGeometry();
  28195. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28196. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28197. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28198. super( geometry, material );
  28199. this.type = 'GridHelper';
  28200. }
  28201. }
  28202. class PolarGridHelper extends LineSegments {
  28203. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28204. color1 = new Color( color1 );
  28205. color2 = new Color( color2 );
  28206. const vertices = [];
  28207. const colors = [];
  28208. // create the radials
  28209. for ( let i = 0; i <= radials; i ++ ) {
  28210. const v = ( i / radials ) * ( Math.PI * 2 );
  28211. const x = Math.sin( v ) * radius;
  28212. const z = Math.cos( v ) * radius;
  28213. vertices.push( 0, 0, 0 );
  28214. vertices.push( x, 0, z );
  28215. const color = ( i & 1 ) ? color1 : color2;
  28216. colors.push( color.r, color.g, color.b );
  28217. colors.push( color.r, color.g, color.b );
  28218. }
  28219. // create the circles
  28220. for ( let i = 0; i <= circles; i ++ ) {
  28221. const color = ( i & 1 ) ? color1 : color2;
  28222. const r = radius - ( radius / circles * i );
  28223. for ( let j = 0; j < divisions; j ++ ) {
  28224. // first vertex
  28225. let v = ( j / divisions ) * ( Math.PI * 2 );
  28226. let x = Math.sin( v ) * r;
  28227. let z = Math.cos( v ) * r;
  28228. vertices.push( x, 0, z );
  28229. colors.push( color.r, color.g, color.b );
  28230. // second vertex
  28231. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28232. x = Math.sin( v ) * r;
  28233. z = Math.cos( v ) * r;
  28234. vertices.push( x, 0, z );
  28235. colors.push( color.r, color.g, color.b );
  28236. }
  28237. }
  28238. const geometry = new BufferGeometry();
  28239. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28240. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28241. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28242. super( geometry, material );
  28243. this.type = 'PolarGridHelper';
  28244. }
  28245. }
  28246. const _v1$6 = /*@__PURE__*/ new Vector3();
  28247. const _v2$3 = /*@__PURE__*/ new Vector3();
  28248. const _v3$1 = /*@__PURE__*/ new Vector3();
  28249. class DirectionalLightHelper extends Object3D {
  28250. constructor( light, size, color ) {
  28251. super();
  28252. this.light = light;
  28253. this.light.updateMatrixWorld();
  28254. this.matrix = light.matrixWorld;
  28255. this.matrixAutoUpdate = false;
  28256. this.color = color;
  28257. if ( size === undefined ) size = 1;
  28258. let geometry = new BufferGeometry();
  28259. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28260. - size, size, 0,
  28261. size, size, 0,
  28262. size, - size, 0,
  28263. - size, - size, 0,
  28264. - size, size, 0
  28265. ], 3 ) );
  28266. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28267. this.lightPlane = new Line( geometry, material );
  28268. this.add( this.lightPlane );
  28269. geometry = new BufferGeometry();
  28270. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28271. this.targetLine = new Line( geometry, material );
  28272. this.add( this.targetLine );
  28273. this.update();
  28274. }
  28275. dispose() {
  28276. this.lightPlane.geometry.dispose();
  28277. this.lightPlane.material.dispose();
  28278. this.targetLine.geometry.dispose();
  28279. this.targetLine.material.dispose();
  28280. }
  28281. update() {
  28282. _v1$6.setFromMatrixPosition( this.light.matrixWorld );
  28283. _v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28284. _v3$1.subVectors( _v2$3, _v1$6 );
  28285. this.lightPlane.lookAt( _v2$3 );
  28286. if ( this.color !== undefined ) {
  28287. this.lightPlane.material.color.set( this.color );
  28288. this.targetLine.material.color.set( this.color );
  28289. } else {
  28290. this.lightPlane.material.color.copy( this.light.color );
  28291. this.targetLine.material.color.copy( this.light.color );
  28292. }
  28293. this.targetLine.lookAt( _v2$3 );
  28294. this.targetLine.scale.z = _v3$1.length();
  28295. }
  28296. }
  28297. const _vector$c = /*@__PURE__*/ new Vector3();
  28298. const _camera = /*@__PURE__*/ new Camera();
  28299. /**
  28300. * - shows frustum, line of sight and up of the camera
  28301. * - suitable for fast updates
  28302. * - based on frustum visualization in lightgl.js shadowmap example
  28303. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28304. */
  28305. class CameraHelper extends LineSegments {
  28306. constructor( camera ) {
  28307. const geometry = new BufferGeometry();
  28308. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28309. const vertices = [];
  28310. const colors = [];
  28311. const pointMap = {};
  28312. // colors
  28313. const colorFrustum = new Color( 0xffaa00 );
  28314. const colorCone = new Color( 0xff0000 );
  28315. const colorUp = new Color( 0x00aaff );
  28316. const colorTarget = new Color( 0xffffff );
  28317. const colorCross = new Color( 0x333333 );
  28318. // near
  28319. addLine( 'n1', 'n2', colorFrustum );
  28320. addLine( 'n2', 'n4', colorFrustum );
  28321. addLine( 'n4', 'n3', colorFrustum );
  28322. addLine( 'n3', 'n1', colorFrustum );
  28323. // far
  28324. addLine( 'f1', 'f2', colorFrustum );
  28325. addLine( 'f2', 'f4', colorFrustum );
  28326. addLine( 'f4', 'f3', colorFrustum );
  28327. addLine( 'f3', 'f1', colorFrustum );
  28328. // sides
  28329. addLine( 'n1', 'f1', colorFrustum );
  28330. addLine( 'n2', 'f2', colorFrustum );
  28331. addLine( 'n3', 'f3', colorFrustum );
  28332. addLine( 'n4', 'f4', colorFrustum );
  28333. // cone
  28334. addLine( 'p', 'n1', colorCone );
  28335. addLine( 'p', 'n2', colorCone );
  28336. addLine( 'p', 'n3', colorCone );
  28337. addLine( 'p', 'n4', colorCone );
  28338. // up
  28339. addLine( 'u1', 'u2', colorUp );
  28340. addLine( 'u2', 'u3', colorUp );
  28341. addLine( 'u3', 'u1', colorUp );
  28342. // target
  28343. addLine( 'c', 't', colorTarget );
  28344. addLine( 'p', 'c', colorCross );
  28345. // cross
  28346. addLine( 'cn1', 'cn2', colorCross );
  28347. addLine( 'cn3', 'cn4', colorCross );
  28348. addLine( 'cf1', 'cf2', colorCross );
  28349. addLine( 'cf3', 'cf4', colorCross );
  28350. function addLine( a, b, color ) {
  28351. addPoint( a, color );
  28352. addPoint( b, color );
  28353. }
  28354. function addPoint( id, color ) {
  28355. vertices.push( 0, 0, 0 );
  28356. colors.push( color.r, color.g, color.b );
  28357. if ( pointMap[ id ] === undefined ) {
  28358. pointMap[ id ] = [];
  28359. }
  28360. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28361. }
  28362. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28363. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28364. super( geometry, material );
  28365. this.type = 'CameraHelper';
  28366. this.camera = camera;
  28367. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28368. this.matrix = camera.matrixWorld;
  28369. this.matrixAutoUpdate = false;
  28370. this.pointMap = pointMap;
  28371. this.update();
  28372. }
  28373. update() {
  28374. const geometry = this.geometry;
  28375. const pointMap = this.pointMap;
  28376. const w = 1, h = 1;
  28377. // we need just camera projection matrix inverse
  28378. // world matrix must be identity
  28379. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28380. // center / target
  28381. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28382. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28383. // near
  28384. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28385. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28386. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28387. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28388. // far
  28389. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28390. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28391. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28392. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28393. // up
  28394. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28395. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28396. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28397. // cross
  28398. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28399. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28400. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28401. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28402. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28403. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28404. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28405. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28406. geometry.getAttribute( 'position' ).needsUpdate = true;
  28407. }
  28408. }
  28409. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28410. _vector$c.set( x, y, z ).unproject( camera );
  28411. const points = pointMap[ point ];
  28412. if ( points !== undefined ) {
  28413. const position = geometry.getAttribute( 'position' );
  28414. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28415. position.setXYZ( points[ i ], _vector$c.x, _vector$c.y, _vector$c.z );
  28416. }
  28417. }
  28418. }
  28419. const _box$3 = /*@__PURE__*/ new Box3();
  28420. class BoxHelper extends LineSegments {
  28421. constructor( object, color = 0xffff00 ) {
  28422. const 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 ] );
  28423. const positions = new Float32Array( 8 * 3 );
  28424. const geometry = new BufferGeometry();
  28425. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28426. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28427. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28428. this.object = object;
  28429. this.type = 'BoxHelper';
  28430. this.matrixAutoUpdate = false;
  28431. this.update();
  28432. }
  28433. update( object ) {
  28434. if ( object !== undefined ) {
  28435. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28436. }
  28437. if ( this.object !== undefined ) {
  28438. _box$3.setFromObject( this.object );
  28439. }
  28440. if ( _box$3.isEmpty() ) return;
  28441. const min = _box$3.min;
  28442. const max = _box$3.max;
  28443. /*
  28444. 5____4
  28445. 1/___0/|
  28446. | 6__|_7
  28447. 2/___3/
  28448. 0: max.x, max.y, max.z
  28449. 1: min.x, max.y, max.z
  28450. 2: min.x, min.y, max.z
  28451. 3: max.x, min.y, max.z
  28452. 4: max.x, max.y, min.z
  28453. 5: min.x, max.y, min.z
  28454. 6: min.x, min.y, min.z
  28455. 7: max.x, min.y, min.z
  28456. */
  28457. const position = this.geometry.attributes.position;
  28458. const array = position.array;
  28459. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28460. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28461. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28462. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28463. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28464. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28465. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28466. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28467. position.needsUpdate = true;
  28468. this.geometry.computeBoundingSphere();
  28469. }
  28470. setFromObject( object ) {
  28471. this.object = object;
  28472. this.update();
  28473. return this;
  28474. }
  28475. copy( source ) {
  28476. LineSegments.prototype.copy.call( this, source );
  28477. this.object = source.object;
  28478. return this;
  28479. }
  28480. }
  28481. class Box3Helper extends LineSegments {
  28482. constructor( box, color = 0xffff00 ) {
  28483. const 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 ] );
  28484. const 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 ];
  28485. const geometry = new BufferGeometry();
  28486. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28487. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28488. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28489. this.box = box;
  28490. this.type = 'Box3Helper';
  28491. this.geometry.computeBoundingSphere();
  28492. }
  28493. updateMatrixWorld( force ) {
  28494. const box = this.box;
  28495. if ( box.isEmpty() ) return;
  28496. box.getCenter( this.position );
  28497. box.getSize( this.scale );
  28498. this.scale.multiplyScalar( 0.5 );
  28499. super.updateMatrixWorld( force );
  28500. }
  28501. }
  28502. class PlaneHelper extends Line {
  28503. constructor( plane, size = 1, hex = 0xffff00 ) {
  28504. const color = hex;
  28505. const 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 ];
  28506. const geometry = new BufferGeometry();
  28507. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28508. geometry.computeBoundingSphere();
  28509. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28510. this.type = 'PlaneHelper';
  28511. this.plane = plane;
  28512. this.size = size;
  28513. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  28514. const geometry2 = new BufferGeometry();
  28515. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28516. geometry2.computeBoundingSphere();
  28517. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28518. }
  28519. updateMatrixWorld( force ) {
  28520. let scale = - this.plane.constant;
  28521. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  28522. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  28523. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28524. this.lookAt( this.plane.normal );
  28525. super.updateMatrixWorld( force );
  28526. }
  28527. }
  28528. const _axis = /*@__PURE__*/ new Vector3();
  28529. let _lineGeometry, _coneGeometry;
  28530. class ArrowHelper extends Object3D {
  28531. constructor( dir, origin, length, color, headLength, headWidth ) {
  28532. super();
  28533. // dir is assumed to be normalized
  28534. this.type = 'ArrowHelper';
  28535. if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
  28536. if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
  28537. if ( length === undefined ) length = 1;
  28538. if ( color === undefined ) color = 0xffff00;
  28539. if ( headLength === undefined ) headLength = 0.2 * length;
  28540. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  28541. if ( _lineGeometry === undefined ) {
  28542. _lineGeometry = new BufferGeometry();
  28543. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28544. _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  28545. _coneGeometry.translate( 0, - 0.5, 0 );
  28546. }
  28547. this.position.copy( origin );
  28548. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28549. this.line.matrixAutoUpdate = false;
  28550. this.add( this.line );
  28551. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28552. this.cone.matrixAutoUpdate = false;
  28553. this.add( this.cone );
  28554. this.setDirection( dir );
  28555. this.setLength( length, headLength, headWidth );
  28556. }
  28557. setDirection( dir ) {
  28558. // dir is assumed to be normalized
  28559. if ( dir.y > 0.99999 ) {
  28560. this.quaternion.set( 0, 0, 0, 1 );
  28561. } else if ( dir.y < - 0.99999 ) {
  28562. this.quaternion.set( 1, 0, 0, 0 );
  28563. } else {
  28564. _axis.set( dir.z, 0, - dir.x ).normalize();
  28565. const radians = Math.acos( dir.y );
  28566. this.quaternion.setFromAxisAngle( _axis, radians );
  28567. }
  28568. }
  28569. setLength( length, headLength, headWidth ) {
  28570. if ( headLength === undefined ) headLength = 0.2 * length;
  28571. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  28572. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28573. this.line.updateMatrix();
  28574. this.cone.scale.set( headWidth, headLength, headWidth );
  28575. this.cone.position.y = length;
  28576. this.cone.updateMatrix();
  28577. }
  28578. setColor( color ) {
  28579. this.line.material.color.set( color );
  28580. this.cone.material.color.set( color );
  28581. }
  28582. copy( source ) {
  28583. super.copy( source, false );
  28584. this.line.copy( source.line );
  28585. this.cone.copy( source.cone );
  28586. return this;
  28587. }
  28588. }
  28589. class AxesHelper extends LineSegments {
  28590. constructor( size = 1 ) {
  28591. const vertices = [
  28592. 0, 0, 0, size, 0, 0,
  28593. 0, 0, 0, 0, size, 0,
  28594. 0, 0, 0, 0, 0, size
  28595. ];
  28596. const colors = [
  28597. 1, 0, 0, 1, 0.6, 0,
  28598. 0, 1, 0, 0.6, 1, 0,
  28599. 0, 0, 1, 0, 0.6, 1
  28600. ];
  28601. const geometry = new BufferGeometry();
  28602. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28603. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28604. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28605. super( geometry, material );
  28606. this.type = 'AxesHelper';
  28607. }
  28608. }
  28609. const _floatView = new Float32Array( 1 );
  28610. const _int32View = new Int32Array( _floatView.buffer );
  28611. const DataUtils = {
  28612. // Converts float32 to float16 (stored as uint16 value).
  28613. toHalfFloat: function ( val ) {
  28614. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28615. /* This method is faster than the OpenEXR implementation (very often
  28616. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28617. * by James Tursa?s half-precision code. */
  28618. _floatView[ 0 ] = val;
  28619. const x = _int32View[ 0 ];
  28620. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  28621. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  28622. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  28623. /* If zero, or denormal, or exponent underflows too much for a denormal
  28624. * half, return signed zero. */
  28625. if ( e < 103 ) return bits;
  28626. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28627. if ( e > 142 ) {
  28628. bits |= 0x7c00;
  28629. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28630. * not Inf, so make sure we set one mantissa bit too. */
  28631. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  28632. return bits;
  28633. }
  28634. /* If exponent underflows but not too much, return a denormal */
  28635. if ( e < 113 ) {
  28636. m |= 0x0800;
  28637. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28638. * to 1, which is OK. */
  28639. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  28640. return bits;
  28641. }
  28642. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  28643. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28644. * the exponent, which is OK. */
  28645. bits += m & 1;
  28646. return bits;
  28647. }
  28648. };
  28649. const LOD_MIN = 4;
  28650. const LOD_MAX = 8;
  28651. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  28652. // The standard deviations (radians) associated with the extra mips. These are
  28653. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28654. // geometric shadowing function. These sigma values squared must match the
  28655. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28656. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28657. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  28658. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28659. // samples and exit early, but not recompile the shader.
  28660. const MAX_SAMPLES = 20;
  28661. const ENCODINGS = {
  28662. [ LinearEncoding ]: 0,
  28663. [ sRGBEncoding ]: 1,
  28664. [ RGBEEncoding ]: 2,
  28665. [ RGBM7Encoding ]: 3,
  28666. [ RGBM16Encoding ]: 4,
  28667. [ RGBDEncoding ]: 5,
  28668. [ GammaEncoding ]: 6
  28669. };
  28670. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  28671. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  28672. const _clearColor = /*@__PURE__*/ new Color();
  28673. let _oldTarget = null;
  28674. // Golden Ratio
  28675. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28676. const INV_PHI = 1 / PHI;
  28677. // Vertices of a dodecahedron (except the opposites, which represent the
  28678. // same axis), used as axis directions evenly spread on a sphere.
  28679. const _axisDirections = [
  28680. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  28681. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  28682. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  28683. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  28684. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28685. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28686. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28687. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28688. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28689. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  28690. /**
  28691. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28692. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28693. * blur to be quickly accessed based on material roughness. It is packed into a
  28694. * special CubeUV format that allows us to perform custom interpolation so that
  28695. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28696. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28697. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28698. * higher roughness levels. In this way we maintain resolution to smoothly
  28699. * interpolate diffuse lighting while limiting sampling computation.
  28700. */
  28701. class PMREMGenerator {
  28702. constructor( renderer ) {
  28703. this._renderer = renderer;
  28704. this._pingPongRenderTarget = null;
  28705. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  28706. this._equirectShader = null;
  28707. this._cubemapShader = null;
  28708. this._compileMaterial( this._blurMaterial );
  28709. }
  28710. /**
  28711. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28712. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28713. * in radians to be applied to the scene before PMREM generation. Optional near
  28714. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28715. * is placed at the origin).
  28716. */
  28717. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  28718. _oldTarget = this._renderer.getRenderTarget();
  28719. const cubeUVRenderTarget = this._allocateTargets();
  28720. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  28721. if ( sigma > 0 ) {
  28722. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  28723. }
  28724. this._applyPMREM( cubeUVRenderTarget );
  28725. this._cleanup( cubeUVRenderTarget );
  28726. return cubeUVRenderTarget;
  28727. }
  28728. /**
  28729. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28730. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  28731. * as this matches best with the 256 x 256 cubemap output.
  28732. */
  28733. fromEquirectangular( equirectangular ) {
  28734. return this._fromTexture( equirectangular );
  28735. }
  28736. /**
  28737. * Generates a PMREM from an cubemap texture, which can be either LDR
  28738. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  28739. * as this matches best with the 256 x 256 cubemap output.
  28740. */
  28741. fromCubemap( cubemap ) {
  28742. return this._fromTexture( cubemap );
  28743. }
  28744. /**
  28745. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28746. * your texture's network fetch for increased concurrency.
  28747. */
  28748. compileCubemapShader() {
  28749. if ( this._cubemapShader === null ) {
  28750. this._cubemapShader = _getCubemapShader();
  28751. this._compileMaterial( this._cubemapShader );
  28752. }
  28753. }
  28754. /**
  28755. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28756. * your texture's network fetch for increased concurrency.
  28757. */
  28758. compileEquirectangularShader() {
  28759. if ( this._equirectShader === null ) {
  28760. this._equirectShader = _getEquirectShader();
  28761. this._compileMaterial( this._equirectShader );
  28762. }
  28763. }
  28764. /**
  28765. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28766. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28767. * one of them will cause any others to also become unusable.
  28768. */
  28769. dispose() {
  28770. this._blurMaterial.dispose();
  28771. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  28772. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  28773. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  28774. _lodPlanes[ i ].dispose();
  28775. }
  28776. }
  28777. // private interface
  28778. _cleanup( outputTarget ) {
  28779. this._pingPongRenderTarget.dispose();
  28780. this._renderer.setRenderTarget( _oldTarget );
  28781. outputTarget.scissorTest = false;
  28782. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  28783. }
  28784. _fromTexture( texture ) {
  28785. _oldTarget = this._renderer.getRenderTarget();
  28786. const cubeUVRenderTarget = this._allocateTargets( texture );
  28787. this._textureToCubeUV( texture, cubeUVRenderTarget );
  28788. this._applyPMREM( cubeUVRenderTarget );
  28789. this._cleanup( cubeUVRenderTarget );
  28790. return cubeUVRenderTarget;
  28791. }
  28792. _allocateTargets( texture ) { // warning: null texture is valid
  28793. const params = {
  28794. magFilter: NearestFilter,
  28795. minFilter: NearestFilter,
  28796. generateMipmaps: false,
  28797. type: UnsignedByteType,
  28798. format: RGBEFormat,
  28799. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  28800. depthBuffer: false
  28801. };
  28802. const cubeUVRenderTarget = _createRenderTarget( params );
  28803. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  28804. this._pingPongRenderTarget = _createRenderTarget( params );
  28805. return cubeUVRenderTarget;
  28806. }
  28807. _compileMaterial( material ) {
  28808. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  28809. this._renderer.compile( tmpMesh, _flatCamera );
  28810. }
  28811. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  28812. const fov = 90;
  28813. const aspect = 1;
  28814. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  28815. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  28816. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  28817. const renderer = this._renderer;
  28818. const outputEncoding = renderer.outputEncoding;
  28819. const toneMapping = renderer.toneMapping;
  28820. renderer.getClearColor( _clearColor );
  28821. const clearAlpha = renderer.getClearAlpha();
  28822. renderer.toneMapping = NoToneMapping;
  28823. renderer.outputEncoding = LinearEncoding;
  28824. let background = scene.background;
  28825. if ( background && background.isColor ) {
  28826. background.convertSRGBToLinear();
  28827. // Convert linear to RGBE
  28828. const maxComponent = Math.max( background.r, background.g, background.b );
  28829. const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  28830. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  28831. const alpha = ( fExp + 128.0 ) / 255.0;
  28832. renderer.setClearColor( background, alpha );
  28833. scene.background = null;
  28834. }
  28835. for ( let i = 0; i < 6; i ++ ) {
  28836. const col = i % 3;
  28837. if ( col == 0 ) {
  28838. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28839. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  28840. } else if ( col == 1 ) {
  28841. cubeCamera.up.set( 0, 0, upSign[ i ] );
  28842. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  28843. } else {
  28844. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28845. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  28846. }
  28847. _setViewport( cubeUVRenderTarget,
  28848. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  28849. renderer.setRenderTarget( cubeUVRenderTarget );
  28850. renderer.render( scene, cubeCamera );
  28851. }
  28852. renderer.toneMapping = toneMapping;
  28853. renderer.outputEncoding = outputEncoding;
  28854. renderer.setClearColor( _clearColor, clearAlpha );
  28855. }
  28856. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  28857. const renderer = this._renderer;
  28858. if ( texture.isCubeTexture ) {
  28859. if ( this._cubemapShader == null ) {
  28860. this._cubemapShader = _getCubemapShader();
  28861. }
  28862. } else {
  28863. if ( this._equirectShader == null ) {
  28864. this._equirectShader = _getEquirectShader();
  28865. }
  28866. }
  28867. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  28868. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  28869. const uniforms = material.uniforms;
  28870. uniforms[ 'envMap' ].value = texture;
  28871. if ( ! texture.isCubeTexture ) {
  28872. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  28873. }
  28874. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  28875. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  28876. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  28877. renderer.setRenderTarget( cubeUVRenderTarget );
  28878. renderer.render( mesh, _flatCamera );
  28879. }
  28880. _applyPMREM( cubeUVRenderTarget ) {
  28881. const renderer = this._renderer;
  28882. const autoClear = renderer.autoClear;
  28883. renderer.autoClear = false;
  28884. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  28885. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  28886. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  28887. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  28888. }
  28889. renderer.autoClear = autoClear;
  28890. }
  28891. /**
  28892. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  28893. * vertically and horizontally, but this breaks down on a cube. Here we apply
  28894. * the blur latitudinally (around the poles), and then longitudinally (towards
  28895. * the poles) to approximate the orthogonally-separable blur. It is least
  28896. * accurate at the poles, but still does a decent job.
  28897. */
  28898. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  28899. const pingPongRenderTarget = this._pingPongRenderTarget;
  28900. this._halfBlur(
  28901. cubeUVRenderTarget,
  28902. pingPongRenderTarget,
  28903. lodIn,
  28904. lodOut,
  28905. sigma,
  28906. 'latitudinal',
  28907. poleAxis );
  28908. this._halfBlur(
  28909. pingPongRenderTarget,
  28910. cubeUVRenderTarget,
  28911. lodOut,
  28912. lodOut,
  28913. sigma,
  28914. 'longitudinal',
  28915. poleAxis );
  28916. }
  28917. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  28918. const renderer = this._renderer;
  28919. const blurMaterial = this._blurMaterial;
  28920. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  28921. console.error(
  28922. 'blur direction must be either latitudinal or longitudinal!' );
  28923. }
  28924. // Number of standard deviations at which to cut off the discrete approximation.
  28925. const STANDARD_DEVIATIONS = 3;
  28926. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  28927. const blurUniforms = blurMaterial.uniforms;
  28928. const pixels = _sizeLods[ lodIn ] - 1;
  28929. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  28930. const sigmaPixels = sigmaRadians / radiansPerPixel;
  28931. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  28932. if ( samples > MAX_SAMPLES ) {
  28933. console.warn( `sigmaRadians, ${
  28934. sigmaRadians}, is too large and will clip, as it requested ${
  28935. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  28936. }
  28937. const weights = [];
  28938. let sum = 0;
  28939. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  28940. const x = i / sigmaPixels;
  28941. const weight = Math.exp( - x * x / 2 );
  28942. weights.push( weight );
  28943. if ( i == 0 ) {
  28944. sum += weight;
  28945. } else if ( i < samples ) {
  28946. sum += 2 * weight;
  28947. }
  28948. }
  28949. for ( let i = 0; i < weights.length; i ++ ) {
  28950. weights[ i ] = weights[ i ] / sum;
  28951. }
  28952. blurUniforms[ 'envMap' ].value = targetIn.texture;
  28953. blurUniforms[ 'samples' ].value = samples;
  28954. blurUniforms[ 'weights' ].value = weights;
  28955. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  28956. if ( poleAxis ) {
  28957. blurUniforms[ 'poleAxis' ].value = poleAxis;
  28958. }
  28959. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  28960. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  28961. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  28962. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  28963. const outputSize = _sizeLods[ lodOut ];
  28964. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  28965. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  28966. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  28967. renderer.setRenderTarget( targetOut );
  28968. renderer.render( blurMesh, _flatCamera );
  28969. }
  28970. }
  28971. function _isLDR( texture ) {
  28972. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  28973. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  28974. }
  28975. function _createPlanes() {
  28976. const _lodPlanes = [];
  28977. const _sizeLods = [];
  28978. const _sigmas = [];
  28979. let lod = LOD_MAX;
  28980. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  28981. const sizeLod = Math.pow( 2, lod );
  28982. _sizeLods.push( sizeLod );
  28983. let sigma = 1.0 / sizeLod;
  28984. if ( i > LOD_MAX - LOD_MIN ) {
  28985. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  28986. } else if ( i == 0 ) {
  28987. sigma = 0;
  28988. }
  28989. _sigmas.push( sigma );
  28990. const texelSize = 1.0 / ( sizeLod - 1 );
  28991. const min = - texelSize / 2;
  28992. const max = 1 + texelSize / 2;
  28993. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  28994. const cubeFaces = 6;
  28995. const vertices = 6;
  28996. const positionSize = 3;
  28997. const uvSize = 2;
  28998. const faceIndexSize = 1;
  28999. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29000. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29001. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29002. for ( let face = 0; face < cubeFaces; face ++ ) {
  29003. const x = ( face % 3 ) * 2 / 3 - 1;
  29004. const y = face > 2 ? 0 : - 1;
  29005. const coordinates = [
  29006. x, y, 0,
  29007. x + 2 / 3, y, 0,
  29008. x + 2 / 3, y + 1, 0,
  29009. x, y, 0,
  29010. x + 2 / 3, y + 1, 0,
  29011. x, y + 1, 0
  29012. ];
  29013. position.set( coordinates, positionSize * vertices * face );
  29014. uv.set( uv1, uvSize * vertices * face );
  29015. const fill = [ face, face, face, face, face, face ];
  29016. faceIndex.set( fill, faceIndexSize * vertices * face );
  29017. }
  29018. const planes = new BufferGeometry();
  29019. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29020. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29021. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29022. _lodPlanes.push( planes );
  29023. if ( lod > LOD_MIN ) {
  29024. lod --;
  29025. }
  29026. }
  29027. return { _lodPlanes, _sizeLods, _sigmas };
  29028. }
  29029. function _createRenderTarget( params ) {
  29030. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  29031. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29032. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29033. cubeUVRenderTarget.scissorTest = true;
  29034. return cubeUVRenderTarget;
  29035. }
  29036. function _setViewport( target, x, y, width, height ) {
  29037. target.viewport.set( x, y, width, height );
  29038. target.scissor.set( x, y, width, height );
  29039. }
  29040. function _getBlurShader( maxSamples ) {
  29041. const weights = new Float32Array( maxSamples );
  29042. const poleAxis = new Vector3( 0, 1, 0 );
  29043. const shaderMaterial = new RawShaderMaterial( {
  29044. name: 'SphericalGaussianBlur',
  29045. defines: { 'n': maxSamples },
  29046. uniforms: {
  29047. 'envMap': { value: null },
  29048. 'samples': { value: 1 },
  29049. 'weights': { value: weights },
  29050. 'latitudinal': { value: false },
  29051. 'dTheta': { value: 0 },
  29052. 'mipInt': { value: 0 },
  29053. 'poleAxis': { value: poleAxis },
  29054. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29055. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29056. },
  29057. vertexShader: _getCommonVertexShader(),
  29058. fragmentShader: /* glsl */`
  29059. precision mediump float;
  29060. precision mediump int;
  29061. varying vec3 vOutputDirection;
  29062. uniform sampler2D envMap;
  29063. uniform int samples;
  29064. uniform float weights[ n ];
  29065. uniform bool latitudinal;
  29066. uniform float dTheta;
  29067. uniform float mipInt;
  29068. uniform vec3 poleAxis;
  29069. ${ _getEncodings() }
  29070. #define ENVMAP_TYPE_CUBE_UV
  29071. #include <cube_uv_reflection_fragment>
  29072. vec3 getSample( float theta, vec3 axis ) {
  29073. float cosTheta = cos( theta );
  29074. // Rodrigues' axis-angle rotation
  29075. vec3 sampleDirection = vOutputDirection * cosTheta
  29076. + cross( axis, vOutputDirection ) * sin( theta )
  29077. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  29078. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  29079. }
  29080. void main() {
  29081. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  29082. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  29083. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  29084. }
  29085. axis = normalize( axis );
  29086. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29087. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  29088. for ( int i = 1; i < n; i++ ) {
  29089. if ( i >= samples ) {
  29090. break;
  29091. }
  29092. float theta = dTheta * float( i );
  29093. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  29094. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  29095. }
  29096. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29097. }
  29098. `,
  29099. blending: NoBlending,
  29100. depthTest: false,
  29101. depthWrite: false
  29102. } );
  29103. return shaderMaterial;
  29104. }
  29105. function _getEquirectShader() {
  29106. const texelSize = new Vector2( 1, 1 );
  29107. const shaderMaterial = new RawShaderMaterial( {
  29108. name: 'EquirectangularToCubeUV',
  29109. uniforms: {
  29110. 'envMap': { value: null },
  29111. 'texelSize': { value: texelSize },
  29112. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29113. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29114. },
  29115. vertexShader: _getCommonVertexShader(),
  29116. fragmentShader: /* glsl */`
  29117. precision mediump float;
  29118. precision mediump int;
  29119. varying vec3 vOutputDirection;
  29120. uniform sampler2D envMap;
  29121. uniform vec2 texelSize;
  29122. ${ _getEncodings() }
  29123. #include <common>
  29124. void main() {
  29125. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29126. vec3 outputDirection = normalize( vOutputDirection );
  29127. vec2 uv = equirectUv( outputDirection );
  29128. vec2 f = fract( uv / texelSize - 0.5 );
  29129. uv -= f * texelSize;
  29130. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29131. uv.x += texelSize.x;
  29132. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29133. uv.y += texelSize.y;
  29134. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29135. uv.x -= texelSize.x;
  29136. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29137. vec3 tm = mix( tl, tr, f.x );
  29138. vec3 bm = mix( bl, br, f.x );
  29139. gl_FragColor.rgb = mix( tm, bm, f.y );
  29140. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29141. }
  29142. `,
  29143. blending: NoBlending,
  29144. depthTest: false,
  29145. depthWrite: false
  29146. } );
  29147. return shaderMaterial;
  29148. }
  29149. function _getCubemapShader() {
  29150. const shaderMaterial = new RawShaderMaterial( {
  29151. name: 'CubemapToCubeUV',
  29152. uniforms: {
  29153. 'envMap': { value: null },
  29154. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29155. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29156. },
  29157. vertexShader: _getCommonVertexShader(),
  29158. fragmentShader: /* glsl */`
  29159. precision mediump float;
  29160. precision mediump int;
  29161. varying vec3 vOutputDirection;
  29162. uniform samplerCube envMap;
  29163. ${ _getEncodings() }
  29164. void main() {
  29165. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29166. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  29167. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29168. }
  29169. `,
  29170. blending: NoBlending,
  29171. depthTest: false,
  29172. depthWrite: false
  29173. } );
  29174. return shaderMaterial;
  29175. }
  29176. function _getCommonVertexShader() {
  29177. return /* glsl */`
  29178. precision mediump float;
  29179. precision mediump int;
  29180. attribute vec3 position;
  29181. attribute vec2 uv;
  29182. attribute float faceIndex;
  29183. varying vec3 vOutputDirection;
  29184. // RH coordinate system; PMREM face-indexing convention
  29185. vec3 getDirection( vec2 uv, float face ) {
  29186. uv = 2.0 * uv - 1.0;
  29187. vec3 direction = vec3( uv, 1.0 );
  29188. if ( face == 0.0 ) {
  29189. direction = direction.zyx; // ( 1, v, u ) pos x
  29190. } else if ( face == 1.0 ) {
  29191. direction = direction.xzy;
  29192. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  29193. } else if ( face == 2.0 ) {
  29194. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  29195. } else if ( face == 3.0 ) {
  29196. direction = direction.zyx;
  29197. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  29198. } else if ( face == 4.0 ) {
  29199. direction = direction.xzy;
  29200. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  29201. } else if ( face == 5.0 ) {
  29202. direction.z *= -1.0; // ( u, v, -1 ) neg z
  29203. }
  29204. return direction;
  29205. }
  29206. void main() {
  29207. vOutputDirection = getDirection( uv, faceIndex );
  29208. gl_Position = vec4( position, 1.0 );
  29209. }
  29210. `;
  29211. }
  29212. function _getEncodings() {
  29213. return /* glsl */`
  29214. uniform int inputEncoding;
  29215. uniform int outputEncoding;
  29216. #include <encodings_pars_fragment>
  29217. vec4 inputTexelToLinear( vec4 value ) {
  29218. if ( inputEncoding == 0 ) {
  29219. return value;
  29220. } else if ( inputEncoding == 1 ) {
  29221. return sRGBToLinear( value );
  29222. } else if ( inputEncoding == 2 ) {
  29223. return RGBEToLinear( value );
  29224. } else if ( inputEncoding == 3 ) {
  29225. return RGBMToLinear( value, 7.0 );
  29226. } else if ( inputEncoding == 4 ) {
  29227. return RGBMToLinear( value, 16.0 );
  29228. } else if ( inputEncoding == 5 ) {
  29229. return RGBDToLinear( value, 256.0 );
  29230. } else {
  29231. return GammaToLinear( value, 2.2 );
  29232. }
  29233. }
  29234. vec4 linearToOutputTexel( vec4 value ) {
  29235. if ( outputEncoding == 0 ) {
  29236. return value;
  29237. } else if ( outputEncoding == 1 ) {
  29238. return LinearTosRGB( value );
  29239. } else if ( outputEncoding == 2 ) {
  29240. return LinearToRGBE( value );
  29241. } else if ( outputEncoding == 3 ) {
  29242. return LinearToRGBM( value, 7.0 );
  29243. } else if ( outputEncoding == 4 ) {
  29244. return LinearToRGBM( value, 16.0 );
  29245. } else if ( outputEncoding == 5 ) {
  29246. return LinearToRGBD( value, 256.0 );
  29247. } else {
  29248. return LinearToGamma( value, 2.2 );
  29249. }
  29250. }
  29251. vec4 envMapTexelToLinear( vec4 color ) {
  29252. return inputTexelToLinear( color );
  29253. }
  29254. `;
  29255. }
  29256. function Face4( a, b, c, d, normal, color, materialIndex ) {
  29257. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  29258. return new Face3( a, b, c, normal, color, materialIndex );
  29259. }
  29260. const LineStrip = 0;
  29261. const LinePieces = 1;
  29262. const NoColors = 0;
  29263. const FaceColors = 1;
  29264. const VertexColors = 2;
  29265. function MeshFaceMaterial( materials ) {
  29266. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  29267. return materials;
  29268. }
  29269. function MultiMaterial( materials = [] ) {
  29270. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  29271. materials.isMultiMaterial = true;
  29272. materials.materials = materials;
  29273. materials.clone = function () {
  29274. return materials.slice();
  29275. };
  29276. return materials;
  29277. }
  29278. function PointCloud( geometry, material ) {
  29279. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  29280. return new Points( geometry, material );
  29281. }
  29282. function Particle( material ) {
  29283. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  29284. return new Sprite$1( material );
  29285. }
  29286. function ParticleSystem( geometry, material ) {
  29287. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  29288. return new Points( geometry, material );
  29289. }
  29290. function PointCloudMaterial( parameters ) {
  29291. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  29292. return new PointsMaterial( parameters );
  29293. }
  29294. function ParticleBasicMaterial( parameters ) {
  29295. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  29296. return new PointsMaterial( parameters );
  29297. }
  29298. function ParticleSystemMaterial( parameters ) {
  29299. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  29300. return new PointsMaterial( parameters );
  29301. }
  29302. function Vertex( x, y, z ) {
  29303. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  29304. return new Vector3( x, y, z );
  29305. }
  29306. //
  29307. function DynamicBufferAttribute( array, itemSize ) {
  29308. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  29309. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  29310. }
  29311. function Int8Attribute( array, itemSize ) {
  29312. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  29313. return new Int8BufferAttribute( array, itemSize );
  29314. }
  29315. function Uint8Attribute( array, itemSize ) {
  29316. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  29317. return new Uint8BufferAttribute( array, itemSize );
  29318. }
  29319. function Uint8ClampedAttribute( array, itemSize ) {
  29320. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  29321. return new Uint8ClampedBufferAttribute( array, itemSize );
  29322. }
  29323. function Int16Attribute( array, itemSize ) {
  29324. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  29325. return new Int16BufferAttribute( array, itemSize );
  29326. }
  29327. function Uint16Attribute( array, itemSize ) {
  29328. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  29329. return new Uint16BufferAttribute( array, itemSize );
  29330. }
  29331. function Int32Attribute( array, itemSize ) {
  29332. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  29333. return new Int32BufferAttribute( array, itemSize );
  29334. }
  29335. function Uint32Attribute( array, itemSize ) {
  29336. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  29337. return new Uint32BufferAttribute( array, itemSize );
  29338. }
  29339. function Float32Attribute( array, itemSize ) {
  29340. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  29341. return new Float32BufferAttribute( array, itemSize );
  29342. }
  29343. function Float64Attribute( array, itemSize ) {
  29344. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  29345. return new Float64BufferAttribute( array, itemSize );
  29346. }
  29347. //
  29348. Curve.create = function ( construct, getPoint ) {
  29349. console.log( 'THREE.Curve.create() has been deprecated' );
  29350. construct.prototype = Object.create( Curve.prototype );
  29351. construct.prototype.constructor = construct;
  29352. construct.prototype.getPoint = getPoint;
  29353. return construct;
  29354. };
  29355. //
  29356. Object.assign( CurvePath.prototype, {
  29357. createPointsGeometry: function ( divisions ) {
  29358. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  29359. // generate geometry from path points (for Line or Points objects)
  29360. const pts = this.getPoints( divisions );
  29361. return this.createGeometry( pts );
  29362. },
  29363. createSpacedPointsGeometry: function ( divisions ) {
  29364. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  29365. // generate geometry from equidistant sampling along the path
  29366. const pts = this.getSpacedPoints( divisions );
  29367. return this.createGeometry( pts );
  29368. },
  29369. createGeometry: function ( points ) {
  29370. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  29371. const geometry = new Geometry();
  29372. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29373. const point = points[ i ];
  29374. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  29375. }
  29376. return geometry;
  29377. }
  29378. } );
  29379. //
  29380. Object.assign( Path.prototype, {
  29381. fromPoints: function ( points ) {
  29382. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  29383. return this.setFromPoints( points );
  29384. }
  29385. } );
  29386. //
  29387. function ClosedSplineCurve3( points ) {
  29388. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29389. CatmullRomCurve3.call( this, points );
  29390. this.type = 'catmullrom';
  29391. this.closed = true;
  29392. }
  29393. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29394. //
  29395. function SplineCurve3( points ) {
  29396. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29397. CatmullRomCurve3.call( this, points );
  29398. this.type = 'catmullrom';
  29399. }
  29400. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29401. //
  29402. function Spline( points ) {
  29403. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  29404. CatmullRomCurve3.call( this, points );
  29405. this.type = 'catmullrom';
  29406. }
  29407. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  29408. Object.assign( Spline.prototype, {
  29409. initFromArray: function ( /* a */ ) {
  29410. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  29411. },
  29412. getControlPointsArray: function ( /* optionalTarget */ ) {
  29413. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  29414. },
  29415. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  29416. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  29417. }
  29418. } );
  29419. //
  29420. function AxisHelper( size ) {
  29421. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  29422. return new AxesHelper( size );
  29423. }
  29424. function BoundingBoxHelper( object, color ) {
  29425. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  29426. return new BoxHelper( object, color );
  29427. }
  29428. function EdgesHelper( object, hex ) {
  29429. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  29430. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29431. }
  29432. GridHelper.prototype.setColors = function () {
  29433. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  29434. };
  29435. SkeletonHelper.prototype.update = function () {
  29436. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  29437. };
  29438. function WireframeHelper( object, hex ) {
  29439. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  29440. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29441. }
  29442. //
  29443. Object.assign( Loader.prototype, {
  29444. extractUrlBase: function ( url ) {
  29445. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  29446. return LoaderUtils.extractUrlBase( url );
  29447. }
  29448. } );
  29449. Loader.Handlers = {
  29450. add: function ( /* regex, loader */ ) {
  29451. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  29452. },
  29453. get: function ( /* file */ ) {
  29454. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  29455. }
  29456. };
  29457. function XHRLoader( manager ) {
  29458. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  29459. return new FileLoader( manager );
  29460. }
  29461. function BinaryTextureLoader( manager ) {
  29462. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  29463. return new DataTextureLoader( manager );
  29464. }
  29465. //
  29466. Object.assign( Box2.prototype, {
  29467. center: function ( optionalTarget ) {
  29468. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  29469. return this.getCenter( optionalTarget );
  29470. },
  29471. empty: function () {
  29472. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  29473. return this.isEmpty();
  29474. },
  29475. isIntersectionBox: function ( box ) {
  29476. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29477. return this.intersectsBox( box );
  29478. },
  29479. size: function ( optionalTarget ) {
  29480. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  29481. return this.getSize( optionalTarget );
  29482. }
  29483. } );
  29484. Object.assign( Box3.prototype, {
  29485. center: function ( optionalTarget ) {
  29486. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  29487. return this.getCenter( optionalTarget );
  29488. },
  29489. empty: function () {
  29490. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  29491. return this.isEmpty();
  29492. },
  29493. isIntersectionBox: function ( box ) {
  29494. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29495. return this.intersectsBox( box );
  29496. },
  29497. isIntersectionSphere: function ( sphere ) {
  29498. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29499. return this.intersectsSphere( sphere );
  29500. },
  29501. size: function ( optionalTarget ) {
  29502. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  29503. return this.getSize( optionalTarget );
  29504. }
  29505. } );
  29506. Object.assign( Sphere.prototype, {
  29507. empty: function () {
  29508. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  29509. return this.isEmpty();
  29510. },
  29511. } );
  29512. Frustum.prototype.setFromMatrix = function ( m ) {
  29513. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  29514. return this.setFromProjectionMatrix( m );
  29515. };
  29516. Line3.prototype.center = function ( optionalTarget ) {
  29517. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  29518. return this.getCenter( optionalTarget );
  29519. };
  29520. Object.assign( MathUtils, {
  29521. random16: function () {
  29522. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  29523. return Math.random();
  29524. },
  29525. nearestPowerOfTwo: function ( value ) {
  29526. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  29527. return MathUtils.floorPowerOfTwo( value );
  29528. },
  29529. nextPowerOfTwo: function ( value ) {
  29530. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  29531. return MathUtils.ceilPowerOfTwo( value );
  29532. }
  29533. } );
  29534. Object.assign( Matrix3.prototype, {
  29535. flattenToArrayOffset: function ( array, offset ) {
  29536. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  29537. return this.toArray( array, offset );
  29538. },
  29539. multiplyVector3: function ( vector ) {
  29540. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  29541. return vector.applyMatrix3( this );
  29542. },
  29543. multiplyVector3Array: function ( /* a */ ) {
  29544. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  29545. },
  29546. applyToBufferAttribute: function ( attribute ) {
  29547. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  29548. return attribute.applyMatrix3( this );
  29549. },
  29550. applyToVector3Array: function ( /* array, offset, length */ ) {
  29551. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  29552. },
  29553. getInverse: function ( matrix ) {
  29554. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  29555. return this.copy( matrix ).invert();
  29556. }
  29557. } );
  29558. Object.assign( Matrix4.prototype, {
  29559. extractPosition: function ( m ) {
  29560. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  29561. return this.copyPosition( m );
  29562. },
  29563. flattenToArrayOffset: function ( array, offset ) {
  29564. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  29565. return this.toArray( array, offset );
  29566. },
  29567. getPosition: function () {
  29568. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  29569. return new Vector3().setFromMatrixColumn( this, 3 );
  29570. },
  29571. setRotationFromQuaternion: function ( q ) {
  29572. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  29573. return this.makeRotationFromQuaternion( q );
  29574. },
  29575. multiplyToArray: function () {
  29576. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  29577. },
  29578. multiplyVector3: function ( vector ) {
  29579. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29580. return vector.applyMatrix4( this );
  29581. },
  29582. multiplyVector4: function ( vector ) {
  29583. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29584. return vector.applyMatrix4( this );
  29585. },
  29586. multiplyVector3Array: function ( /* a */ ) {
  29587. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  29588. },
  29589. rotateAxis: function ( v ) {
  29590. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  29591. v.transformDirection( this );
  29592. },
  29593. crossVector: function ( vector ) {
  29594. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29595. return vector.applyMatrix4( this );
  29596. },
  29597. translate: function () {
  29598. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  29599. },
  29600. rotateX: function () {
  29601. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  29602. },
  29603. rotateY: function () {
  29604. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  29605. },
  29606. rotateZ: function () {
  29607. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  29608. },
  29609. rotateByAxis: function () {
  29610. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  29611. },
  29612. applyToBufferAttribute: function ( attribute ) {
  29613. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  29614. return attribute.applyMatrix4( this );
  29615. },
  29616. applyToVector3Array: function ( /* array, offset, length */ ) {
  29617. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  29618. },
  29619. makeFrustum: function ( left, right, bottom, top, near, far ) {
  29620. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  29621. return this.makePerspective( left, right, top, bottom, near, far );
  29622. },
  29623. getInverse: function ( matrix ) {
  29624. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  29625. return this.copy( matrix ).invert();
  29626. }
  29627. } );
  29628. Plane.prototype.isIntersectionLine = function ( line ) {
  29629. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  29630. return this.intersectsLine( line );
  29631. };
  29632. Object.assign( Quaternion.prototype, {
  29633. multiplyVector3: function ( vector ) {
  29634. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  29635. return vector.applyQuaternion( this );
  29636. },
  29637. inverse: function ( ) {
  29638. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  29639. return this.invert();
  29640. }
  29641. } );
  29642. Object.assign( Ray.prototype, {
  29643. isIntersectionBox: function ( box ) {
  29644. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29645. return this.intersectsBox( box );
  29646. },
  29647. isIntersectionPlane: function ( plane ) {
  29648. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  29649. return this.intersectsPlane( plane );
  29650. },
  29651. isIntersectionSphere: function ( sphere ) {
  29652. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29653. return this.intersectsSphere( sphere );
  29654. }
  29655. } );
  29656. Object.assign( Triangle.prototype, {
  29657. area: function () {
  29658. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  29659. return this.getArea();
  29660. },
  29661. barycoordFromPoint: function ( point, target ) {
  29662. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29663. return this.getBarycoord( point, target );
  29664. },
  29665. midpoint: function ( target ) {
  29666. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  29667. return this.getMidpoint( target );
  29668. },
  29669. normal: function ( target ) {
  29670. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29671. return this.getNormal( target );
  29672. },
  29673. plane: function ( target ) {
  29674. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  29675. return this.getPlane( target );
  29676. }
  29677. } );
  29678. Object.assign( Triangle, {
  29679. barycoordFromPoint: function ( point, a, b, c, target ) {
  29680. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  29681. return Triangle.getBarycoord( point, a, b, c, target );
  29682. },
  29683. normal: function ( a, b, c, target ) {
  29684. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  29685. return Triangle.getNormal( a, b, c, target );
  29686. }
  29687. } );
  29688. Object.assign( Shape.prototype, {
  29689. extractAllPoints: function ( divisions ) {
  29690. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  29691. return this.extractPoints( divisions );
  29692. },
  29693. extrude: function ( options ) {
  29694. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  29695. return new ExtrudeGeometry( this, options );
  29696. },
  29697. makeGeometry: function ( options ) {
  29698. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  29699. return new ShapeGeometry( this, options );
  29700. }
  29701. } );
  29702. Object.assign( Vector2.prototype, {
  29703. fromAttribute: function ( attribute, index, offset ) {
  29704. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29705. return this.fromBufferAttribute( attribute, index, offset );
  29706. },
  29707. distanceToManhattan: function ( v ) {
  29708. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  29709. return this.manhattanDistanceTo( v );
  29710. },
  29711. lengthManhattan: function () {
  29712. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  29713. return this.manhattanLength();
  29714. }
  29715. } );
  29716. Object.assign( Vector3.prototype, {
  29717. setEulerFromRotationMatrix: function () {
  29718. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  29719. },
  29720. setEulerFromQuaternion: function () {
  29721. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  29722. },
  29723. getPositionFromMatrix: function ( m ) {
  29724. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  29725. return this.setFromMatrixPosition( m );
  29726. },
  29727. getScaleFromMatrix: function ( m ) {
  29728. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  29729. return this.setFromMatrixScale( m );
  29730. },
  29731. getColumnFromMatrix: function ( index, matrix ) {
  29732. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  29733. return this.setFromMatrixColumn( matrix, index );
  29734. },
  29735. applyProjection: function ( m ) {
  29736. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  29737. return this.applyMatrix4( m );
  29738. },
  29739. fromAttribute: function ( attribute, index, offset ) {
  29740. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29741. return this.fromBufferAttribute( attribute, index, offset );
  29742. },
  29743. distanceToManhattan: function ( v ) {
  29744. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  29745. return this.manhattanDistanceTo( v );
  29746. },
  29747. lengthManhattan: function () {
  29748. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  29749. return this.manhattanLength();
  29750. }
  29751. } );
  29752. Object.assign( Vector4.prototype, {
  29753. fromAttribute: function ( attribute, index, offset ) {
  29754. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  29755. return this.fromBufferAttribute( attribute, index, offset );
  29756. },
  29757. lengthManhattan: function () {
  29758. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  29759. return this.manhattanLength();
  29760. }
  29761. } );
  29762. //
  29763. Object.assign( Geometry.prototype, {
  29764. computeTangents: function () {
  29765. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  29766. },
  29767. computeLineDistances: function () {
  29768. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  29769. },
  29770. applyMatrix: function ( matrix ) {
  29771. console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  29772. return this.applyMatrix4( matrix );
  29773. }
  29774. } );
  29775. Object.assign( Object3D.prototype, {
  29776. getChildByName: function ( name ) {
  29777. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  29778. return this.getObjectByName( name );
  29779. },
  29780. renderDepth: function () {
  29781. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  29782. },
  29783. translate: function ( distance, axis ) {
  29784. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  29785. return this.translateOnAxis( axis, distance );
  29786. },
  29787. getWorldRotation: function () {
  29788. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  29789. },
  29790. applyMatrix: function ( matrix ) {
  29791. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  29792. return this.applyMatrix4( matrix );
  29793. }
  29794. } );
  29795. Object.defineProperties( Object3D.prototype, {
  29796. eulerOrder: {
  29797. get: function () {
  29798. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29799. return this.rotation.order;
  29800. },
  29801. set: function ( value ) {
  29802. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29803. this.rotation.order = value;
  29804. }
  29805. },
  29806. useQuaternion: {
  29807. get: function () {
  29808. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29809. },
  29810. set: function () {
  29811. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29812. }
  29813. }
  29814. } );
  29815. Object.assign( Mesh.prototype, {
  29816. setDrawMode: function () {
  29817. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  29818. },
  29819. } );
  29820. Object.defineProperties( Mesh.prototype, {
  29821. drawMode: {
  29822. get: function () {
  29823. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  29824. return TrianglesDrawMode;
  29825. },
  29826. set: function () {
  29827. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  29828. }
  29829. }
  29830. } );
  29831. Object.defineProperties( LOD.prototype, {
  29832. objects: {
  29833. get: function () {
  29834. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  29835. return this.levels;
  29836. }
  29837. }
  29838. } );
  29839. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  29840. get: function () {
  29841. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  29842. },
  29843. set: function () {
  29844. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  29845. }
  29846. } );
  29847. SkinnedMesh.prototype.initBones = function () {
  29848. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  29849. };
  29850. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  29851. get: function () {
  29852. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  29853. return this.arcLengthDivisions;
  29854. },
  29855. set: function ( value ) {
  29856. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  29857. this.arcLengthDivisions = value;
  29858. }
  29859. } );
  29860. //
  29861. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  29862. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  29863. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  29864. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  29865. this.setFocalLength( focalLength );
  29866. };
  29867. //
  29868. Object.defineProperties( Light.prototype, {
  29869. onlyShadow: {
  29870. set: function () {
  29871. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  29872. }
  29873. },
  29874. shadowCameraFov: {
  29875. set: function ( value ) {
  29876. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  29877. this.shadow.camera.fov = value;
  29878. }
  29879. },
  29880. shadowCameraLeft: {
  29881. set: function ( value ) {
  29882. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  29883. this.shadow.camera.left = value;
  29884. }
  29885. },
  29886. shadowCameraRight: {
  29887. set: function ( value ) {
  29888. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  29889. this.shadow.camera.right = value;
  29890. }
  29891. },
  29892. shadowCameraTop: {
  29893. set: function ( value ) {
  29894. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  29895. this.shadow.camera.top = value;
  29896. }
  29897. },
  29898. shadowCameraBottom: {
  29899. set: function ( value ) {
  29900. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  29901. this.shadow.camera.bottom = value;
  29902. }
  29903. },
  29904. shadowCameraNear: {
  29905. set: function ( value ) {
  29906. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29907. this.shadow.camera.near = value;
  29908. }
  29909. },
  29910. shadowCameraFar: {
  29911. set: function ( value ) {
  29912. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29913. this.shadow.camera.far = value;
  29914. }
  29915. },
  29916. shadowCameraVisible: {
  29917. set: function () {
  29918. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29919. }
  29920. },
  29921. shadowBias: {
  29922. set: function ( value ) {
  29923. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29924. this.shadow.bias = value;
  29925. }
  29926. },
  29927. shadowDarkness: {
  29928. set: function () {
  29929. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29930. }
  29931. },
  29932. shadowMapWidth: {
  29933. set: function ( value ) {
  29934. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29935. this.shadow.mapSize.width = value;
  29936. }
  29937. },
  29938. shadowMapHeight: {
  29939. set: function ( value ) {
  29940. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29941. this.shadow.mapSize.height = value;
  29942. }
  29943. }
  29944. } );
  29945. //
  29946. Object.defineProperties( BufferAttribute.prototype, {
  29947. length: {
  29948. get: function () {
  29949. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29950. return this.array.length;
  29951. }
  29952. },
  29953. dynamic: {
  29954. get: function () {
  29955. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29956. return this.usage === DynamicDrawUsage;
  29957. },
  29958. set: function ( /* value */ ) {
  29959. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  29960. this.setUsage( DynamicDrawUsage );
  29961. }
  29962. }
  29963. } );
  29964. Object.assign( BufferAttribute.prototype, {
  29965. setDynamic: function ( value ) {
  29966. //console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  29967. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  29968. return this;
  29969. },
  29970. copyIndicesArray: function ( /* indices */ ) {
  29971. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  29972. },
  29973. setArray: function ( /* array */ ) {
  29974. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  29975. }
  29976. } );
  29977. Object.assign( BufferGeometry.prototype, {
  29978. addIndex: function ( index ) {
  29979. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29980. this.setIndex( index );
  29981. },
  29982. addAttribute: function ( name, attribute ) {
  29983. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  29984. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  29985. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  29986. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  29987. }
  29988. if ( name === 'index' ) {
  29989. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  29990. this.setIndex( attribute );
  29991. return this;
  29992. }
  29993. return this.setAttribute( name, attribute );
  29994. },
  29995. addDrawCall: function ( start, count, indexOffset ) {
  29996. if ( indexOffset !== undefined ) {
  29997. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29998. }
  29999. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  30000. this.addGroup( start, count );
  30001. },
  30002. clearDrawCalls: function () {
  30003. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  30004. this.clearGroups();
  30005. },
  30006. computeTangents: function () {
  30007. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  30008. },
  30009. computeOffsets: function () {
  30010. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  30011. },
  30012. removeAttribute: function ( name ) {
  30013. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  30014. return this.deleteAttribute( name );
  30015. },
  30016. applyMatrix: function ( matrix ) {
  30017. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30018. return this.applyMatrix4( matrix );
  30019. }
  30020. } );
  30021. Object.defineProperties( BufferGeometry.prototype, {
  30022. drawcalls: {
  30023. get: function () {
  30024. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  30025. return this.groups;
  30026. }
  30027. },
  30028. offsets: {
  30029. get: function () {
  30030. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  30031. return this.groups;
  30032. }
  30033. }
  30034. } );
  30035. Object.defineProperties( InstancedBufferGeometry.prototype, {
  30036. maxInstancedCount: {
  30037. get: function () {
  30038. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  30039. return this.instanceCount;
  30040. },
  30041. set: function ( value ) {
  30042. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  30043. this.instanceCount = value;
  30044. }
  30045. }
  30046. } );
  30047. Object.defineProperties( Raycaster.prototype, {
  30048. linePrecision: {
  30049. get: function () {
  30050. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  30051. return this.params.Line.threshold;
  30052. },
  30053. set: function ( value ) {
  30054. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  30055. this.params.Line.threshold = value;
  30056. }
  30057. }
  30058. } );
  30059. Object.defineProperties( InterleavedBuffer.prototype, {
  30060. dynamic: {
  30061. get: function () {
  30062. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  30063. return this.usage === DynamicDrawUsage;
  30064. },
  30065. set: function ( value ) {
  30066. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  30067. this.setUsage( value );
  30068. }
  30069. }
  30070. } );
  30071. Object.assign( InterleavedBuffer.prototype, {
  30072. setDynamic: function ( value ) {
  30073. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30074. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30075. return this;
  30076. },
  30077. setArray: function ( /* array */ ) {
  30078. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30079. }
  30080. } );
  30081. //
  30082. Object.assign( ExtrudeBufferGeometry.prototype, {
  30083. getArrays: function () {
  30084. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  30085. },
  30086. addShapeList: function () {
  30087. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  30088. },
  30089. addShape: function () {
  30090. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  30091. }
  30092. } );
  30093. //
  30094. Object.assign( Scene.prototype, {
  30095. dispose: function () {
  30096. console.error( 'THREE.Scene: .dispose() has been removed.' );
  30097. }
  30098. } );
  30099. //
  30100. Object.defineProperties( Uniform.prototype, {
  30101. dynamic: {
  30102. set: function () {
  30103. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  30104. }
  30105. },
  30106. onUpdate: {
  30107. value: function () {
  30108. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  30109. return this;
  30110. }
  30111. }
  30112. } );
  30113. //
  30114. Object.defineProperties( Material.prototype, {
  30115. wrapAround: {
  30116. get: function () {
  30117. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30118. },
  30119. set: function () {
  30120. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30121. }
  30122. },
  30123. overdraw: {
  30124. get: function () {
  30125. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30126. },
  30127. set: function () {
  30128. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30129. }
  30130. },
  30131. wrapRGB: {
  30132. get: function () {
  30133. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  30134. return new Color();
  30135. }
  30136. },
  30137. shading: {
  30138. get: function () {
  30139. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30140. },
  30141. set: function ( value ) {
  30142. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30143. this.flatShading = ( value === FlatShading$1 );
  30144. }
  30145. },
  30146. stencilMask: {
  30147. get: function () {
  30148. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30149. return this.stencilFuncMask;
  30150. },
  30151. set: function ( value ) {
  30152. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30153. this.stencilFuncMask = value;
  30154. }
  30155. }
  30156. } );
  30157. Object.defineProperties( MeshPhongMaterial.prototype, {
  30158. metal: {
  30159. get: function () {
  30160. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  30161. return false;
  30162. },
  30163. set: function () {
  30164. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  30165. }
  30166. }
  30167. } );
  30168. Object.defineProperties( MeshPhysicalMaterial.prototype, {
  30169. transparency: {
  30170. get: function () {
  30171. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  30172. return this.transmission;
  30173. },
  30174. set: function ( value ) {
  30175. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  30176. this.transmission = value;
  30177. }
  30178. }
  30179. } );
  30180. Object.defineProperties( ShaderMaterial.prototype, {
  30181. derivatives: {
  30182. get: function () {
  30183. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30184. return this.extensions.derivatives;
  30185. },
  30186. set: function ( value ) {
  30187. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30188. this.extensions.derivatives = value;
  30189. }
  30190. }
  30191. } );
  30192. //
  30193. Object.assign( WebGLRenderer.prototype, {
  30194. clearTarget: function ( renderTarget, color, depth, stencil ) {
  30195. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  30196. this.setRenderTarget( renderTarget );
  30197. this.clear( color, depth, stencil );
  30198. },
  30199. animate: function ( callback ) {
  30200. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  30201. this.setAnimationLoop( callback );
  30202. },
  30203. getCurrentRenderTarget: function () {
  30204. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  30205. return this.getRenderTarget();
  30206. },
  30207. getMaxAnisotropy: function () {
  30208. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  30209. return this.capabilities.getMaxAnisotropy();
  30210. },
  30211. getPrecision: function () {
  30212. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  30213. return this.capabilities.precision;
  30214. },
  30215. resetGLState: function () {
  30216. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  30217. return this.state.reset();
  30218. },
  30219. supportsFloatTextures: function () {
  30220. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  30221. return this.extensions.get( 'OES_texture_float' );
  30222. },
  30223. supportsHalfFloatTextures: function () {
  30224. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  30225. return this.extensions.get( 'OES_texture_half_float' );
  30226. },
  30227. supportsStandardDerivatives: function () {
  30228. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  30229. return this.extensions.get( 'OES_standard_derivatives' );
  30230. },
  30231. supportsCompressedTextureS3TC: function () {
  30232. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  30233. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  30234. },
  30235. supportsCompressedTexturePVRTC: function () {
  30236. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  30237. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  30238. },
  30239. supportsBlendMinMax: function () {
  30240. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  30241. return this.extensions.get( 'EXT_blend_minmax' );
  30242. },
  30243. supportsVertexTextures: function () {
  30244. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  30245. return this.capabilities.vertexTextures;
  30246. },
  30247. supportsInstancedArrays: function () {
  30248. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  30249. return this.extensions.get( 'ANGLE_instanced_arrays' );
  30250. },
  30251. enableScissorTest: function ( boolean ) {
  30252. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  30253. this.setScissorTest( boolean );
  30254. },
  30255. initMaterial: function () {
  30256. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  30257. },
  30258. addPrePlugin: function () {
  30259. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  30260. },
  30261. addPostPlugin: function () {
  30262. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  30263. },
  30264. updateShadowMap: function () {
  30265. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  30266. },
  30267. setFaceCulling: function () {
  30268. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  30269. },
  30270. allocTextureUnit: function () {
  30271. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  30272. },
  30273. setTexture: function () {
  30274. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  30275. },
  30276. setTexture2D: function () {
  30277. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  30278. },
  30279. setTextureCube: function () {
  30280. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  30281. },
  30282. getActiveMipMapLevel: function () {
  30283. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  30284. return this.getActiveMipmapLevel();
  30285. }
  30286. } );
  30287. Object.defineProperties( WebGLRenderer.prototype, {
  30288. shadowMapEnabled: {
  30289. get: function () {
  30290. return this.shadowMap.enabled;
  30291. },
  30292. set: function ( value ) {
  30293. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  30294. this.shadowMap.enabled = value;
  30295. }
  30296. },
  30297. shadowMapType: {
  30298. get: function () {
  30299. return this.shadowMap.type;
  30300. },
  30301. set: function ( value ) {
  30302. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  30303. this.shadowMap.type = value;
  30304. }
  30305. },
  30306. shadowMapCullFace: {
  30307. get: function () {
  30308. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  30309. return undefined;
  30310. },
  30311. set: function ( /* value */ ) {
  30312. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  30313. }
  30314. },
  30315. context: {
  30316. get: function () {
  30317. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  30318. return this.getContext();
  30319. }
  30320. },
  30321. vr: {
  30322. get: function () {
  30323. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  30324. return this.xr;
  30325. }
  30326. },
  30327. gammaInput: {
  30328. get: function () {
  30329. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  30330. return false;
  30331. },
  30332. set: function () {
  30333. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  30334. }
  30335. },
  30336. gammaOutput: {
  30337. get: function () {
  30338. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  30339. return false;
  30340. },
  30341. set: function ( value ) {
  30342. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  30343. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  30344. }
  30345. },
  30346. toneMappingWhitePoint: {
  30347. get: function () {
  30348. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  30349. return 1.0;
  30350. },
  30351. set: function () {
  30352. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  30353. }
  30354. },
  30355. } );
  30356. Object.defineProperties( WebGLShadowMap.prototype, {
  30357. cullFace: {
  30358. get: function () {
  30359. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  30360. return undefined;
  30361. },
  30362. set: function ( /* cullFace */ ) {
  30363. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  30364. }
  30365. },
  30366. renderReverseSided: {
  30367. get: function () {
  30368. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  30369. return undefined;
  30370. },
  30371. set: function () {
  30372. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  30373. }
  30374. },
  30375. renderSingleSided: {
  30376. get: function () {
  30377. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  30378. return undefined;
  30379. },
  30380. set: function () {
  30381. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  30382. }
  30383. }
  30384. } );
  30385. function WebGLRenderTargetCube( width, height, options ) {
  30386. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  30387. return new WebGLCubeRenderTarget( width, options );
  30388. }
  30389. //
  30390. Object.defineProperties( WebGLRenderTarget.prototype, {
  30391. wrapS: {
  30392. get: function () {
  30393. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30394. return this.texture.wrapS;
  30395. },
  30396. set: function ( value ) {
  30397. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30398. this.texture.wrapS = value;
  30399. }
  30400. },
  30401. wrapT: {
  30402. get: function () {
  30403. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30404. return this.texture.wrapT;
  30405. },
  30406. set: function ( value ) {
  30407. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30408. this.texture.wrapT = value;
  30409. }
  30410. },
  30411. magFilter: {
  30412. get: function () {
  30413. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30414. return this.texture.magFilter;
  30415. },
  30416. set: function ( value ) {
  30417. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30418. this.texture.magFilter = value;
  30419. }
  30420. },
  30421. minFilter: {
  30422. get: function () {
  30423. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30424. return this.texture.minFilter;
  30425. },
  30426. set: function ( value ) {
  30427. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30428. this.texture.minFilter = value;
  30429. }
  30430. },
  30431. anisotropy: {
  30432. get: function () {
  30433. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30434. return this.texture.anisotropy;
  30435. },
  30436. set: function ( value ) {
  30437. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30438. this.texture.anisotropy = value;
  30439. }
  30440. },
  30441. offset: {
  30442. get: function () {
  30443. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30444. return this.texture.offset;
  30445. },
  30446. set: function ( value ) {
  30447. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30448. this.texture.offset = value;
  30449. }
  30450. },
  30451. repeat: {
  30452. get: function () {
  30453. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30454. return this.texture.repeat;
  30455. },
  30456. set: function ( value ) {
  30457. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30458. this.texture.repeat = value;
  30459. }
  30460. },
  30461. format: {
  30462. get: function () {
  30463. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30464. return this.texture.format;
  30465. },
  30466. set: function ( value ) {
  30467. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30468. this.texture.format = value;
  30469. }
  30470. },
  30471. type: {
  30472. get: function () {
  30473. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30474. return this.texture.type;
  30475. },
  30476. set: function ( value ) {
  30477. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30478. this.texture.type = value;
  30479. }
  30480. },
  30481. generateMipmaps: {
  30482. get: function () {
  30483. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30484. return this.texture.generateMipmaps;
  30485. },
  30486. set: function ( value ) {
  30487. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30488. this.texture.generateMipmaps = value;
  30489. }
  30490. }
  30491. } );
  30492. //
  30493. Object.defineProperties( Audio.prototype, {
  30494. load: {
  30495. value: function ( file ) {
  30496. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  30497. const scope = this;
  30498. const audioLoader = new AudioLoader();
  30499. audioLoader.load( file, function ( buffer ) {
  30500. scope.setBuffer( buffer );
  30501. } );
  30502. return this;
  30503. }
  30504. },
  30505. startTime: {
  30506. set: function () {
  30507. console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
  30508. }
  30509. }
  30510. } );
  30511. AudioAnalyser.prototype.getData = function () {
  30512. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  30513. return this.getFrequencyData();
  30514. };
  30515. //
  30516. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  30517. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  30518. return this.update( renderer, scene );
  30519. };
  30520. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  30521. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  30522. return this.renderTarget.clear( renderer, color, depth, stencil );
  30523. };
  30524. //
  30525. const GeometryUtils = {
  30526. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  30527. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  30528. let matrix;
  30529. if ( geometry2.isMesh ) {
  30530. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30531. matrix = geometry2.matrix;
  30532. geometry2 = geometry2.geometry;
  30533. }
  30534. geometry1.merge( geometry2, matrix, materialIndexOffset );
  30535. },
  30536. center: function ( geometry ) {
  30537. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  30538. return geometry.center();
  30539. }
  30540. };
  30541. ImageUtils.crossOrigin = undefined;
  30542. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  30543. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  30544. const loader = new TextureLoader();
  30545. loader.setCrossOrigin( this.crossOrigin );
  30546. const texture = loader.load( url, onLoad, undefined, onError );
  30547. if ( mapping ) texture.mapping = mapping;
  30548. return texture;
  30549. };
  30550. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  30551. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  30552. const loader = new CubeTextureLoader();
  30553. loader.setCrossOrigin( this.crossOrigin );
  30554. const texture = loader.load( urls, onLoad, undefined, onError );
  30555. if ( mapping ) texture.mapping = mapping;
  30556. return texture;
  30557. };
  30558. ImageUtils.loadCompressedTexture = function () {
  30559. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  30560. };
  30561. ImageUtils.loadCompressedTextureCube = function () {
  30562. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  30563. };
  30564. //
  30565. function CanvasRenderer() {
  30566. console.error( 'THREE.CanvasRenderer has been removed' );
  30567. }
  30568. //
  30569. function JSONLoader() {
  30570. console.error( 'THREE.JSONLoader has been removed.' );
  30571. }
  30572. //
  30573. const SceneUtils = {
  30574. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  30575. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30576. },
  30577. detach: function ( /* child, parent, scene */ ) {
  30578. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30579. },
  30580. attach: function ( /* child, scene, parent */ ) {
  30581. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  30582. }
  30583. };
  30584. //
  30585. function LensFlare() {
  30586. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  30587. }
  30588. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30589. /* eslint-disable no-undef */
  30590. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30591. revision: REVISION,
  30592. } } ) );
  30593. /* eslint-enable no-undef */
  30594. }
  30595. var THREE$1 = /*#__PURE__*/Object.freeze({
  30596. __proto__: null,
  30597. ACESFilmicToneMapping: ACESFilmicToneMapping,
  30598. AddEquation: AddEquation,
  30599. AddOperation: AddOperation,
  30600. AdditiveAnimationBlendMode: AdditiveAnimationBlendMode,
  30601. AdditiveBlending: AdditiveBlending,
  30602. AlphaFormat: AlphaFormat,
  30603. AlwaysDepth: AlwaysDepth,
  30604. AlwaysStencilFunc: AlwaysStencilFunc,
  30605. AmbientLight: AmbientLight,
  30606. AmbientLightProbe: AmbientLightProbe,
  30607. AnimationClip: AnimationClip,
  30608. AnimationLoader: AnimationLoader,
  30609. AnimationMixer: AnimationMixer,
  30610. AnimationObjectGroup: AnimationObjectGroup,
  30611. AnimationUtils: AnimationUtils,
  30612. ArcCurve: ArcCurve,
  30613. ArrayCamera: ArrayCamera,
  30614. ArrowHelper: ArrowHelper,
  30615. Audio: Audio,
  30616. AudioAnalyser: AudioAnalyser,
  30617. AudioContext: AudioContext,
  30618. AudioListener: AudioListener,
  30619. AudioLoader: AudioLoader,
  30620. AxesHelper: AxesHelper,
  30621. AxisHelper: AxisHelper,
  30622. BackSide: BackSide,
  30623. BasicDepthPacking: BasicDepthPacking,
  30624. BasicShadowMap: BasicShadowMap,
  30625. BinaryTextureLoader: BinaryTextureLoader,
  30626. Bone: Bone,
  30627. BooleanKeyframeTrack: BooleanKeyframeTrack,
  30628. BoundingBoxHelper: BoundingBoxHelper,
  30629. Box2: Box2,
  30630. Box3: Box3,
  30631. Box3Helper: Box3Helper,
  30632. BoxBufferGeometry: BoxBufferGeometry,
  30633. BoxGeometry: BoxGeometry,
  30634. BoxHelper: BoxHelper,
  30635. BufferAttribute: BufferAttribute,
  30636. BufferGeometry: BufferGeometry,
  30637. BufferGeometryLoader: BufferGeometryLoader,
  30638. ByteType: ByteType,
  30639. Cache: Cache,
  30640. Camera: Camera,
  30641. CameraHelper: CameraHelper,
  30642. CanvasRenderer: CanvasRenderer,
  30643. CanvasTexture: CanvasTexture,
  30644. CatmullRomCurve3: CatmullRomCurve3,
  30645. CineonToneMapping: CineonToneMapping,
  30646. CircleBufferGeometry: CircleBufferGeometry,
  30647. CircleGeometry: CircleGeometry,
  30648. ClampToEdgeWrapping: ClampToEdgeWrapping,
  30649. Clock: Clock,
  30650. ClosedSplineCurve3: ClosedSplineCurve3,
  30651. Color: Color,
  30652. ColorKeyframeTrack: ColorKeyframeTrack,
  30653. CompressedTexture: CompressedTexture,
  30654. CompressedTextureLoader: CompressedTextureLoader,
  30655. ConeBufferGeometry: ConeBufferGeometry,
  30656. ConeGeometry: ConeGeometry,
  30657. CubeCamera: CubeCamera,
  30658. CubeGeometry: BoxGeometry,
  30659. CubeReflectionMapping: CubeReflectionMapping,
  30660. CubeRefractionMapping: CubeRefractionMapping,
  30661. CubeTexture: CubeTexture,
  30662. CubeTextureLoader: CubeTextureLoader,
  30663. CubeUVReflectionMapping: CubeUVReflectionMapping,
  30664. CubeUVRefractionMapping: CubeUVRefractionMapping,
  30665. CubicBezierCurve: CubicBezierCurve,
  30666. CubicBezierCurve3: CubicBezierCurve3,
  30667. CubicInterpolant: CubicInterpolant,
  30668. CullFaceBack: CullFaceBack,
  30669. CullFaceFront: CullFaceFront,
  30670. CullFaceFrontBack: CullFaceFrontBack,
  30671. CullFaceNone: CullFaceNone,
  30672. Curve: Curve,
  30673. CurvePath: CurvePath,
  30674. CustomBlending: CustomBlending,
  30675. CustomToneMapping: CustomToneMapping,
  30676. CylinderBufferGeometry: CylinderBufferGeometry,
  30677. CylinderGeometry: CylinderGeometry,
  30678. Cylindrical: Cylindrical,
  30679. DataTexture: DataTexture,
  30680. DataTexture2DArray: DataTexture2DArray,
  30681. DataTexture3D: DataTexture3D,
  30682. DataTextureLoader: DataTextureLoader,
  30683. DataUtils: DataUtils,
  30684. DecrementStencilOp: DecrementStencilOp,
  30685. DecrementWrapStencilOp: DecrementWrapStencilOp,
  30686. DefaultLoadingManager: DefaultLoadingManager,
  30687. DepthFormat: DepthFormat,
  30688. DepthStencilFormat: DepthStencilFormat,
  30689. DepthTexture: DepthTexture,
  30690. DirectionalLight: DirectionalLight,
  30691. DirectionalLightHelper: DirectionalLightHelper,
  30692. DiscreteInterpolant: DiscreteInterpolant,
  30693. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  30694. DodecahedronGeometry: DodecahedronGeometry,
  30695. DoubleSide: DoubleSide,
  30696. DstAlphaFactor: DstAlphaFactor,
  30697. DstColorFactor: DstColorFactor,
  30698. DynamicBufferAttribute: DynamicBufferAttribute,
  30699. DynamicCopyUsage: DynamicCopyUsage,
  30700. DynamicDrawUsage: DynamicDrawUsage,
  30701. DynamicReadUsage: DynamicReadUsage,
  30702. EdgesGeometry: EdgesGeometry,
  30703. EdgesHelper: EdgesHelper,
  30704. EllipseCurve: EllipseCurve,
  30705. EqualDepth: EqualDepth,
  30706. EqualStencilFunc: EqualStencilFunc,
  30707. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  30708. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  30709. Euler: Euler,
  30710. EventDispatcher: EventDispatcher,
  30711. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  30712. ExtrudeGeometry: ExtrudeGeometry,
  30713. Face3: Face3,
  30714. Face4: Face4,
  30715. FaceColors: FaceColors,
  30716. FileLoader: FileLoader,
  30717. FlatShading: FlatShading$1,
  30718. Float16BufferAttribute: Float16BufferAttribute,
  30719. Float32Attribute: Float32Attribute,
  30720. Float32BufferAttribute: Float32BufferAttribute,
  30721. Float64Attribute: Float64Attribute,
  30722. Float64BufferAttribute: Float64BufferAttribute,
  30723. FloatType: FloatType,
  30724. Fog: Fog,
  30725. FogExp2: FogExp2,
  30726. Font: Font,
  30727. FontLoader: FontLoader,
  30728. FrontSide: FrontSide,
  30729. Frustum: Frustum,
  30730. GLBufferAttribute: GLBufferAttribute,
  30731. GLSL1: GLSL1,
  30732. GLSL3: GLSL3,
  30733. GammaEncoding: GammaEncoding,
  30734. Geometry: Geometry,
  30735. GeometryUtils: GeometryUtils,
  30736. GreaterDepth: GreaterDepth,
  30737. GreaterEqualDepth: GreaterEqualDepth,
  30738. GreaterEqualStencilFunc: GreaterEqualStencilFunc,
  30739. GreaterStencilFunc: GreaterStencilFunc,
  30740. GridHelper: GridHelper,
  30741. Group: Group,
  30742. HalfFloatType: HalfFloatType,
  30743. HemisphereLight: HemisphereLight,
  30744. HemisphereLightHelper: HemisphereLightHelper,
  30745. HemisphereLightProbe: HemisphereLightProbe,
  30746. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  30747. IcosahedronGeometry: IcosahedronGeometry,
  30748. ImageBitmapLoader: ImageBitmapLoader,
  30749. ImageLoader: ImageLoader,
  30750. ImageUtils: ImageUtils,
  30751. ImmediateRenderObject: ImmediateRenderObject,
  30752. IncrementStencilOp: IncrementStencilOp,
  30753. IncrementWrapStencilOp: IncrementWrapStencilOp,
  30754. InstancedBufferAttribute: InstancedBufferAttribute,
  30755. InstancedBufferGeometry: InstancedBufferGeometry,
  30756. InstancedInterleavedBuffer: InstancedInterleavedBuffer,
  30757. InstancedMesh: InstancedMesh,
  30758. Int16Attribute: Int16Attribute,
  30759. Int16BufferAttribute: Int16BufferAttribute,
  30760. Int32Attribute: Int32Attribute,
  30761. Int32BufferAttribute: Int32BufferAttribute,
  30762. Int8Attribute: Int8Attribute,
  30763. Int8BufferAttribute: Int8BufferAttribute,
  30764. IntType: IntType,
  30765. InterleavedBuffer: InterleavedBuffer,
  30766. InterleavedBufferAttribute: InterleavedBufferAttribute,
  30767. Interpolant: Interpolant,
  30768. InterpolateDiscrete: InterpolateDiscrete,
  30769. InterpolateLinear: InterpolateLinear,
  30770. InterpolateSmooth: InterpolateSmooth,
  30771. InvertStencilOp: InvertStencilOp,
  30772. JSONLoader: JSONLoader,
  30773. KeepStencilOp: KeepStencilOp,
  30774. KeyframeTrack: KeyframeTrack,
  30775. LOD: LOD,
  30776. LatheBufferGeometry: LatheBufferGeometry,
  30777. LatheGeometry: LatheGeometry,
  30778. Layers: Layers,
  30779. LensFlare: LensFlare,
  30780. LessDepth: LessDepth,
  30781. LessEqualDepth: LessEqualDepth,
  30782. LessEqualStencilFunc: LessEqualStencilFunc,
  30783. LessStencilFunc: LessStencilFunc,
  30784. Light: Light,
  30785. LightProbe: LightProbe,
  30786. Line: Line,
  30787. Line3: Line3,
  30788. LineBasicMaterial: LineBasicMaterial,
  30789. LineCurve: LineCurve,
  30790. LineCurve3: LineCurve3,
  30791. LineDashedMaterial: LineDashedMaterial,
  30792. LineLoop: LineLoop,
  30793. LinePieces: LinePieces,
  30794. LineSegments: LineSegments,
  30795. LineStrip: LineStrip,
  30796. LinearEncoding: LinearEncoding,
  30797. LinearFilter: LinearFilter,
  30798. LinearInterpolant: LinearInterpolant,
  30799. LinearMipMapLinearFilter: LinearMipMapLinearFilter,
  30800. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  30801. LinearMipmapLinearFilter: LinearMipmapLinearFilter,
  30802. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  30803. LinearToneMapping: LinearToneMapping,
  30804. Loader: Loader,
  30805. LoaderUtils: LoaderUtils,
  30806. LoadingManager: LoadingManager,
  30807. LogLuvEncoding: LogLuvEncoding,
  30808. LoopOnce: LoopOnce,
  30809. LoopPingPong: LoopPingPong,
  30810. LoopRepeat: LoopRepeat,
  30811. LuminanceAlphaFormat: LuminanceAlphaFormat,
  30812. LuminanceFormat: LuminanceFormat,
  30813. MOUSE: MOUSE,
  30814. Material: Material,
  30815. MaterialLoader: MaterialLoader,
  30816. Math: MathUtils,
  30817. MathUtils: MathUtils,
  30818. Matrix3: Matrix3,
  30819. Matrix4: Matrix4,
  30820. MaxEquation: MaxEquation,
  30821. Mesh: Mesh,
  30822. MeshBasicMaterial: MeshBasicMaterial,
  30823. MeshDepthMaterial: MeshDepthMaterial,
  30824. MeshDistanceMaterial: MeshDistanceMaterial,
  30825. MeshFaceMaterial: MeshFaceMaterial,
  30826. MeshLambertMaterial: MeshLambertMaterial,
  30827. MeshMatcapMaterial: MeshMatcapMaterial,
  30828. MeshNormalMaterial: MeshNormalMaterial,
  30829. MeshPhongMaterial: MeshPhongMaterial,
  30830. MeshPhysicalMaterial: MeshPhysicalMaterial,
  30831. MeshStandardMaterial: MeshStandardMaterial,
  30832. MeshToonMaterial: MeshToonMaterial,
  30833. MinEquation: MinEquation,
  30834. MirroredRepeatWrapping: MirroredRepeatWrapping,
  30835. MixOperation: MixOperation,
  30836. MultiMaterial: MultiMaterial,
  30837. MultiplyBlending: MultiplyBlending,
  30838. MultiplyOperation: MultiplyOperation,
  30839. NearestFilter: NearestFilter,
  30840. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  30841. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  30842. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  30843. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  30844. NeverDepth: NeverDepth,
  30845. NeverStencilFunc: NeverStencilFunc,
  30846. NoBlending: NoBlending,
  30847. NoColors: NoColors,
  30848. NoToneMapping: NoToneMapping,
  30849. NormalAnimationBlendMode: NormalAnimationBlendMode,
  30850. NormalBlending: NormalBlending,
  30851. NotEqualDepth: NotEqualDepth,
  30852. NotEqualStencilFunc: NotEqualStencilFunc,
  30853. NumberKeyframeTrack: NumberKeyframeTrack,
  30854. Object3D: Object3D,
  30855. ObjectLoader: ObjectLoader,
  30856. ObjectSpaceNormalMap: ObjectSpaceNormalMap,
  30857. OctahedronBufferGeometry: OctahedronBufferGeometry,
  30858. OctahedronGeometry: OctahedronGeometry,
  30859. OneFactor: OneFactor,
  30860. OneMinusDstAlphaFactor: OneMinusDstAlphaFactor,
  30861. OneMinusDstColorFactor: OneMinusDstColorFactor,
  30862. OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor,
  30863. OneMinusSrcColorFactor: OneMinusSrcColorFactor,
  30864. OrthographicCamera: OrthographicCamera,
  30865. PCFShadowMap: PCFShadowMap,
  30866. PCFSoftShadowMap: PCFSoftShadowMap,
  30867. PMREMGenerator: PMREMGenerator,
  30868. ParametricBufferGeometry: ParametricBufferGeometry,
  30869. ParametricGeometry: ParametricGeometry,
  30870. Particle: Particle,
  30871. ParticleBasicMaterial: ParticleBasicMaterial,
  30872. ParticleSystem: ParticleSystem,
  30873. ParticleSystemMaterial: ParticleSystemMaterial,
  30874. Path: Path,
  30875. PerspectiveCamera: PerspectiveCamera,
  30876. Plane: Plane,
  30877. PlaneBufferGeometry: PlaneBufferGeometry,
  30878. PlaneGeometry: PlaneGeometry,
  30879. PlaneHelper: PlaneHelper,
  30880. PointCloud: PointCloud,
  30881. PointCloudMaterial: PointCloudMaterial,
  30882. PointLight: PointLight,
  30883. PointLightHelper: PointLightHelper,
  30884. Points: Points,
  30885. PointsMaterial: PointsMaterial,
  30886. PolarGridHelper: PolarGridHelper,
  30887. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  30888. PolyhedronGeometry: PolyhedronGeometry,
  30889. PositionalAudio: PositionalAudio,
  30890. PropertyBinding: PropertyBinding,
  30891. PropertyMixer: PropertyMixer,
  30892. QuadraticBezierCurve: QuadraticBezierCurve,
  30893. QuadraticBezierCurve3: QuadraticBezierCurve3,
  30894. Quaternion: Quaternion,
  30895. QuaternionKeyframeTrack: QuaternionKeyframeTrack,
  30896. QuaternionLinearInterpolant: QuaternionLinearInterpolant,
  30897. REVISION: REVISION,
  30898. RGBADepthPacking: RGBADepthPacking,
  30899. RGBAFormat: RGBAFormat,
  30900. RGBAIntegerFormat: RGBAIntegerFormat,
  30901. RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format,
  30902. RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format,
  30903. RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format,
  30904. RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format,
  30905. RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format,
  30906. RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format,
  30907. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  30908. RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format,
  30909. RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format,
  30910. RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format,
  30911. RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format,
  30912. RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format,
  30913. RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format,
  30914. RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format,
  30915. RGBA_BPTC_Format: RGBA_BPTC_Format,
  30916. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  30917. RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format,
  30918. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  30919. RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format$1,
  30920. RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format,
  30921. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  30922. RGBDEncoding: RGBDEncoding,
  30923. RGBEEncoding: RGBEEncoding,
  30924. RGBEFormat: RGBEFormat,
  30925. RGBFormat: RGBFormat,
  30926. RGBIntegerFormat: RGBIntegerFormat,
  30927. RGBM16Encoding: RGBM16Encoding,
  30928. RGBM7Encoding: RGBM7Encoding,
  30929. RGB_ETC1_Format: RGB_ETC1_Format,
  30930. RGB_ETC2_Format: RGB_ETC2_Format,
  30931. RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format,
  30932. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  30933. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  30934. RGFormat: RGFormat,
  30935. RGIntegerFormat: RGIntegerFormat,
  30936. RawShaderMaterial: RawShaderMaterial,
  30937. Ray: Ray,
  30938. Raycaster: Raycaster,
  30939. RectAreaLight: RectAreaLight,
  30940. RedFormat: RedFormat,
  30941. RedIntegerFormat: RedIntegerFormat,
  30942. ReinhardToneMapping: ReinhardToneMapping,
  30943. RepeatWrapping: RepeatWrapping,
  30944. ReplaceStencilOp: ReplaceStencilOp,
  30945. ReverseSubtractEquation: ReverseSubtractEquation,
  30946. RingBufferGeometry: RingBufferGeometry,
  30947. RingGeometry: RingGeometry,
  30948. SRGB8_ALPHA8_ASTC_10x10_Format: SRGB8_ALPHA8_ASTC_10x10_Format,
  30949. SRGB8_ALPHA8_ASTC_10x5_Format: SRGB8_ALPHA8_ASTC_10x5_Format,
  30950. SRGB8_ALPHA8_ASTC_10x6_Format: SRGB8_ALPHA8_ASTC_10x6_Format,
  30951. SRGB8_ALPHA8_ASTC_10x8_Format: SRGB8_ALPHA8_ASTC_10x8_Format,
  30952. SRGB8_ALPHA8_ASTC_12x10_Format: SRGB8_ALPHA8_ASTC_12x10_Format,
  30953. SRGB8_ALPHA8_ASTC_12x12_Format: SRGB8_ALPHA8_ASTC_12x12_Format,
  30954. SRGB8_ALPHA8_ASTC_4x4_Format: SRGB8_ALPHA8_ASTC_4x4_Format,
  30955. SRGB8_ALPHA8_ASTC_5x4_Format: SRGB8_ALPHA8_ASTC_5x4_Format,
  30956. SRGB8_ALPHA8_ASTC_5x5_Format: SRGB8_ALPHA8_ASTC_5x5_Format,
  30957. SRGB8_ALPHA8_ASTC_6x5_Format: SRGB8_ALPHA8_ASTC_6x5_Format,
  30958. SRGB8_ALPHA8_ASTC_6x6_Format: SRGB8_ALPHA8_ASTC_6x6_Format,
  30959. SRGB8_ALPHA8_ASTC_8x5_Format: SRGB8_ALPHA8_ASTC_8x5_Format,
  30960. SRGB8_ALPHA8_ASTC_8x6_Format: SRGB8_ALPHA8_ASTC_8x6_Format,
  30961. SRGB8_ALPHA8_ASTC_8x8_Format: SRGB8_ALPHA8_ASTC_8x8_Format,
  30962. Scene: Scene,
  30963. SceneUtils: SceneUtils,
  30964. ShaderChunk: ShaderChunk,
  30965. ShaderLib: ShaderLib,
  30966. ShaderMaterial: ShaderMaterial,
  30967. ShadowMaterial: ShadowMaterial,
  30968. Shape: Shape,
  30969. ShapeBufferGeometry: ShapeBufferGeometry,
  30970. ShapeGeometry: ShapeGeometry,
  30971. ShapePath: ShapePath,
  30972. ShapeUtils: ShapeUtils,
  30973. ShortType: ShortType,
  30974. Skeleton: Skeleton,
  30975. SkeletonHelper: SkeletonHelper,
  30976. SkinnedMesh: SkinnedMesh,
  30977. SmoothShading: SmoothShading,
  30978. Sphere: Sphere,
  30979. SphereBufferGeometry: SphereBufferGeometry,
  30980. SphereGeometry: SphereGeometry,
  30981. Spherical: Spherical,
  30982. SphericalHarmonics3: SphericalHarmonics3,
  30983. Spline: Spline,
  30984. SplineCurve: SplineCurve,
  30985. SplineCurve3: SplineCurve3,
  30986. SpotLight: SpotLight,
  30987. SpotLightHelper: SpotLightHelper,
  30988. Sprite: Sprite$1,
  30989. SpriteMaterial: SpriteMaterial,
  30990. SrcAlphaFactor: SrcAlphaFactor,
  30991. SrcAlphaSaturateFactor: SrcAlphaSaturateFactor,
  30992. SrcColorFactor: SrcColorFactor,
  30993. StaticCopyUsage: StaticCopyUsage,
  30994. StaticDrawUsage: StaticDrawUsage,
  30995. StaticReadUsage: StaticReadUsage,
  30996. StereoCamera: StereoCamera,
  30997. StreamCopyUsage: StreamCopyUsage,
  30998. StreamDrawUsage: StreamDrawUsage,
  30999. StreamReadUsage: StreamReadUsage,
  31000. StringKeyframeTrack: StringKeyframeTrack,
  31001. SubtractEquation: SubtractEquation,
  31002. SubtractiveBlending: SubtractiveBlending,
  31003. TOUCH: TOUCH,
  31004. TangentSpaceNormalMap: TangentSpaceNormalMap,
  31005. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  31006. TetrahedronGeometry: TetrahedronGeometry,
  31007. TextBufferGeometry: TextBufferGeometry,
  31008. TextGeometry: TextGeometry,
  31009. Texture: Texture,
  31010. TextureLoader: TextureLoader,
  31011. TorusBufferGeometry: TorusBufferGeometry,
  31012. TorusGeometry: TorusGeometry,
  31013. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  31014. TorusKnotGeometry: TorusKnotGeometry,
  31015. Triangle: Triangle,
  31016. TriangleFanDrawMode: TriangleFanDrawMode,
  31017. TriangleStripDrawMode: TriangleStripDrawMode,
  31018. TrianglesDrawMode: TrianglesDrawMode,
  31019. TubeBufferGeometry: TubeBufferGeometry,
  31020. TubeGeometry: TubeGeometry,
  31021. UVMapping: UVMapping,
  31022. Uint16Attribute: Uint16Attribute,
  31023. Uint16BufferAttribute: Uint16BufferAttribute,
  31024. Uint32Attribute: Uint32Attribute,
  31025. Uint32BufferAttribute: Uint32BufferAttribute,
  31026. Uint8Attribute: Uint8Attribute,
  31027. Uint8BufferAttribute: Uint8BufferAttribute,
  31028. Uint8ClampedAttribute: Uint8ClampedAttribute,
  31029. Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute,
  31030. Uniform: Uniform,
  31031. UniformsLib: UniformsLib,
  31032. UniformsUtils: UniformsUtils,
  31033. UnsignedByteType: UnsignedByteType,
  31034. UnsignedInt248Type: UnsignedInt248Type$1,
  31035. UnsignedIntType: UnsignedIntType,
  31036. UnsignedShort4444Type: UnsignedShort4444Type,
  31037. UnsignedShort5551Type: UnsignedShort5551Type,
  31038. UnsignedShort565Type: UnsignedShort565Type,
  31039. UnsignedShortType: UnsignedShortType,
  31040. VSMShadowMap: VSMShadowMap,
  31041. Vector2: Vector2,
  31042. Vector3: Vector3,
  31043. Vector4: Vector4,
  31044. VectorKeyframeTrack: VectorKeyframeTrack,
  31045. Vertex: Vertex,
  31046. VertexColors: VertexColors,
  31047. VideoTexture: VideoTexture,
  31048. WebGL1Renderer: WebGL1Renderer,
  31049. WebGLCubeRenderTarget: WebGLCubeRenderTarget,
  31050. WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget,
  31051. WebGLRenderTarget: WebGLRenderTarget,
  31052. WebGLRenderTargetCube: WebGLRenderTargetCube,
  31053. WebGLRenderer: WebGLRenderer,
  31054. WebGLUtils: WebGLUtils,
  31055. WireframeGeometry: WireframeGeometry,
  31056. WireframeHelper: WireframeHelper,
  31057. WrapAroundEnding: WrapAroundEnding,
  31058. XHRLoader: XHRLoader,
  31059. ZeroCurvatureEnding: ZeroCurvatureEnding,
  31060. ZeroFactor: ZeroFactor,
  31061. ZeroSlopeEnding: ZeroSlopeEnding,
  31062. ZeroStencilOp: ZeroStencilOp,
  31063. sRGBEncoding: sRGBEncoding
  31064. });
  31065. var points = [];
  31066. var lines = [];
  31067. var rings = [];
  31068. var precision = 0.1; //容错精度 //正常是0.01 但是在编辑时容易出现交错的线看不出来,导致需要getSliceLines 然后多出新增点
  31069. var getPoint = function(o, type){
  31070. var point;
  31071. if(typeof o == "string" || typeof o == "number")point = points.find(p=> p.ids.includes(o));
  31072. else {
  31073. point = points.find(p=> math.closeTo(p.x , o.x, precision) && math.closeTo(p.y , o.y, precision) );
  31074. if(!point) point = new Point(o.x, o.y,{record:true, id:o.id}, type);
  31075. else {
  31076. //console.log('addPoint', point, o)
  31077. point.addPoint(o.id);
  31078. }
  31079. }
  31080. if(!point){
  31081. console.log("no point!");
  31082. }
  31083. return point
  31084. };
  31085. var getLine = function(id){
  31086. return lines.find(line=> line.ids.includes(id));
  31087. };
  31088. var getAngleInfo = function(points){
  31089. var info = {};
  31090. info.angle = points[1].clone().sub(points[0]).angle();
  31091. if(math.closeTo(info.angle, Math.PI*2)){ //如360-0.01
  31092. info.angle -= Math.PI*2; //有可能得到负数-0.001
  31093. }else if(info.angle > Math.PI || math.closeTo(info.angle, Math.PI)){//如180+-0.01
  31094. info.angle -= Math.PI;
  31095. info.reverse = true;
  31096. }
  31097. return info //结果大约是 0 - 3.14
  31098. };
  31099. class Point extends Vector2{
  31100. constructor(x, y, o={}){
  31101. super(x, y);
  31102. if(o.record){
  31103. this.id = o.id;
  31104. if(this.id == void 0) this.id = "add_"+points.length;
  31105. this.ids = [this.id] ;//存储拥有该坐标的点原始数据的id
  31106. points.push(this);
  31107. }
  31108. this.type = o.type || "";
  31109. this.lines = [];
  31110. }
  31111. addPoint(id){
  31112. this.ids.push(id);
  31113. }
  31114. searchLineByFactor(dir, type, comeLine){
  31115. var lines = this.lines.filter(line=>line.searchTime<2);
  31116. if(lines.length==0)return;
  31117. else if(lines.length==1)return lines[0];
  31118. else lines = lines.filter(line=>line!=comeLine);
  31119. if(lines.length==1)return lines[0];
  31120. var result;
  31121. lines.forEach(line=>{
  31122. var vec = line.getVector();
  31123. if(line.points[1] == this) vec.negate();
  31124. var factor = math.getVec2Angle(dir, vec);
  31125. if(new Vector3(dir.x, dir.y, 0).cross(new Vector3(vec.x, vec.y, 0)).z<0) factor*= -1; /////
  31126. if(!result){
  31127. result = {line, factor};
  31128. }
  31129. else {
  31130. if(type == "min" && factor<result.factor || type == "max" && factor>result.factor) result = {line, factor};
  31131. }
  31132. });
  31133. return result.line;
  31134. }
  31135. }
  31136. var lineLen=0;
  31137. class Line$1{
  31138. constructor(o){
  31139. if(o.points[0] == o.points[1])return;
  31140. this.points = o.points;
  31141. this.type = o.type || 'line';
  31142. if(this.type == 'line'){
  31143. var oldLine = lines.find(line=>line.points.includes(o.points[0]) && line.points.includes(o.points[1]));
  31144. if(oldLine){
  31145. o.id != void 0 && oldLine.ids.push(o.id);
  31146. return oldLine;
  31147. }
  31148. this.id = o.id == void 0 ? ("line"+lineLen ++) : o.id;
  31149. this.ids = [this.id];
  31150. o.dontWriteToPoint || this.points.forEach((point)=>{point.lines.push(this);});
  31151. o.isChild || lines.push(this);
  31152. this.searchTime = 0; // 最多两次
  31153. }
  31154. this.children = [];//分割
  31155. this.parents = [];//分割
  31156. this.match = [];
  31157. }
  31158. getAngleInfo(){
  31159. var angleInfo = getAngleInfo(this.points);
  31160. this.angle = angleInfo.angle;
  31161. this.reverse = angleInfo.reverse;
  31162. }
  31163. getIntersectWithLine(line, precision){
  31164. var joint = line.points.find(point=>this.points.includes(point));
  31165. if(joint)return {point:joint, type:"joint"};
  31166. var intersect = math.isLineIntersect( line.points , this.points , false, precision );
  31167. if(intersect) return {point: intersect, type:"intersect"};
  31168. }
  31169. writeToPoint(){
  31170. this.points.forEach((point)=>{point.lines.includes(this) || point.lines.push(this);});
  31171. }
  31172. checkIfParent(line){
  31173. if(this == line){
  31174. return true;//原因就是slice的点和端点很近 误差导致
  31175. }
  31176. else return this.parents.find(e=>e.checkIfParent(line))
  31177. }
  31178. splitByPoint(point){
  31179. var line1 = new Line$1({points:[point, this.points[0]], dontWriteToPoint:true, hasntsure:true});
  31180. var line2 = new Line$1({points:[point, this.points[1]], dontWriteToPoint:true, hasntsure:true});
  31181. if(!line1.points || !line2.points){//有至少一个是点相同的,没写到group.lines里
  31182. console.warn('splitByPoint 线有点相同');
  31183. return;
  31184. }
  31185. if(this.checkIfParent(line1)||this.checkIfParent(line2) || line1.checkIfParent(this) || line2.checkIfParent(this)){
  31186. console.warn("splitByPoint 发现parent和children一样");//,请检查getSliceWalls,尤其 if(math.closeTo(line1.angle,line2.angle)){ 处
  31187. return;
  31188. }
  31189. var deal = (line)=>{
  31190. this.children.push(line);
  31191. line.parents.push(this);
  31192. if(!lines.includes(line))lines.push(line);
  31193. line.writeToPoint();
  31194. };
  31195. deal(line1);
  31196. deal(line2);
  31197. var index = this.points[0].lines.indexOf(this);
  31198. index > -1 && this.points[0].lines.splice(index,1);
  31199. var index = this.points[1].lines.indexOf(this);
  31200. index > -1 && this.points[1].lines.splice(index,1);
  31201. return [line1,line2]
  31202. }
  31203. splitByPoints(points){
  31204. points = points.map(point=>{return {dis:point.distanceTo(this.points[0]), point:point}});
  31205. points.sort((point1, point2)=>{return point1.dis - point2.dis});
  31206. var children = [];
  31207. points.forEach((point, index)=>{
  31208. var line1 = new Line$1({points:[point.point, index==0?this.points[0]:points[index-1].point ],group:this.group , dontWriteToPoint:true, hasntsure:true});
  31209. children.push(line1);
  31210. });
  31211. var line2 = new Line$1({points:[points[points.length-1].point, this.points[1] ],group:this.group , dontWriteToPoint:true, hasntsure:true});
  31212. children.push(line2);
  31213. var a = children.find(line=> !line.points || this.checkIfParent(line) || line.checkIfParent(this));
  31214. if(a){
  31215. console.error("splitByPoints return");
  31216. return;
  31217. }
  31218. children.forEach(line=>{
  31219. this.children.push(line);
  31220. line.parents.push(this);
  31221. if(!lines.includes(line))lines.push(line);
  31222. line.writeToPoint();
  31223. line.writeToPoint();
  31224. });
  31225. var index = this.points[0].lines.indexOf(this);
  31226. index > -1 && this.points[0].lines.splice(index,1);
  31227. var index = this.points[1].lines.indexOf(this);
  31228. index > -1 && this.points[1].lines.splice(index,1);
  31229. }
  31230. getAllSlices(){//如果有被分割的片段 就返回片段,否则返回自身
  31231. var children = [];
  31232. var traverse = function(elem){
  31233. if(elem.children.length == 0) children.push(elem);
  31234. else elem.children.forEach(traverse);
  31235. };
  31236. traverse(this);
  31237. return children
  31238. }
  31239. getVector(){
  31240. return this.points[1].clone().sub(this.points[0]);
  31241. }
  31242. getLength(){
  31243. return this.points[0].distanceTo(this.points[1])
  31244. }
  31245. getCenter(){
  31246. return this.points[1].clone().add(this.points[0]).multiplyScalar(.5);
  31247. }
  31248. }
  31249. var getMixedSet = function(arr1, arr2){//交集
  31250. return arr1.filter(item=>arr2.includes(item));
  31251. };
  31252. var getUnionSet = function(arr1, arr2){//并集
  31253. return arr1.concat(arr2.filter(item=>!arr1.includes(item)))
  31254. };
  31255. var getDifferenceSet = function(arr1, arr2){//差集
  31256. var arr11 = arr1.filter(item=>!arr2.includes(item));
  31257. var arr22 = arr2.filter(item=>!arr1.includes(item));
  31258. return arr11.concat(arr22)
  31259. };
  31260. var getDifferenceSetMuti = function(arr){//收集绝对没有重复的元素,也就是判断出现次数=1的
  31261. var set = [];
  31262. arr.forEach(arr1=>{
  31263. arr1.forEach(item=>{
  31264. var index = set.indexOf(item);
  31265. if(index>-1){
  31266. set.splice(index, 1);
  31267. }else {
  31268. set.push(item);
  31269. }
  31270. });
  31271. });
  31272. return set;
  31273. };
  31274. function DoorAtWhichLine(points, lines){
  31275. var mid = points[0].clone().add(points[1]).multiplyScalar(0.5);
  31276. lines = lines.filter(line=>math.ifPointAtLineBound(mid, line.points, precision));
  31277. if(lines.length == 0)return
  31278. var result = {line:null, dis:Infinity};
  31279. lines.forEach(line=>{
  31280. var foot = math.getFootPoint(mid, line.points[0], line.points[1] );
  31281. var dis = foot.distanceTo(mid);
  31282. if(dis<result.dis){
  31283. result.line = line; result.dis = dis;
  31284. }
  31285. });
  31286. return result
  31287. }
  31288. var ringLen = 0;
  31289. class Ring{
  31290. constructor(o){
  31291. this.id = ringLen ++;
  31292. this.type = o.type || 'normal';
  31293. this.points = o.points;
  31294. this.lines = o.lines;
  31295. rings.push(this);
  31296. this.child = [];//包含的环
  31297. this.parent = [];//被包含的环
  31298. this.smallNeibours = [];//相邻最小环(存在和它有一个以上的相同边的最小环)
  31299. var area = math.getArea(this.points);
  31300. this.area = Math.abs(area);
  31301. this.isClockwise = area<0;//是否逆时针。一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  31302. }
  31303. }
  31304. var findLine = function(p1,p2){
  31305. return lines.find(line=>line.points.includes(p1) && line.points.includes(p2) )
  31306. };
  31307. var ifSamePart = function(checkPart , part){//checkPart中所包含的part片段是否和基准part的顺序一样(逆序也可以, 中间有其他数也可以,起始不同也行。比如 01234和204一样的)
  31308. var axis, startIndex, newCheckPart=[];
  31309. for(var j=0,len1 = checkPart.length; j<len1; j++){//将checkPart中比part多的数除去,使两个数组中包含的数完全相同。
  31310. if(part.indexOf(checkPart[j])>-1)newCheckPart.push(checkPart[j]);
  31311. }
  31312. for(var i=0,len = part.length; i<len; i++){
  31313. var index = newCheckPart.indexOf(part[i]);
  31314. if(index == -1)return false;
  31315. if(i == 0) startIndex = index;//标记第一个查找点对应的index
  31316. else if(i == 1){//标记查找顺序是正还是逆
  31317. axis = index - startIndex;
  31318. if(axis == len - 1) axis = -1;//刚好是首和尾
  31319. else if(axis == 1- len) axis = 1;
  31320. if(axis != -1 && axis != 1){
  31321. return false
  31322. }
  31323. }else {//判断是否是按顺序的
  31324. if(index != ((startIndex+axis * i + len) % len) ) return false;
  31325. }
  31326. }
  31327. return {sameAxis:axis>0}; //如果一样的话返回正逆是否相同
  31328. };
  31329. //或者判断是否有相同边(但是相同点是可以组成不同环)
  31330. var ifSameRing = function(ring1, ring2){//判断两个环是否相等。 除了可以逆向外顺序要对
  31331. if(ring1 instanceof Ring)ring1 = ring1.points;
  31332. if(ring2 instanceof Ring)ring2 = ring2.points;
  31333. if(ring1.length != ring2.length)return false;
  31334. if(ring1.lines && ring2.lines){
  31335. if(getDifferenceSet(ring1.lines , ring2.lines).length == 0)return true;//差集个数为0
  31336. }else {
  31337. if(ifSamePart(ring1, ring2))return true
  31338. }
  31339. };
  31340. var atWhichChildLine = function(point, line, precision){
  31341. if(line.children.length == 0){//这里可能要放低精度 保证能找到
  31342. if(math.ifPointAtLineBound(point, line.points, precision)) return line;
  31343. }else {
  31344. for(var i=0;i<line.children.length;i++){
  31345. var at = atWhichChildLine(point, line.children[i], precision);
  31346. if(at)return at
  31347. }
  31348. }
  31349. };
  31350. function getSliceLines(){
  31351. var len = lines.length;
  31352. var deal = function(line1,line2){
  31353. if(line1 == line2)return;
  31354. if(line1.angle == void 0) line1.getAngleInfo();
  31355. if(line2.angle == void 0) line2.getAngleInfo();
  31356. var intersect = line1.getIntersectWithLine(line2, precision);
  31357. if(intersect){
  31358. var point; //得到交点
  31359. if(intersect.type == "intersect"){
  31360. point = getPoint(intersect.point, "whenGetSliceLines");
  31361. var line1_ = atWhichChildLine(point, line1);
  31362. var line2_ = atWhichChildLine(point, line2);
  31363. //重合的情况还没考虑(平行)
  31364. if(!line1_) line1_ = atWhichChildLine(point, line1, precision);//降低精度
  31365. if(!line1_) line1_ = atWhichChildLine(point, line1, precision*2);//降低精度
  31366. if(!line2_) line2_ = atWhichChildLine(point, line2, precision);
  31367. if(!line2_) line2_ = atWhichChildLine(point, line2, precision*2);//降低精度
  31368. //拆分线条:
  31369. //如果还报错,找不到ChildLine,就直接返回吧 或者搞个循环 逐渐降低精度
  31370. if(!line1_ || !line2_){
  31371. console.warn("atWhichChildLine仍旧找不到 :" + line1.id + ',' + line2.id + ", pointId: "+point.id);
  31372. line1_ || console.warn("找不到line1");
  31373. line2_ || console.warn("找不到line2");
  31374. return;
  31375. }
  31376. if(line1_.points.find(p=>p == point) && line2_.points.find(p=>p == point)){//这个点是line1_、 line2_端点,不做处理
  31377. //console.log("joint型 "+point.id)
  31378. }else if(line1_.points.find(p=>p == point)){//T型交叉
  31379. line2_.splitByPoint(point);//加入到母线中,之后还先用母线判断交点
  31380. //console.log("T型交叉1 "+point.id)
  31381. }else if(line2_.points.find(p=>p == point)){//T型交叉
  31382. line1_.splitByPoint(point);
  31383. //console.log("T型交叉2 "+point.id)
  31384. }else {//十字交叉
  31385. line1_.splitByPoint(point);
  31386. line2_.splitByPoint(point);
  31387. }
  31388. }else {
  31389. point = intersect.point;//交点是端点
  31390. if(math.closeTo(line1.angle,line2.angle)){ //重合一部分
  31391. var children1 = line1.getAllSlices();
  31392. var children2 = line2.getAllSlices();
  31393. if(children1.length>1 || children2.length>1){ //使用最小分割片段来比较
  31394. children1.forEach(child1=>{
  31395. children2.forEach(child2=>{
  31396. deal(child1, child2);
  31397. });
  31398. });
  31399. return;
  31400. }
  31401. var anotherPoint1 = line1.points.find(point_=>point_!=point);
  31402. var anotherPoint2 = line2.points.find(point_=>point_!=point);
  31403. if(math.ifPointAtLineBound(anotherPoint1, line2.points)){
  31404. line2.splitByPoint(anotherPoint1);
  31405. }else if(math.ifPointAtLineBound(anotherPoint2, line1.points)){
  31406. line1.splitByPoint(anotherPoint2);
  31407. }
  31408. }
  31409. }
  31410. }else if(math.closeTo(line1.angle,line2.angle)){
  31411. var vec1 = line1.getVector();
  31412. var vec = line1.points[0].clone().sub(line2.points[0]);
  31413. var cos = math.getVec2Cos(vec1, vec);
  31414. if(math.closeTo(cos, -1, 1e-4) || math.closeTo(cos, 1, 1e-4)){ //共线
  31415. var children1 = line1.getAllSlices();
  31416. var children2 = line2.getAllSlices();
  31417. if(children1.length>1 || children2.length>1){ //使用最小分割片段来比较
  31418. children1.forEach(child1=>{
  31419. children2.forEach(child2=>{
  31420. deal(child1, child2);
  31421. });
  31422. });
  31423. return;
  31424. }
  31425. //判断是否重叠
  31426. var A = line1.points[0];
  31427. var C = line1.reverse == line2.reverse ? line2.points[0] : line2.points[1];
  31428. var B = line1.points[1];
  31429. var D = line1.reverse == line2.reverse ? line2.points[1] : line2.points[0];
  31430. var BC = C.clone().sub(B);
  31431. var AD = D.clone().sub(A);
  31432. if(BC.length()<AD.length()){
  31433. var BA = A.clone().sub(B);
  31434. if(math.getVec2Angle(BC, BA) >= 1.57 )return;//没有重叠部分
  31435. }else {
  31436. var AB = B.clone().sub(A);
  31437. if(math.getVec2Angle(AD, AB) >= 1.57 )return;
  31438. }
  31439. var f = function(line1,line2){
  31440. var one = math.ifPointAtLineBound(line1.points[0], line2.points);
  31441. var two = math.ifPointAtLineBound(line1.points[1], line2.points);
  31442. if(one && two){//line1在line2上
  31443. line2.splitByPoints( line1.points );
  31444. return true
  31445. }else if(one || two){//错开
  31446. var point1 = one ? line1.points[0] : line1.points[1];
  31447. var anotherPoint1 = one ? line1.points[1] : line1.points[0];
  31448. var dis1 = line2.points[0].distanceTo(anotherPoint1);
  31449. var dis2 = line2.points[1].distanceTo(anotherPoint1);
  31450. var point2 = dis1 < dis2 ? line2.points[0] : line2.points[1];
  31451. line1.splitByPoint(point2);
  31452. line2.splitByPoint(point1);
  31453. return true
  31454. }
  31455. };
  31456. f(line1, line2) || f(line2, line1);
  31457. }
  31458. }
  31459. };
  31460. for(let i=0;i<len;i++){
  31461. let line1 = lines[i];
  31462. for(let j=i+1;j<len;j++){
  31463. let line2 = lines[j];
  31464. deal(line1,line2);
  31465. }
  31466. }
  31467. //console.log("原有线条个数:"+len)
  31468. //lines = lines.filter((line)=>{return line.children.length == 0})
  31469. //console.log("现有线条个数:"+lines.length)
  31470. }
  31471. var bound = new Box2();
  31472. var build = function(o){
  31473. //融合了相近点
  31474. //根据bound 处理precision
  31475. o.points.forEach(p=>{
  31476. bound.expandByPoint(new Vector2(p.x,p.y));
  31477. });
  31478. if(o.precision != void 0){
  31479. precision = o.precision;
  31480. }else {
  31481. var boundSize = bound.getSize(new Vector2);
  31482. precision = MathUtils.clamp(Math.max(boundSize.x, boundSize.y) / 70, 0.2, 2);
  31483. }
  31484. o.points.forEach(point=>getPoint(point));//{x:..,y:..}
  31485. o.lines.forEach(line=>{ //{p1:id1. p2:id2}
  31486. new Line$1({points:[getPoint(line.p1), getPoint(line.p2)], id:line.id });
  31487. });
  31488. //注意:不能出现一条线的两个点坐标一致,否则寻路时方向出错。 所以手动融合下相近点。
  31489. };
  31490. var searchRings = function(o={}){
  31491. points = [];
  31492. lines = [];
  31493. rings = [];
  31494. lineLen = ringLen = 0;
  31495. o.points = o.points || [];
  31496. o.lines = o.lines || [];
  31497. build(o);
  31498. if(!o.dontSliceLines){
  31499. getSliceLines();
  31500. }
  31501. //查找最小回路:
  31502. //参考: 引入方向因子的最小回路、最大回路搜索算法.pdf
  31503. //方法: 逆时针寻找(标记)最外层大环 -->从走过的点开始逆时针寻找最小环(直到所有可走的路被走过两次)-->逆时针寻找最外层大环(直到所有可走的路被走过两次)-->..
  31504. //其中找大环时选择方向因子最小的路, 而小环则相反(但只有开始第一条路是一样的, 都是选择最左边的点的因子最小的路)。
  31505. //标记方法: 每条线需要被搜索两次才算完毕。搜索完毕的线退出搜索。(依据:搜索完全部最小回路后 , 在无向图中删除搜索过 2 次的边及孤立节点得到退化图 , 恰好构成最大回路。)
  31506. var searchTime = 0;
  31507. var addRingJudgeCount = 0;
  31508. var addRingJudge = function(ring, lines, connectedLines, type){// 处理拣出的片段
  31509. addRingJudgeCount++;
  31510. //console.log("addRingJudge points("+ type+"):"+ ring.map(point=>point.id) )
  31511. if(o.onlyGetOutRing && type == "small")return
  31512. if(type == "small" || o.onlyGetOutRing){//挑出回路:
  31513. var newRings = [];
  31514. while(ring.length){
  31515. var road = [];
  31516. var turnBack = false;
  31517. for(let i=0;i<ring.length;i++){
  31518. if(road.includes(ring[i])){//如果走到方才的点,可能形成回路。 无论是不是回路都要摘去这段。
  31519. var index = road.indexOf(ring[i]);
  31520. var pointArr = ring.slice(index, i);
  31521. var linesArr = lines.slice(index, i);
  31522. ring.splice(index,i-index);
  31523. lines.splice(index,i-index);
  31524. if(pointArr.length>2){// 如果只有两个数,代表原路返回, 如 1->2(->1)
  31525. if( !rings.find(ring_=>ifSameRing(pointArr, ring_))) newRings.push( new Ring({points: pointArr, lines:linesArr}) );
  31526. }
  31527. turnBack = true;
  31528. break;
  31529. }else {
  31530. road.push(ring[i]);
  31531. turnBack = false;
  31532. }
  31533. }
  31534. if(!turnBack){//没有重复的点,那么就直接处理整条。
  31535. if(ring.length>2){// 如果只有两个数,代表原路返回, 如 1->2(->1)
  31536. if( !rings.find(ring_=>ifSameRing(ring, ring_))) newRings.push( new Ring({points: ring, lines}) );
  31537. }
  31538. break;
  31539. }
  31540. }
  31541. if(type != 'small'){
  31542. newRings.forEach(e=>e.isOutRing = true);
  31543. }
  31544. //console.log(newRings)
  31545. }else {
  31546. return ring
  31547. }
  31548. };
  31549. var search = function(point2d, comeRoad, type, connectedLines){
  31550. searchTime++;
  31551. var goLine;
  31552. var direction;
  31553. if(type.includes("big")){
  31554. if(!comeRoad){
  31555. if(type.includes("Left")){//逆时针
  31556. direction = new Vector2(1,0);
  31557. }else {
  31558. direction = new Vector2(-1,0);
  31559. }
  31560. goLine = point2d.searchLineByFactor(direction,"min");
  31561. }else {
  31562. var lastPoint = comeRoad.points[comeRoad.points.length-1];
  31563. direction = point2d.clone().sub(lastPoint);
  31564. goLine = point2d.searchLineByFactor(direction,"min", findLine(point2d, lastPoint));
  31565. }
  31566. }else {
  31567. if(!comeRoad){
  31568. //似乎找最小环时,第一条线也是找最小的因子,这样才能保证逆时针(除非只有顺时针一条路)
  31569. direction = new Vector2(1,0);
  31570. goLine = point2d.searchLineByFactor(direction,"min");
  31571. }else {
  31572. var lastPoint = comeRoad.points[comeRoad.points.length-1];
  31573. direction = point2d.clone().sub(lastPoint);
  31574. goLine = point2d.searchLineByFactor(direction,"max", findLine(point2d, lastPoint));
  31575. }
  31576. }
  31577. if(!goLine)return
  31578. goLine.searchTime++;
  31579. connectedLines.includes(goLine) || connectedLines.push(goLine);
  31580. var nextPoint = goLine.points.find( point => point2d!=point );
  31581. //if( comeRoad && comeRoad.points[comeRoad.points.length - 1] == nextPoint ) return;//不能查找来时的方向(反方向)
  31582. //走不通就原路返回
  31583. var roadPoints = comeRoad ? comeRoad.points.concat([point2d]) : [point2d];//每个分叉都能构成一条新的road
  31584. var roadLines = comeRoad ? comeRoad.lines.concat([goLine]) : [goLine];
  31585. //走到第一个点就算停止,这时候可能得到一个环、或者一段走了两遍的线、或者一条线上带了些环。
  31586. if(nextPoint == roadPoints[0]) return addRingJudge(roadPoints, roadLines, connectedLines, type) //形成环
  31587. else {
  31588. /* var len = roadPoints.indexOf(nextPoint);
  31589. if( len > -1){ //走到走过的路的某一点 构成这段路的回路
  31590. var points = roadPoints.slice(len, roadPoints.length);
  31591. var lines = roadLines.slice(len, roadPoints.length);
  31592. addRingJudge(points, lines)
  31593. }else{ */
  31594. return search(nextPoint, {lines:roadLines, points:roadPoints}, type, connectedLines);//继续寻路
  31595. //}
  31596. }
  31597. };
  31598. while(1){//搜寻一次大环
  31599. var connectedLines = [];//被搜寻过的且searchTime<2的线。一旦全部搜完就说明该连通区域搜寻完毕,继续查下一个连通区域。
  31600. var startPoint = null;
  31601. points.forEach(point=>{//找出x最小的点
  31602. if(!point.lines.find(line=>line.searchTime<2))return;
  31603. if(!startPoint)startPoint = point;
  31604. else if(point.x < startPoint.x)startPoint = point;
  31605. });
  31606. if(!startPoint)break; //说明全部找完
  31607. var ring = search(startPoint, null, "bigLeft", connectedLines);//逆时针
  31608. //search(startPoint, null, "bigRight", connectedLines);//顺时针(为了防止最外层不是回路之前写了顺时针,但如果是回路就会走重复。后来发现只要逆时针即可,因为走完后剩下的可以再次找大环)
  31609. connectedLines = connectedLines.filter(line=>line.searchTime<2);
  31610. while(connectedLines.length>0){//目标是顺着connectedLines把所有连通的小环都找到
  31611. let points_ = [];//connectedLines中所有的点
  31612. connectedLines.forEach(line=>line.points.forEach(point=>{if(!points_.includes(point))points_.push(point); }));
  31613. var startPoint = null;
  31614. points_.forEach(point=>{//找出x最小的点
  31615. if(!point.lines.find(line=>line.searchTime<2))return;
  31616. if(!startPoint)startPoint = point;
  31617. else if(point.x < startPoint.x)startPoint = point;
  31618. });
  31619. if(!startPoint)break;
  31620. search(startPoint, null, "small", connectedLines);
  31621. connectedLines = connectedLines.filter(line=>line.searchTime<2);
  31622. }
  31623. }
  31624. /* if(o.onlyGetOutRing){
  31625. rings = rings.filter(e=>e.isOutRing)
  31626. } */
  31627. //console.log("searchTime "+searchTime + ", addRingJudgeCount " +addRingJudgeCount)
  31628. //找出所有的相邻关系,包括公共边
  31629. var len = rings.length;
  31630. for(let i=0; i<len; i++){
  31631. let ring1 = rings[i];
  31632. for(let j=i+1; j<len; j++){
  31633. let ring2 = rings[j];
  31634. var bothHasLines = getMixedSet(ring1.lines, ring2.lines);
  31635. if(bothHasLines.length){//ring1oíring2?àáú
  31636. ring1.smallNeibours.push(ring2);
  31637. ring2.smallNeibours.push(ring1);
  31638. }else {
  31639. }
  31640. }
  31641. }
  31642. rings.forEach(ring1=>{
  31643. for(let i=0; i<len; i++){
  31644. var ring2 = rings[i];
  31645. if(ring1 == ring2 || ring1.smallNeibours.includes(ring2))continue;
  31646. let inside;
  31647. for(let u=0;u<ring1.points.length;u++){
  31648. inside = math.isPointInArea(ring2.points, null, ring1.points[u]);
  31649. if(!inside)break
  31650. else if(inside && !inside.atLine){
  31651. break
  31652. }
  31653. }
  31654. if(inside){ //只要其中一个点在ring2内,就说明ring1是内环
  31655. if(inside.atLine){//(还是会存在点全在线上的情况,这时候判断中心点)
  31656. var center = math.getCenterOfGravityPoint(ring1.points);
  31657. let inside1 = math.isPointInArea(ring2.points, null, center);
  31658. if(!inside1){
  31659. continue
  31660. }
  31661. }
  31662. ring2.child.push(ring1);
  31663. ring1.parent.push(ring2);
  31664. }
  31665. }
  31666. });
  31667. //去除非最小的ring 是否应该检测parent child?
  31668. /*
  31669. like this:
  31670. |———————————————————————|
  31671. |———|———————|———————| |
  31672. | | | | |
  31673. | |———————|———————| |
  31674. |———————————————————————|
  31675. */
  31676. var wiseRings = rings.filter(r=>!r.isClockwise);//一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  31677. if(wiseRings.length > 0){
  31678. //console.log('%c存在非最小的ring! 进行处理:',"color:#00f");
  31679. wiseRings.forEach(ring=>{ //(此案例验证出smallNeibours就是它的最小构成,可以再看看别的案例)
  31680. if(ring.smallNeibours.length>0){//另:如果内部只有一个,说明它是最小环,不需要处理
  31681. var is = false;
  31682. var difference = getDifferenceSet(ring.lines , getDifferenceSetMuti(ring.smallNeibours.concat(ring.child).map(ring=>ring.lines)));//获取所有smallNeibours和child的边中没有重复过的边(就是outline) 和该ring的线比较
  31683. is = difference.every(line=> ring.child.find(r=>r.lines.includes(line)) ); //多出的线只能是child中的线
  31684. if(is){
  31685. console.log('%c删除非最小环 ring'+ring.id,"color:#00f");
  31686. console.log(ring);
  31687. rings.splice(rings.indexOf(ring), 1);
  31688. ring.child.forEach(c=>{var index = c.parent.indexOf(ring);index>-1 && c.parent.splice(index,1);});
  31689. ring.parent.forEach(c=>{var index = c.child.indexOf(ring);index>-1 && c.child.splice(index,1);});
  31690. ring.smallNeibours.forEach(c=>{var index = c.smallNeibours.indexOf(ring);index>-1 && c.smallNeibours.splice(index,1);});
  31691. }
  31692. }
  31693. });
  31694. }
  31695. /* rings = rings.filter(ring=>{
  31696. rings = rings.filter(ring=>{
  31697. var enoughSize = ring.area > 0.5
  31698. if(!enoughSize){console.log('因面积过小去除ring '+ring.id + " , area: "+ring.area)}
  31699. return enoughSize
  31700. })
  31701. rings.forEach(ring=>{
  31702. if(ring.closetChilds){
  31703. ring.closetChilds = ring.closetChilds.filter(e=>rings.includes(e))
  31704. }
  31705. })
  31706. return rings
  31707. }) */ //在dealRings前不能随意删除rings,因为判断是否是最小环时需要全部的环
  31708. rings.forEach(ring=>{ //这里和cad中的不太一样, cad中双数个parent算外环,单数内环; 这里不分内外, 只看有无parent child
  31709. if(ring.parent.length){
  31710. ring.closetParent = ring.parent.find(ring_ => ring_.parent.length == ring.parent.length - 1);//最近一层的大环就是比它的parent个数少一的
  31711. ring.closetParent.closetChilds || (ring.closetParent.closetChilds = []);//内环可能多个
  31712. ring.closetParent.closetChilds.push(ring);
  31713. }
  31714. });
  31715. //console.log(rings)
  31716. var _ring = rings.map(ring=>{
  31717. var data = {
  31718. id: ring.id,
  31719. points: ring.points.map(point=>{return {id: point.ids[0], x:point.x, y:point.y}}),
  31720. /* doors : o.doors.filter(door=>{
  31721. if(ring.closetChilds){
  31722. var childOutLines = getDifferenceSetMuti(ring.closetChilds.map(ring=>ring.lines)) //最近子环的外边
  31723. return ring.lines.concat(childOutLines).includes(door.atLine)
  31724. }else{
  31725. return ring.lines.includes(door.atLine)
  31726. }
  31727. }), */
  31728. area:ring.area,
  31729. closetParent : ring.closetParent && ring.closetParent.id,
  31730. closetChilds : ring.closetChilds && ring.closetChilds.map(e=>e.id)
  31731. };
  31732. return data
  31733. });
  31734. //console.log(JSON.stringify(_ring))
  31735. return _ring
  31736. };
  31737. var easing = {};
  31738. //渐变曲线函数,反应加速度的变化
  31739. //currentTime:x轴当前时间(从0-到duration), startY:起始点, duration:总时长, wholeY:路程 (即endY-startY)
  31740. //参数基本是 x, 0, 1, 1
  31741. /*
  31742. easeOut 基本是y= m * (x-dur)^k + n, 若k为偶数,m<0, 若k为奇数,m>0; (因为偶数的话必须开口向下才能获得斜率递减的递增的那段,而奇数是对称的,单调递增. )
  31743. 根据x=0时y=0, x=dur时y=S , 得 n = S,m = -S/(-dur)^k
  31744. */
  31745. easing.getEaseOut = function(k){// k 是>=2的整数. 越大变化率越大, 相同初始速度所需要时间越久
  31746. let easeFun;
  31747. k = Math.round(k);
  31748. if(k<2){
  31749. k = Math.PI / 2;
  31750. easeFun = easing.easeOutSine;
  31751. }else {
  31752. easeFun = function(currentTime, startY, wholeY, duration) {
  31753. if(k>2){
  31754. console.log(k);
  31755. }
  31756. return -wholeY/Math.pow(-duration, k) * Math.pow(currentTime-duration, k) + wholeY
  31757. };
  31758. }
  31759. return {
  31760. k,
  31761. easeFun
  31762. }
  31763. };
  31764. easing.linearTween = function(currentTime, startY, wholeY, duration) {
  31765. return wholeY * currentTime / duration + startY
  31766. }
  31767. ,
  31768. easing.easeInQuad = function(currentTime, startY, wholeY, duration) {
  31769. return currentTime /= duration,
  31770. wholeY * currentTime * currentTime + startY
  31771. }
  31772. ,
  31773. easing.easeOutQuad = function(currentTime, startY, wholeY, duration) { // 如套上实际的距离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
  31774. return currentTime /= duration,
  31775. -wholeY * currentTime * (currentTime - 2) + startY
  31776. }
  31777. ,
  31778. easing.easeInOutQuad = function(currentTime, startY, wholeY, duration) {
  31779. return currentTime /= duration / 2,
  31780. currentTime < 1 ? wholeY / 2 * currentTime * currentTime + startY : (currentTime--,
  31781. -wholeY / 2 * (currentTime * (currentTime - 2) - 1) + startY)
  31782. }
  31783. ,
  31784. easing.easeInCubic = function(currentTime, startY, wholeY, duration) {
  31785. return currentTime /= duration,
  31786. wholeY * currentTime * currentTime * currentTime + startY
  31787. }
  31788. ,
  31789. easing.easeOutCubic = function(currentTime, startY, wholeY, duration) {// y = S / dur^3 *(x-dur)^3 + S,对称中心是(dur,S),从0-dur是 斜率递减的递增函数,导数为3S/dur^3 * (x-dur)^2, 0时速度为3S/dur
  31790. return currentTime /= duration,
  31791. currentTime--,
  31792. wholeY * (currentTime * currentTime * currentTime + 1) + startY
  31793. }
  31794. ,
  31795. easing.easeInOutCubic = function(currentTime, startY, wholeY, duration) {
  31796. return currentTime /= duration / 2,
  31797. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  31798. wholeY / 2 * (currentTime * currentTime * currentTime + 2) + startY)
  31799. }
  31800. ,
  31801. easing.easeInQuart = function(currentTime, startY, wholeY, duration) {
  31802. return currentTime /= duration,
  31803. wholeY * currentTime * currentTime * currentTime * currentTime + startY
  31804. }
  31805. ,
  31806. easing.easeOutQuart = function(currentTime, startY, wholeY, duration) {//根据上面的计算,估计0时速度应该是4S/dur吧……
  31807. return currentTime /= duration,
  31808. currentTime--,
  31809. -wholeY * (currentTime * currentTime * currentTime * currentTime - 1) + startY
  31810. }
  31811. ,
  31812. easing.easeInOutQuart = function(currentTime, startY, wholeY, duration) {
  31813. return currentTime /= duration / 2,
  31814. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  31815. -wholeY / 2 * (currentTime * currentTime * currentTime * currentTime - 2) + startY)
  31816. }
  31817. ,
  31818. easing.easeInQuint = function(currentTime, startY, wholeY, duration) {
  31819. return currentTime /= duration,
  31820. wholeY * currentTime * currentTime * currentTime * currentTime * currentTime + startY
  31821. }
  31822. ,
  31823. easing.easeOutQuint = function(currentTime, startY, wholeY, duration) {
  31824. return currentTime /= duration,
  31825. currentTime--,
  31826. wholeY * (currentTime * currentTime * currentTime * currentTime * currentTime + 1) + startY
  31827. }
  31828. ,
  31829. easing.easeInOutQuint = function(currentTime, startY, wholeY, duration) {
  31830. return currentTime /= duration / 2,
  31831. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  31832. wholeY / 2 * (currentTime * currentTime * currentTime * currentTime * currentTime + 2) + startY)
  31833. }
  31834. ,
  31835. easing.easeInSine = function(currentTime, startY, wholeY, duration) {
  31836. return -wholeY * Math.cos(currentTime / duration * (Math.PI / 2)) + wholeY + startY
  31837. }
  31838. ,
  31839. easing.easeOutSine = function(currentTime, startY, wholeY, duration) {// y' = S * PI / 2 / dur * cos(PI/2/dur * x)
  31840. return wholeY * Math.sin(currentTime / duration * (Math.PI / 2)) + startY
  31841. }
  31842. ,
  31843. easing.easeInOutSine = function(currentTime, startY, wholeY, duration) {
  31844. return -wholeY / 2 * (Math.cos(Math.PI * currentTime / duration) - 1) + startY
  31845. }
  31846. ,
  31847. easing.easeInExpo = function(currentTime, startY, wholeY, duration) {
  31848. return wholeY * Math.pow(2, 10 * (currentTime / duration - 1)) + startY
  31849. }
  31850. ,
  31851. easing.easeOutExpo = function(currentTime, startY, wholeY, duration) {
  31852. return wholeY * (-Math.pow(2, -10 * currentTime / duration) + 1) + startY
  31853. }
  31854. ,
  31855. easing.easeInOutExpo = function(currentTime, startY, wholeY, duration) {
  31856. return currentTime /= duration / 2,
  31857. currentTime < 1 ? wholeY / 2 * Math.pow(2, 10 * (currentTime - 1)) + startY : (currentTime--,
  31858. wholeY / 2 * (-Math.pow(2, -10 * currentTime) + 2) + startY)
  31859. }
  31860. ,
  31861. easing.easeInCirc = function(currentTime, startY, wholeY, duration) {
  31862. return currentTime /= duration,
  31863. -wholeY * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY
  31864. }
  31865. ,
  31866. easing.easeOutCirc = function(currentTime, startY, wholeY, duration) {
  31867. return currentTime /= duration,
  31868. currentTime--,
  31869. wholeY * Math.sqrt(1 - currentTime * currentTime) + startY
  31870. }
  31871. ,
  31872. easing.easeInOutCirc = function(currentTime, startY, wholeY, duration) {
  31873. return currentTime /= duration / 2,
  31874. currentTime < 1 ? -wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY : (currentTime -= 2,
  31875. wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) + 1) + startY)
  31876. }
  31877. ,
  31878. easing.easeInElastic = function(currentTime, startY, wholeY, duration) {
  31879. var r = 1.70158
  31880. , o = 0
  31881. , a = wholeY;
  31882. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration),
  31883. a < Math.abs(wholeY) ? (a = wholeY,
  31884. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  31885. -(a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY)
  31886. }
  31887. ,
  31888. easing.easeOutElastic = function(currentTime, startY, wholeY, duration) {
  31889. var r = 1.70158
  31890. , o = 0
  31891. , a = wholeY;
  31892. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration),
  31893. a < Math.abs(wholeY) ? (a = wholeY,
  31894. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  31895. a * Math.pow(2, -10 * currentTime) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) + wholeY + startY)
  31896. }
  31897. ,
  31898. easing.easeInOutElastic = function(currentTime, startY, wholeY, duration) {
  31899. var r = 1.70158
  31900. , o = 0
  31901. , a = wholeY;
  31902. return 0 === currentTime ? startY : 2 === (currentTime /= duration / 2) ? startY + wholeY : (o || (o = duration * (.3 * 1.5)),
  31903. a < Math.abs(wholeY) ? (a = wholeY,
  31904. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  31905. 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)
  31906. }
  31907. ,
  31908. easing.easeInBack = function(currentTime, startY, wholeY, duration, r) {
  31909. return void 0 === r && (r = 1.70158),
  31910. wholeY * (currentTime /= duration) * currentTime * ((r + 1) * currentTime - r) + startY
  31911. }
  31912. ,
  31913. easing.easeOutBack = function(currentTime, startY, wholeY, duration, r) {
  31914. return void 0 === r && (r = 1.70158),
  31915. wholeY * ((currentTime = currentTime / duration - 1) * currentTime * ((r + 1) * currentTime + r) + 1) + startY
  31916. }
  31917. ,
  31918. easing.easeInOutBack = function(currentTime, startY, wholeY, duration, r) {
  31919. return void 0 === r && (r = 1.70158),
  31920. (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
  31921. }
  31922. ,
  31923. easing.easeOutBounce = function(currentTime, startY, wholeY, duration) {
  31924. 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
  31925. }
  31926. ,
  31927. easing.easeInBounce = function(currentTime, startY, wholeY, r) {
  31928. return wholeY - easing.easeOutBounce(r - currentTime, 0, wholeY, r) + startY
  31929. }
  31930. ,
  31931. easing.easeInOutBounce = function(currentTime, startY, wholeY, r) {
  31932. 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
  31933. };
  31934. var lerp = {
  31935. /* vector: function(currentTime, startY, f) {//xzw change, add f
  31936. var wholeY = currentTime.clone();
  31937. return startY = startY.clone(),
  31938. function(duration) {
  31939. currentTime.set(wholeY.x * (1 - duration) + startY.x * duration, wholeY.y * (1 - duration) + startY.y * duration, wholeY.z * (1 - duration) + startY.z * duration)
  31940. f && f(currentTime,duration);
  31941. }
  31942. },
  31943. quaternion: function(currentTime, startY, f) {//xzw change, add f
  31944. var wholeY = currentTime.clone();
  31945. return function(duration) {
  31946. currentTime.copy(wholeY).slerp(startY, duration);
  31947. f && f(currentTime,duration);
  31948. }
  31949. },
  31950. property: function(currentTime, startY, wholeY, duration) {
  31951. var r = currentTime[startY];
  31952. return function(o) {
  31953. currentTime[startY] = r * (1 - o) + wholeY * o,
  31954. duration && duration(currentTime[startY])
  31955. }
  31956. },
  31957. uniform: function(currentTime, startY, wholeY) {
  31958. var duration = currentTime.material.uniforms[startY].value;
  31959. return function(r) {
  31960. try{
  31961. currentTime.material.uniforms[startY] && (currentTime.material.uniforms[startY].value = duration * (1 - r) + wholeY * r)
  31962. }catch(currentTime){
  31963. console.log(1)
  31964. }
  31965. }
  31966. },
  31967. matrix4: function(currentTime, startY) {
  31968. var wholeY = currentTime.clone();
  31969. return function(duration) {
  31970. for (var r = currentTime.elements, o = wholeY.elements, a = startY.elements, s = 0; s < 16; s++)
  31971. r[s] = o[s] * (1 - duration) + a[s] * duration
  31972. }
  31973. },
  31974. allUniforms: function(currentTime, startY, wholeY) {
  31975. var duration = currentTime.map(function(currentTime) {
  31976. return this.uniform(currentTime, startY, wholeY)
  31977. }
  31978. .bind(this));
  31979. return function(currentTime) {
  31980. duration.forEach(function(startY) {
  31981. startY(currentTime)
  31982. })
  31983. }
  31984. } */
  31985. vector: function(t, i, f) {//xzw change, add f
  31986. var n = t.clone();
  31987. return i = i.clone(),
  31988. function(e, delta) {
  31989. t.set(n.x * (1 - e) + i.x * e, n.y * (1 - e) + i.y * e, n.z * (1 - e) + i.z * e);
  31990. f && f(t,e, delta);
  31991. }
  31992. },
  31993. quaternion: function(t, i, f) {//xzw change, add f
  31994. var n = t.clone();
  31995. return function(e) {
  31996. t.copy(n).slerp(i, e);
  31997. f && f(t,e);
  31998. }
  31999. },
  32000. property: function(t, i, n, r) {
  32001. var o = t[i];
  32002. return function(e) {
  32003. t[i] = o * (1 - e) + n * e,
  32004. r && r(t[i]);
  32005. }
  32006. },
  32007. uniform: function(t, i, n) {
  32008. var r = t.material.uniforms[i].value;
  32009. return function(e) {
  32010. t.material.uniforms[i] && (t.material.uniforms[i].value = r * (1 - e) + n * e);
  32011. }
  32012. },
  32013. matrix4: function(o, a) {
  32014. var s = o.clone();
  32015. return function(e) {
  32016. for (var t = o.elements, i = s.elements, n = a.elements, r = 0; r < 16; r++)
  32017. t[r] = i[r] * (1 - e) + n[r] * e;
  32018. }
  32019. },
  32020. allUniforms: function(e, t, i) {
  32021. var n = e.map(function(e) {
  32022. return this.uniform(e, t, i)
  32023. }
  32024. .bind(this));
  32025. return function(t) {
  32026. n.forEach(function(e) {
  32027. e(t);
  32028. });
  32029. }
  32030. }
  32031. };
  32032. /*
  32033. 渐变
  32034. */
  32035. var transitions = {
  32036. globalDone: null,
  32037. funcs: [],
  32038. counter: 0,
  32039. uniqueID: 0,
  32040. start: function(func, duration, done, delay, ease, name, id, cancelFun, ignoreFirstFrame=true) {
  32041. return delay = delay || 0,
  32042. this.funcs.push({
  32043. func: func,
  32044. current: -delay * Math.abs(duration), //当前时间
  32045. duration: (1 - Math.max(delay, 0)) * Math.abs(duration), //总时长
  32046. done: done,
  32047. easing: ease || easing.linearTween, //渐变曲线
  32048. cycling: duration < 0,
  32049. running: !0,
  32050. debug: delay < 0,
  32051. name: name || "T" + this.counter,
  32052. id: void 0 === id ? this.counter : id,
  32053. paused: !1,
  32054. cancelFun : cancelFun, //取消时执行的函数
  32055. updateCount:0,
  32056. ignoreFirstFrame,
  32057. }),
  32058. func(0, 16),
  32059. this.counter += 1,
  32060. func
  32061. },
  32062. trigger: function(e) {
  32063. var t = void 0 === e.delayRatio ? 0 : e.delayRatio
  32064. , u = e.func || function() {}
  32065. , r = void 0 === e.duration ? 0 : e.duration;
  32066. void 0 !== e.cycling && e.cycling && (r = -Math.abs(r));
  32067. var o = e.done || null
  32068. , a = e.easing || easing.linearTween
  32069. , s = e.name || "R" + this.counter
  32070. , l = void 0 === e.id ? this.counter : e.id;
  32071. return this.start(u, r, o, t, a, s, l)
  32072. },
  32073. setTimeout: function(e, t, u) {
  32074. var duration = void 0 === u ? this.counter : u;
  32075. return this.trigger({
  32076. done: e,
  32077. duration: void 0 === t ? 0 : t,
  32078. name: "O" + this.counter,
  32079. id: duration
  32080. })
  32081. },
  32082. pause: function() {
  32083. this.paused = !0;
  32084. },
  32085. resume: function() {
  32086. this.paused = !1;
  32087. },
  32088. update: function(e) {
  32089. this.funcs.forEach(function(t) {
  32090. if(t.updateCount++ == 0 && t.ignoreFirstFrame) return //add start可能发生在一帧中任意时刻,而每次update的是在一帧中的固定时刻,所以从start到第一次update的时间并不是所传入的delta,该delta 是上一帧的update到这一帧的update的耗时。 故去掉了第一次的update,相当于延迟一帧再update.
  32091. if (!(t.paused || (t.current += 1e3 * e, t.current < 0))){
  32092. if (t.current >= t.duration && !t.cycling) {
  32093. var u = t.easing(1, 0, 1, 1);
  32094. t.func(u, 1e3 * e),
  32095. t.done && t.done(),
  32096. t.running = !1;
  32097. } else {
  32098. var duration = t.easing(t.current % t.duration / t.duration, 0, 1, 1)
  32099. , r = t.func(duration, 1e3 * e) || !1;
  32100. r && (t.done && t.done(),
  32101. t.running = !1);
  32102. }
  32103. }
  32104. });
  32105. var t = this.funcs.length;
  32106. this.funcs = this.funcs.filter(function(e) {
  32107. return e.running
  32108. });
  32109. var u = this.funcs.length;
  32110. if (t > 0 && 0 === u && this.globalDone) {
  32111. var duration = this.globalDone;
  32112. this.globalDone = null,
  32113. duration();
  32114. }
  32115. },
  32116. adjustSpeed: function(e, t) {
  32117. for (var u = this.getById(e), duration = 0; duration < u.length; duration++) {
  32118. var r = u[duration];
  32119. r.duration /= t,
  32120. r.current /= t;
  32121. }
  32122. },
  32123. getById: function(e) {
  32124. return this.funcs.filter(function(t) {
  32125. return e === t.id
  32126. })
  32127. },
  32128. get: function(e) {
  32129. for (var t = 0; t < this.funcs.length; t += 1)
  32130. if (this.funcs[t].func === e)
  32131. return this.funcs[t];
  32132. return null
  32133. },
  32134. isRunning: function(e) {
  32135. var t = this.get(e);
  32136. return null !== t && t.running
  32137. },
  32138. countActive: function() {
  32139. for (var e = 0, t = 0; t < this.funcs.length; t += 1)
  32140. e += this.funcs[t].running;
  32141. return e
  32142. },
  32143. listActive: function() {
  32144. for (var e = [], t = 0; t < this.funcs.length; t += 1)
  32145. this.funcs[t].running && e.push(this.funcs[t].name);
  32146. return e
  32147. },
  32148. done: function(e) {
  32149. this.globalDone = e;
  32150. },
  32151. cancelById: function(e, dealCancelFun) { //xzw add dealDone
  32152. var t = void 0 === e ? 0 : e;
  32153. let cancels = [];
  32154. this.funcs = this.funcs.filter(function(e) {
  32155. var is = e.id == t;
  32156. if(is && dealCancelFun){
  32157. e.cancelFun && cancels.push(e.cancelFun);
  32158. //e.cancelFun && e.cancelFun()
  32159. }
  32160. return !is
  32161. });
  32162. cancels.forEach(e=>{e();}); //先从funcs中去除后再执行
  32163. },
  32164. cancel: function(e) {
  32165. this.funcs = this.funcs.filter(function(t) {
  32166. return t.func !== e
  32167. });
  32168. },
  32169. getUniqueId: function() {
  32170. return this.uniqueID -= 1,
  32171. this.uniqueID
  32172. }
  32173. };
  32174. var Common$1 = {
  32175. sortByScore: function(list, request, rank){
  32176. var i = request ? Common$1.filterAll(list, request) : list;
  32177. return 0 === i.length ? [] : i = i.map(function(e) {
  32178. let results = rank.map(function(f){return f(e)});
  32179. let scores = results.map(e=>e.score != void 0 ? e.score : e);
  32180. let logs = results.map(e=>e.log);
  32181. return {
  32182. item: e,
  32183. scores,
  32184. logs,
  32185. score: scores.reduce(function(t, i) {//总分
  32186. return t + i
  32187. }, 0)
  32188. }
  32189. }).sort(function(e, t) {
  32190. return t.score - e.score;
  32191. })
  32192. }
  32193. ,
  32194. filterAll: function(e, t) {
  32195. return e.filter(function (e) {
  32196. return t.every(function (t) {
  32197. return t(e)
  32198. })
  32199. })
  32200. },
  32201. //---------------
  32202. find : function(list, request, rank, sortByScore ) {
  32203. if(sortByScore){
  32204. var r = this.sortByScore(list, request, rank);
  32205. return r[0] && r[0].item
  32206. }else {
  32207. var i = request ? Common$1.filterAll(list, request) : list;
  32208. return 0 === i.length ? null : (rank && rank.forEach(function(e) {
  32209. i = Common$1.stableSort(i, e);
  32210. }),
  32211. i[0])
  32212. }
  32213. }
  32214. ,
  32215. stableSort: function(e, f) {//用到排序函数,涉及到两个item相减
  32216. return e.map(function(e, i) {
  32217. return {
  32218. value: e,
  32219. index: i
  32220. }
  32221. }).sort(function(e, u) {
  32222. var n = f(e.value, u.value);
  32223. return 0 !== n ? n : e.index - u.index //似乎就是加多了这一步:若差距为0,按照原顺序
  32224. }).map(function(e) {
  32225. return e.value
  32226. })
  32227. },
  32228. average: function (e, t) {
  32229. if (0 === e.length)
  32230. return null;
  32231. for (var i = 0, n = 0, r = 0; r < e.length; r++) {
  32232. var o = t ? e[r][t] : e[r];
  32233. i += o,
  32234. n++;
  32235. }
  32236. return i / n
  32237. },
  32238. //---------------------------
  32239. getMixedSet : function(arr1, arr2){//交集
  32240. return arr1.filter(item=>arr2.includes(item));
  32241. },
  32242. getUnionSet : function(arr1, arr2){//并集
  32243. return arr1.concat(arr2.filter(item=>!arr1.includes(item)))
  32244. },
  32245. getDifferenceSet : function(arr1, arr2){//差集 不能识别重复的,如getDifferenceSet([1,2,2],[1,1,2]) 为空
  32246. var arr11 = arr1.filter(item=>!arr2.includes(item));
  32247. var arr22 = arr2.filter(item=>!arr1.includes(item));
  32248. return arr11.concat(arr22)
  32249. },
  32250. getDifferenceSetMuti : function(arr){//收集绝对没有重复的元素,也就是判断出现次数=1的
  32251. var set = [];
  32252. arr.forEach(arr1=>{
  32253. arr1.forEach(item=>{
  32254. var index = set.indexOf(item);
  32255. if(index>-1){
  32256. set.splice(index, 1);
  32257. }else {
  32258. set.push(item);
  32259. }
  32260. });
  32261. });
  32262. return set;
  32263. }
  32264. ,
  32265. CloneJson : function(data){
  32266. var str = JSON.stringify(data);
  32267. return JSON.parse(str)
  32268. }
  32269. ,
  32270. CloneObject : function (copyObj, isSimpleCopy, simpleCopyList = [], judgeSimpleCopyFun) {
  32271. //isSimpleCopy 只复制最外层
  32272. //复制json result的可能:普通数字或字符串、普通数组、复杂对象
  32273. simpleCopyList.includes(Object3D) || simpleCopyList.push(Object3D); //遇到simpleCopyList中的类直接使用不拷贝
  32274. judgeSimpleCopyFun || (judgeSimpleCopyFun=()=>{});
  32275. if (!copyObj || typeof copyObj == 'number' || typeof copyObj == 'string' || copyObj instanceof Function || simpleCopyList.some(className => copyObj instanceof className) || judgeSimpleCopyFun(copyObj)) {
  32276. return copyObj
  32277. }
  32278. if (copyObj instanceof Array) {
  32279. return copyObj.map(e => {
  32280. return this.CloneObject(e, isSimpleCopy, simpleCopyList, judgeSimpleCopyFun)
  32281. })
  32282. } else {
  32283. if (copyObj.clone instanceof Function) {
  32284. //解决一部分
  32285. return copyObj.clone()
  32286. }
  32287. }
  32288. let result = {};
  32289. for (var key in copyObj) {
  32290. if (copyObj[key] instanceof Object && !isSimpleCopy ) result[key] = this.CloneObject(copyObj[key], isSimpleCopy, simpleCopyList, judgeSimpleCopyFun);
  32291. else result[key] = copyObj[key];
  32292. //如果是函数类同基本数据,即复制引用
  32293. }
  32294. return result
  32295. }
  32296. ,
  32297. CloneClassObject :function(copyObj, {ignoreList=[],simpleCopyList=[]}={}){//复杂类对象
  32298. var newobj = new copyObj.constructor();
  32299. this.CopyClassObject(newobj, copyObj, {ignoreList,simpleCopyList});
  32300. return newobj
  32301. }
  32302. ,
  32303. CopyClassObject :function(targetObj, copyObj, {ignoreList=[],simpleCopyList=[]}={}){//复杂类对象
  32304. for(let i in copyObj){
  32305. if(i in copyObj.__proto__)break; //到函数了跳出
  32306. if(ignoreList.includes(i)){
  32307. continue;
  32308. }else if(simpleCopyList.includes(i)){
  32309. targetObj[i] = copyObj[i];
  32310. }else {
  32311. targetObj[i] = this.CloneObject(copyObj[i], false, simpleCopyList );
  32312. }
  32313. /* else if(copyObj[i].clone instanceof Function ){
  32314. targetObj[i] = copyObj[i].clone()
  32315. }else{
  32316. targetObj[i] = copyObj[i];
  32317. } */
  32318. }
  32319. }
  32320. ,
  32321. ifSame : function(object1, object2, simpleEqualClass=[]){ //对于复杂的类对象,若能简单判断就直接写进simpleEqualClass
  32322. if(object1 == object2 )return true // 0 != undefined , 0 == ''
  32323. else if(!object1 || !object2) return false
  32324. else if(object1.constructor != object2.constructor){
  32325. return false
  32326. }else if(simpleEqualClass.some(className => object1 instanceof className)){
  32327. return object1 == object2
  32328. }else if(object1 instanceof Array ) {
  32329. if(object1.length != object2.length)return false;
  32330. var _object2 = object2.slice(0);
  32331. for(let i=0;i<object1.length;i++){
  32332. var u = _object2.find(e=>Common$1.ifSame(object1[i], e, simpleEqualClass));
  32333. if(u == void 0 && !_object2.includes(u) && !object1.includes(u))return false;
  32334. else {
  32335. let index = _object2.indexOf(u);
  32336. _object2.splice(index,1);
  32337. }
  32338. }
  32339. return true
  32340. }else if(object1.equals instanceof Function ){//复杂数据仅支持这种,其他的可能卡住?
  32341. return object1.equals(object2)
  32342. }else if(typeof object1 == 'number' || typeof object1 == 'string'){
  32343. if(isNaN(object1) && isNaN(object2))return true
  32344. else return object1 == object2
  32345. }else if(typeof object1 == "object"){
  32346. var keys1 = Object.keys(object1);
  32347. var keys2 = Object.keys(object2);
  32348. if(!Common$1.ifSame(keys1,keys2,simpleEqualClass))return false;
  32349. for(let i in object1){
  32350. var same = Common$1.ifSame(object1[i], object2[i],simpleEqualClass);
  32351. if(!same)return false
  32352. }
  32353. return true
  32354. }else {
  32355. console.log('isSame出现例外');
  32356. }
  32357. }
  32358. ,
  32359. downloadFile : function(data, filename, cb) {
  32360. var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
  32361. save_link.href = data;
  32362. save_link.download = filename;
  32363. var event = document.createEvent('MouseEvents');
  32364. event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  32365. save_link.dispatchEvent(event);
  32366. cb && cb();
  32367. },
  32368. replaceAll : function (str, f, e) {
  32369. //f全部替换成e
  32370. var reg = new RegExp(f, "g"); //创建正则RegExp对象
  32371. return str.replace(reg, e);
  32372. },
  32373. dealURL(url){
  32374. let urlNew = this.replaceAll(url, "\\+", "%2B");// 浏览器似乎不支持访问带+的地址
  32375. urlNew = this.replaceAll(urlNew, "/.//", "/"); //去除双斜杠(/.//)
  32376. return urlNew
  32377. },
  32378. getNameFromURL(url){
  32379. if(!url)return ''
  32380. let get = (e)=>{
  32381. return e.split('/').pop()
  32382. };
  32383. if(url instanceof Array){
  32384. return url.map(e=>get(e))
  32385. }
  32386. return get(url)
  32387. },
  32388. //---------------------------
  32389. intervalTool:{ //延时update,防止卡顿
  32390. list:[],
  32391. /* isWaiting:function(name, func, delayTime){
  32392. if(!this.list.includes(name)){ //如果没有该项, 则开始判断
  32393. var needWait = func(); //触发了改变,则等待一段时间后再自动判断
  32394. if(needWait){
  32395. this.list.push(name);
  32396. setTimeout(()=>{
  32397. var a = this.list.indexOf(name);
  32398. this.list.splice(a,1);
  32399. this.isWaiting(name, func, delayTime) //循环
  32400. },delayTime)
  32401. }
  32402. }
  32403. }, */
  32404. isWaiting:function(name, func, delayTime/* , autoCycle */){
  32405. let item = this.list.find(e=>e.name == name);
  32406. if(!item){ //如果没有该项, 则加入循环
  32407. let ifContinue = func();
  32408. item = {name, func, delayTime};
  32409. this.list.push(item);
  32410. setTimeout(()=>{
  32411. var a = this.list.indexOf(item);
  32412. this.list.splice(a,1);
  32413. let {func, delayTime} = item;
  32414. if(item.requestUpdate || ifContinue ) this.isWaiting(name, func, delayTime); //循环
  32415. },delayTime);
  32416. }else {//如果有该项,说明现在请求下一次继续更新
  32417. //if(delayTime == 0){//想立刻更新一次
  32418. // func()
  32419. //}else{
  32420. //更新属性
  32421. item.func = func;
  32422. item.delayTime = delayTime;
  32423. item.requestUpdate = true;
  32424. //}
  32425. }
  32426. },
  32427. }
  32428. ,
  32429. pushToGroupAuto : function(items, groups, recognizeFunction){//自动分组。 items是将分到一起的组合。items.length = 1 or 2.
  32430. recognizeFunction = recognizeFunction || function(){};
  32431. var atGroups = groups.filter(group=>group.find(
  32432. item => items[0] == item || recognizeFunction(item, items[0]) || items[1] == item || items[1] && recognizeFunction(item, items[1])
  32433. ));
  32434. if(atGroups.length){//在不同组
  32435. //因为items是一组的,所以先都放入组1
  32436. items.forEach(item=> {if(!atGroups[0].includes(item)) atGroups[0].push(item);});
  32437. if(atGroups.length>1){//如果在不同组,说明这两个组需要合并
  32438. var combineGroup = [];
  32439. atGroups.forEach(group=>{
  32440. combineGroup = Common$1.getUnionSet(combineGroup, group);
  32441. groups.splice(groups.indexOf(group),1);
  32442. });
  32443. groups.push(combineGroup);
  32444. }
  32445. }else {//直接加入为一组
  32446. groups.push(items);
  32447. }
  32448. },
  32449. getBestCount : (function(){
  32450. let lastCount = {};
  32451. return function(name, minCount=1,maxCount=6, durBound1 = 1.2, durBound2 = 10, ifLog, maxHistory){
  32452. let timeStamp = performance.getEntriesByName("loop-start");
  32453. let count;
  32454. if(timeStamp.length){
  32455. let dur = performance.now() - timeStamp[timeStamp.length-1].startTime; //dur在iphoneX中静止有7,pc是2
  32456. count = Math.round(math.linearClamp(dur, durBound1,durBound2, maxCount, minCount));
  32457. if (maxHistory) {
  32458. if (!lastCount[name]) lastCount[name] = [];
  32459. if (count == 0 && lastCount[name].length > maxHistory - 1 && !lastCount[name].some(e => e > 0)) {
  32460. count = 1;
  32461. }
  32462. lastCount[name].push(count);
  32463. if (lastCount[name].length > maxHistory) lastCount[name].splice(0, 1);
  32464. }
  32465. if(ifLog){//注意,console.log本身用时挺高, 降4倍时可能占用0.5毫秒
  32466. name && count && console.log(name, count , ' ,dur:', dur.toFixed(3));
  32467. }
  32468. }else {
  32469. count = maxCount; // ?
  32470. }
  32471. //主要在手机端有效果。
  32472. return count
  32473. }
  32474. })(),
  32475. batchHandling : {//分批处理
  32476. lists:[],
  32477. getSlice : function(name, items , {stopWhenAllUsed, min=5,max=100, durBound1 , durBound2, useEquals , maxUseCount}){
  32478. if(items.length == 0 ||
  32479. ((maxUseCount = maxUseCount == void 0 ? Common$1.getBestCount(name, min,max , durBound1, durBound2 /* , true */ ) : maxUseCount), !maxUseCount) //本次最多可以使用的个数
  32480. ){
  32481. return {list:[]}
  32482. }
  32483. if(!this.lists[name]) this.lists[name] = {list:[] };
  32484. //更新列表项目,但不变原来的顺序
  32485. let list = this.lists[name].list.filter(a=>items.some(item=> useEquals ? a.item.equals(item) : a.item == item));//去掉已经不在items里的项目
  32486. this.lists[name].list = list;
  32487. items.forEach(item=>{//增加新的项目。
  32488. if(!list.some(a=>useEquals ? a.item.equals(item) : a.item == item )){
  32489. list.push({item, count:0});
  32490. }
  32491. });
  32492. //至此,在后排的都是未使用的
  32493. let unUsed = list.filter(e=>e.count == 0);//未使用的项目(count为0)优先
  32494. let result = [];
  32495. unUsed.slice(0,maxUseCount).forEach(e=>{
  32496. result.push(e.item);
  32497. e.count ++;
  32498. });
  32499. if(unUsed.length > maxUseCount){
  32500. //还是剩有未使用的项目,等待下一次
  32501. }else {
  32502. //所有项目都能使用一次
  32503. if(!stopWhenAllUsed){ //若不是全部使用就停止
  32504. let wholeCount = Math.min(items.length, maxUseCount);
  32505. let restCount = wholeCount - result.length; //补齐
  32506. list.slice(0,restCount).forEach(e=>{
  32507. result.push(e.item);
  32508. e.count ++;
  32509. });
  32510. }
  32511. list.forEach(e=>e.count--); //复原,等待新的循环
  32512. }
  32513. /* result.forEach((e,i)=>{//有重复的
  32514. if( result.slice(0,i).some(a=>a.equals(e)) || result.slice(i+1).some(a=>a.equals(e)) ) {
  32515. console.log(e)
  32516. }
  32517. }) */
  32518. return {list:result }
  32519. }
  32520. },
  32521. getRootWindow(){//获取包含Potree的根window
  32522. let win = window;
  32523. try{
  32524. while(win.parent!=win && win.parent.Potree){
  32525. win = win.parent;
  32526. }
  32527. if(window != win)return win
  32528. }catch(e){
  32529. //console.log(e) //可能跨域,从而win.parent.Potree报错
  32530. console.log('getRootWindow 跨域');
  32531. return
  32532. }
  32533. },
  32534. watch: function(object, propName, initialValue){ //监听某个属性的变化
  32535. let v = initialValue;
  32536. Object.defineProperty(object, propName, {
  32537. get: function() {
  32538. return v
  32539. },
  32540. set: function(e) {
  32541. console.warn('watch:',propName, e);
  32542. v = e;
  32543. }
  32544. });
  32545. },
  32546. };
  32547. Potree.Common = Common$1;
  32548. class View{//base
  32549. constructor () {
  32550. this.position = new Vector3(0, 0, 0);
  32551. this.yaw = Math.PI / 4;
  32552. this._pitch = -Math.PI / 4;
  32553. this.radius = 1;
  32554. this.maxPitch = Math.PI / 2;
  32555. this.minPitch = -Math.PI / 2;
  32556. }
  32557. clone () {
  32558. let c = new View();
  32559. c.yaw = this.yaw;
  32560. c._pitch = this.pitch;
  32561. c.radius = this.radius;
  32562. c.maxPitch = this.maxPitch;
  32563. c.minPitch = this.minPitch;
  32564. return c;
  32565. }
  32566. get pitch () {
  32567. return this._pitch;
  32568. }
  32569. set pitch (angle) {
  32570. this._pitch = Math.max(Math.min(angle, this.maxPitch), this.minPitch);
  32571. }
  32572. get direction () {
  32573. let dir = new Vector3(0, 1, 0);
  32574. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  32575. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  32576. return dir;
  32577. }
  32578. set direction (dir) {
  32579. dir = dir.clone().normalize();//add
  32580. if(dir.x === 0 && dir.y === 0){
  32581. this.pitch = Math.PI / 2 * Math.sign(dir.z);
  32582. //this.yaw = 0 //add:还是要指定一下, 否则不统一
  32583. }else {
  32584. let yaw = Math.atan2(dir.y, dir.x) - Math.PI / 2;
  32585. let pitch = Math.atan2(dir.z, Math.sqrt(dir.x * dir.x + dir.y * dir.y));
  32586. this.yaw = yaw;
  32587. this.pitch = pitch;
  32588. }
  32589. }
  32590. lookAt(t){//setPivot
  32591. let V;
  32592. if(arguments.length === 1){
  32593. V = new Vector3().subVectors(t, this.position);
  32594. }else if(arguments.length === 3){
  32595. V = new Vector3().subVectors(new Vector3(...arguments), this.position);
  32596. }
  32597. let radius = V.length();
  32598. let dir = V.normalize();
  32599. this.radius = radius;
  32600. this.direction = dir;
  32601. }
  32602. getPivot () {
  32603. return new Vector3().addVectors(this.position, this.direction.multiplyScalar(this.radius));
  32604. }
  32605. getSide () {
  32606. let side = new Vector3(1, 0, 0);
  32607. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  32608. return side;
  32609. }
  32610. pan (x, y) {
  32611. let dir = new Vector3(0, 1, 0);
  32612. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  32613. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  32614. // let side = new THREE.Vector3(1, 0, 0);
  32615. // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  32616. let side = this.getSide();
  32617. let up = side.clone().cross(dir);
  32618. let pan = side.multiplyScalar(x).add(up.multiplyScalar(y));
  32619. this.position = this.position.add(pan);
  32620. // this.target = this.target.add(pan);
  32621. }
  32622. translate (x, y, z) {
  32623. let dir = new Vector3(0, 1, 0);
  32624. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  32625. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  32626. let side = new Vector3(1, 0, 0);
  32627. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  32628. let up = side.clone().cross(dir);
  32629. let t = side.multiplyScalar(x)
  32630. .add(dir.multiplyScalar(y))
  32631. .add(up.multiplyScalar(z));
  32632. this.position = this.position.add(t);
  32633. }
  32634. translateWorld (x, y, z) {
  32635. this.position.x += x;
  32636. this.position.y += y;
  32637. this.position.z += z;
  32638. }
  32639. setView(position, target, duration = 0, callback = null){
  32640. let endPosition = null;
  32641. if(position instanceof Array){
  32642. endPosition = new Vector3(...position);
  32643. }else if(position.x != null){
  32644. endPosition = position.clone();
  32645. }
  32646. let endTarget = null;
  32647. if(target instanceof Array){
  32648. endTarget = new Vector3(...target);
  32649. }else if(target.x != null){
  32650. endTarget = target.clone();
  32651. }
  32652. const startPosition = this.position.clone();
  32653. const startTarget = this.getPivot();
  32654. //const endPosition = position.clone();
  32655. //const endTarget = target.clone();
  32656. let easing = TWEEN.Easing.Quartic.Out;
  32657. if(duration === 0){
  32658. this.position.copy(endPosition);
  32659. this.lookAt(endTarget);
  32660. }else {
  32661. let value = {x: 0};
  32662. let tween = new TWEEN.Tween(value).to({x: 1}, duration);
  32663. tween.easing(easing);
  32664. //this.tweens.push(tween);
  32665. tween.onUpdate(() => {
  32666. let t = value.x;
  32667. //console.log(t);
  32668. const pos = new Vector3(
  32669. (1 - t) * startPosition.x + t * endPosition.x,
  32670. (1 - t) * startPosition.y + t * endPosition.y,
  32671. (1 - t) * startPosition.z + t * endPosition.z,
  32672. );
  32673. const target = new Vector3(
  32674. (1 - t) * startTarget.x + t * endTarget.x,
  32675. (1 - t) * startTarget.y + t * endTarget.y,
  32676. (1 - t) * startTarget.z + t * endTarget.z,
  32677. );
  32678. this.position.copy(pos);
  32679. this.lookAt(target);
  32680. });
  32681. tween.start();
  32682. tween.onComplete(() => {
  32683. if(callback){
  32684. callback();
  32685. }
  32686. });
  32687. }
  32688. }
  32689. };
  32690. let sid = 0;
  32691. class ExtendView extends View {
  32692. constructor () {
  32693. super();
  32694. this.yaw = 0; //Math.PI / 4; // = 4dkk lon + 90
  32695. this._pitch = 0; //-Math.PI / 4; //上下旋转 = 4dkk lat
  32696. this.sid = sid++;
  32697. this.LookTransition = 'LookTransition'+this.sid;
  32698. this.FlyTransition = 'FlyTransition'+this.sid;
  32699. }
  32700. //add------
  32701. applyToCamera(camera){
  32702. camera.position.copy(this.position);
  32703. camera.rotation.copy(this.rotation);
  32704. camera.updateMatrix();
  32705. camera.updateMatrixWorld();
  32706. //camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  32707. }
  32708. get rotation(){
  32709. var rotation = new Euler;
  32710. rotation.order = "ZXY";
  32711. rotation.x = Math.PI / 2 + this.pitch;
  32712. rotation.z = this.yaw;
  32713. return rotation
  32714. }
  32715. set rotation(rotation){
  32716. if(rotation.y != 0){//因为 rotation的y不一定是0 , 所以不能直接逆着get rotation写。
  32717. //console.error('set rotation y不为0!!!!?', rotation ) //过渡时因为quaternion lerp所以不为0。没办法了orz
  32718. this.direction = new Vector3(0,0,-1).applyEuler(rotation); //转回direction有损耗,在俯视时的(dir.x==dir.y==0), 丢失yaw信息从而 yaw无法获取(希望不要遇到这种情况,如果有的话,考虑先计算yaw,似乎好像可以算)
  32719. }else {//尽量不用direction
  32720. this.pitch = rotation.x - Math.PI / 2;
  32721. this.yaw = rotation.z;
  32722. }
  32723. }
  32724. get quaternion(){
  32725. return new Quaternion().setFromEuler(this.rotation)
  32726. }
  32727. set quaternion(q){
  32728. this.rotation = new Euler().setFromQuaternion(q);
  32729. }
  32730. copy(a){
  32731. Common$1.CopyClassObject(this, a, {ignoreList: ['_listeners']});
  32732. }
  32733. clone () {
  32734. return Common$1.CloneClassObject(this, {ignoreList: ['_listeners']})
  32735. }
  32736. //----------
  32737. setCubeView(dir) {
  32738. switch(dir) {
  32739. case "front":
  32740. this.yaw = 0;
  32741. this.pitch = 0;
  32742. break;
  32743. case "back":
  32744. this.yaw = Math.PI;
  32745. this.pitch = 0;
  32746. break;
  32747. case "left":
  32748. this.yaw = -Math.PI / 2;
  32749. this.pitch = 0;
  32750. break;
  32751. case "right":
  32752. this.yaw = Math.PI / 2;
  32753. this.pitch = 0;
  32754. break;
  32755. case "top":
  32756. this.yaw = 0;
  32757. this.pitch = -Math.PI / 2;
  32758. break;
  32759. case "bottom":
  32760. this.yaw = -Math.PI;
  32761. this.pitch = Math.PI / 2;
  32762. break;
  32763. }
  32764. }
  32765. /* pan (x, y) {
  32766. let dir = new THREE.Vector3(0, 1, 0);
  32767. dir.applyAxisAngle(new THREE.Vector3(1, 0, 0), this.pitch);
  32768. dir.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  32769. // let side = new THREE.Vector3(1, 0, 0);
  32770. // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  32771. let side = this.getSide();
  32772. let up = side.clone().cross(dir);
  32773. let pan = side.multiplyScalar(x).add(up.multiplyScalar(y));
  32774. this.position = this.position.add(pan);
  32775. // this.target = this.target.add(pan);
  32776. } */
  32777. pan (x, y) { //发现pan其实就是translate
  32778. this.translate(x, 0, y);
  32779. }
  32780. translate (x, y, z, forceHorizon ) {
  32781. //相机方向
  32782. let dir = new Vector3(0, 1, 0);
  32783. dir.applyAxisAngle(new Vector3(1, 0, 0), forceHorizon ? 0 : this.pitch); //上下角度
  32784. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);//水平角度
  32785. let side = new Vector3(1, 0, 0);
  32786. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); //垂直于相机当前水平朝向的 左右方向
  32787. let up = side.clone().cross(dir); //垂直于相机当前水平朝向的 向上方向
  32788. let t = side.multiplyScalar(x) //x影响 左右分量
  32789. .add(dir.multiplyScalar(y)) //y影响 前后分量
  32790. .add(up.multiplyScalar(z)); //z影响 上下分量
  32791. this.position = this.position.add(t);
  32792. if((!math.closeTo(x, 0, 1e-2) || !math.closeTo(y, 0, 1e-2) || !math.closeTo(z, 0, 1e-2)) && Potree.settings.displayMode != 'showPanos'){
  32793. this.cancelFlying('pos');
  32794. }
  32795. this.restrictPos();
  32796. }
  32797. translateWorld (x, y, z) {
  32798. super.translateWorld(x, y, z);
  32799. if((!math.closeTo(x, 0, 1e-2) || !math.closeTo(y, 0, 1e-2) || !math.closeTo(z, 0, 1e-2)) && Potree.settings.displayMode != 'showPanos'){
  32800. this.cancelFlying('pos');
  32801. }
  32802. this.restrictPos();
  32803. }
  32804. restrictPos(position){//add
  32805. if(this.limitBound){
  32806. (position || this.position).clamp(this.limitBound.min, this.limitBound.max);
  32807. }
  32808. }
  32809. isFlying(type='all'){
  32810. let a = transitions.getById(this.FlyTransition).length > 0;
  32811. let b = transitions.getById(this.LookTransition).length > 0;
  32812. return type == 'pos' ? a : type == 'rotate' ? b : (a || b)
  32813. }
  32814. cancelFlying(type='all', dealCancel=true){//外界只能通过这个来cancel
  32815. type == 'pos' ? transitions.cancelById(this.FlyTransition, dealCancel )
  32816. : type == 'rotate' ? transitions.cancelById(this.LookTransition, dealCancel )
  32817. : (transitions.cancelById(this.FlyTransition, dealCancel ), transitions.cancelById(this.LookTransition, dealCancel ));
  32818. //console.log('cancelFlying ' , this.sid, type)
  32819. }
  32820. setView( info = {}){
  32821. // position, target, duration = 0, callback = null, onUpdate = null, Easing='', cancelFun
  32822. this.cancelFlying();
  32823. let posWaitDone, rotWaitDone , dir;
  32824. let posDone = ()=>{
  32825. rotWaitDone || done();
  32826. posWaitDone = false;
  32827. };
  32828. let rotDone = ()=>{
  32829. if(endTarget){
  32830. this.lookAt(endTarget); //compute radius for orbitcontrol
  32831. }else if(endQuaternion){
  32832. this.rotation = new Euler().setFromQuaternion(endQuaternion);
  32833. }else if(endYaw != void 0){
  32834. this.yaw = endYaw, this.pitch = endPitch;
  32835. }
  32836. //if(dir.x == 0 && dir.y == 0)this.yaw = 0 //统一一下 朝上的话是正的。朝下的一般不是0,会保留一个接近0的小数所以不用管
  32837. posWaitDone || done();
  32838. rotWaitDone = false;
  32839. };
  32840. let done = ()=>{ //一定要旋转和位移都结束了才能执行
  32841. let f = ()=>{
  32842. this.position.copy(endPosition); //因为延时1后control的update会导致位置改变
  32843. info.callback && info.callback();
  32844. this.dispatchEvent('flyingDone');
  32845. };
  32846. if(info.duration){
  32847. setTimeout(f,1);//延迟是为了使isFlying先为false
  32848. }else {
  32849. f(); //有的需要迅速执行回调
  32850. }
  32851. };
  32852. let endPosition = new Vector3().copy(info.position);
  32853. let startPosition = this.position.clone();
  32854. let startQuaternion, endQuaternion, endTarget = null,
  32855. endYaw, startYaw, endPitch, startPitch ;
  32856. this.restrictPos(endPosition);
  32857. if(info.endYaw == void 0){
  32858. if(info.target ){
  32859. endTarget = new Vector3().copy(info.target);
  32860. endQuaternion = math.getQuaFromPosAim(endPosition,endTarget); //若为垂直,会自动偏向x负的方向
  32861. }else if(info.quaternion){
  32862. endQuaternion = info.quaternion.clone();
  32863. }
  32864. if(endQuaternion && math.closeTo(Math.abs(this.direction.z), 1, 1e-4)){ //在垂直的视角下的quaternion刚开始突变的厉害,这时候可能渐变yaw比较好(如俯视时点击测量线)
  32865. let a = this.clone();
  32866. a.quaternion = endQuaternion;
  32867. info.endYaw = a.yaw; info.endPitch = a.pitch;
  32868. console.log('turn to yaw');
  32869. }
  32870. }
  32871. if(info.endYaw != void 0) {
  32872. startPitch = this.pitch;
  32873. endPitch = info.endPitch;
  32874. startYaw = this.yaw;
  32875. endYaw = info.endYaw;
  32876. if(Math.abs(startYaw - endYaw)>Math.PI){//如果差距大于半个圆,就要反个方向转(把大的那个数字减去360度)
  32877. startYaw > endYaw ? (startYaw -= Math.PI*2) : (endYaw -= Math.PI*2);
  32878. }
  32879. console.log('startYaw', startYaw, 'endYaw', endYaw);
  32880. }
  32881. if(endQuaternion){
  32882. startQuaternion = this.quaternion;
  32883. }
  32884. if(!info.duration){
  32885. this.position.copy(endPosition);
  32886. this.restrictPos();
  32887. posWaitDone = true, rotWaitDone = true;
  32888. info.onUpdate && info.onUpdate(1);
  32889. posDone();
  32890. rotDone();
  32891. }else {
  32892. info.onUpdate && info.onUpdate(0); //初始化progress
  32893. let posChange = !this.position.equals(endPosition);
  32894. if(posChange){
  32895. posWaitDone = true;
  32896. transitions.start(lerp.vector(this.position, endPosition, (pos, progress, delta)=>{
  32897. info.onUpdate && info.onUpdate(progress, delta);
  32898. }), info.duration, posDone , 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine ,null, this.FlyTransition, ()=>{
  32899. //中途取消
  32900. if(endTarget ){
  32901. /* endPosition = new THREE.Vector3().copy(this.position)//更改旋转的endQuaternion
  32902. endQuaternion = math.getQuaFromPosAim(endPosition,endTarget) */
  32903. //直接改变endQuaternion会突变,所以还是cancel吧
  32904. this.cancelFlying('rotate');
  32905. }
  32906. posWaitDone = false;
  32907. info.cancelFun && info.cancelFun();
  32908. }, info.ignoreFirstFrame);
  32909. }
  32910. if(endQuaternion || endYaw != void 0){
  32911. rotWaitDone = true;
  32912. transitions.start( (progress, delta )=>{
  32913. if(endYaw != void 0){
  32914. this.yaw = startYaw * (1-progress) + endYaw * progress;
  32915. this.pitch = startPitch * (1-progress) + endPitch * progress;
  32916. }else {
  32917. let quaternion = (new Quaternion()).copy(startQuaternion);
  32918. lerp.quaternion(quaternion, endQuaternion)(progress); //在垂直的视角下的角度突变的厉害,这时候可能渐变yaw比较好
  32919. this.quaternion = quaternion;
  32920. //console.log(quaternion,this.yaw)
  32921. }
  32922. posChange || info.onUpdate && info.onUpdate(progress, delta);
  32923. }, info.duration, rotDone , 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine ,null, this.LookTransition, ()=>{
  32924. //中途取消
  32925. rotWaitDone = false;
  32926. info.cancelFun && info.cancelFun();
  32927. }, info.ignoreFirstFrame);
  32928. }
  32929. /* transitions.start(lerp.vector(this.position, endPosition, (pos, progress)=>{
  32930. let t = progress
  32931. if(endQuaternion){
  32932. let quaternion = (new THREE.Quaternion()).copy(startQuaternion)
  32933. lerp.quaternion(quaternion, endQuaternion)(progress),
  32934. this.rotation = new THREE.Euler().setFromQuaternion(quaternion)
  32935. }
  32936. this.restrictPos()
  32937. //console.log('setView flying')
  32938. info.onUpdate && info.onUpdate(t)//add
  32939. }), info.duration, done, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine ,null, this.LookTransition, info.cancelFun); //easeInOutQuad
  32940. */
  32941. }
  32942. }
  32943. //平移Ortho相机
  32944. moveOrthoCamera(viewport, info, duration, easeName){//boundSize优先于endZoom。
  32945. let camera = info.camera || viewport.camera;
  32946. let startZoom = camera.zoom;
  32947. let endPosition = info.endPosition;
  32948. let boundSize = info.boundSize;
  32949. let endZoom = info.endZoom;
  32950. let margin = info.margin || {x:0,y:0};/* 200 */ //像素
  32951. let onUpdate = info.onUpdate;
  32952. if(info.bound){//需要修改boundSize以适应相机的旋转,当相机不在xy水平面上朝向z时
  32953. endPosition = endPosition || info.bound.getCenter(new Vector3());
  32954. let matrixRot = new Matrix4().makeRotationFromEuler(this.rotation).invert();
  32955. let boundingBox = info.bound.clone().applyMatrix4(matrixRot);
  32956. boundSize = boundingBox.getSize(new Vector3());
  32957. }
  32958. if(boundSize && boundSize.x == 0 && boundSize.y == 0){
  32959. boundSize.set(1,1); //避免infinity
  32960. }
  32961. this.setView( Object.assign(info, { position:endPosition, duration,
  32962. onUpdate:(progress, delta)=>{
  32963. if(boundSize || endZoom){
  32964. if(boundSize){
  32965. let aspect = boundSize.x / boundSize.y;
  32966. let w, h;
  32967. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  32968. h = boundSize.y;
  32969. endZoom = (viewport.resolution.y - margin.y) / h; //注意,要在resolution不为0时执行
  32970. }else {
  32971. w = boundSize.x;
  32972. endZoom = (viewport.resolution.x - margin.x) / w;
  32973. }
  32974. //onUpdate时更新endzoom是因为画布大小可能更改
  32975. }
  32976. camera.zoom = endZoom * progress + startZoom * (1 - progress);
  32977. camera.updateProjectionMatrix();
  32978. onUpdate && onUpdate(progress, delta);
  32979. }
  32980. },
  32981. Easing:easeName
  32982. }));
  32983. }
  32984. zoomOrthoCamera(camera, endZoom, pointer, duration, onProgress){//定点缩放
  32985. let startZoom = camera.zoom;
  32986. let pointerPos = new Vector3(pointer.x, pointer.y,0.5);
  32987. transitions.start(( progress)=>{
  32988. let oldPos = pointerPos.clone().unproject(camera);
  32989. camera.zoom = endZoom * progress + startZoom * (1 - progress);
  32990. camera.updateProjectionMatrix();
  32991. let newPos = pointerPos.clone().unproject(camera);
  32992. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  32993. let moveVec = new Vector3().subVectors(newPos, oldPos);
  32994. camera.position.sub(moveVec);
  32995. this.position.copy(camera.position);
  32996. onProgress && onProgress();
  32997. } , duration, null/* done */, 0, easing.easeInOutSine, null, "zoomInView"/* , info.cancelFun */);
  32998. }
  32999. tranCamera(viewport, info, duration, easeName){
  33000. viewport.camera = info.midCamera;
  33001. //viewport.camera.matrixWorld = info.endCamera.matrixWorld
  33002. //viewer.setCameraMode(CameraMode.ORTHOGRAPHIC)
  33003. info.midCamera.projectionMatrix.copy(info.startCamera.projectionMatrix);
  33004. let onUpdate = info.onUpdate;
  33005. info.onUpdate = (progress, delta)=>{
  33006. lerp.matrix4(info.midCamera.projectionMatrix, info.endCamera.projectionMatrix)(progress);
  33007. onUpdate && onUpdate(progress, delta);
  33008. };
  33009. let callback = info.callback;
  33010. info.callback = ()=>{
  33011. viewport.camera = info.endCamera;
  33012. viewer.scene.measurements.forEach((e)=>{
  33013. Potree.Utils.updateVisible(e, 'tranCamera', true);
  33014. });
  33015. this.applyToCamera(viewport.camera);
  33016. viewer.dispatchEvent({type:'camera_changed', viewport:viewer.mainViewport, changeInfo:{}});//update sprite
  33017. callback && callback();
  33018. };
  33019. //info.forbitCancel = true
  33020. info.camera = info.endCamera;
  33021. if(info.camera.type == "OrthographicCamera"){
  33022. this.moveOrthoCamera(viewport, info, duration, easeName);
  33023. }else {
  33024. this.setView( Object.assign(info, { duration}) );
  33025. }
  33026. }
  33027. };
  33028. var math = {
  33029. getBaseLog(x, y) {//返回以 x 为底 y 的对数(即 logx y) . Math.log 返回一个数的自然对数
  33030. return Math.log(y) / Math.log(x);
  33031. }
  33032. ,
  33033. convertVector : {
  33034. ZupToYup: function(e){//navvis -> 4dkk
  33035. return new Vector3(e.x,e.z,-e.y)
  33036. },
  33037. YupToZup: function(e){//4dkk -> navvis
  33038. return new Vector3(e.x,-e.z,e.y)
  33039. },
  33040. },
  33041. convertQuaternion: {
  33042. ZupToYup: function(e){//navvis -> 4dkk //不同于convertVisionQuaternion
  33043. let rotation = new Euler(-Math.PI/2,0,0);
  33044. let quaternion = new Quaternion().setFromEuler(rotation);
  33045. return e.clone().premultiply(quaternion)
  33046. //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)))
  33047. },
  33048. YupToZup: function(e){//4dkk -> navvis
  33049. let rotation = new Euler(Math.PI/2,0,0);
  33050. let quaternion = new Quaternion().setFromEuler(rotation);
  33051. return e.clone().premultiply(quaternion)
  33052. },
  33053. },
  33054. convertVisionQuaternion: function(e) {
  33055. return new Quaternion(e.x,e.z,-e.y,e.w).multiply((new Quaternion).setFromAxisAngle(new Vector3(0,1,0), MathUtils.degToRad(90)))
  33056. },
  33057. invertVisionQuaternion : function(e) {//反转给算法部
  33058. var a = e.clone().multiply((new Quaternion).setFromAxisAngle(new Vector3(0,1,0), MathUtils.degToRad(-90)));
  33059. return new Quaternion(a.x,-a.z,a.y,a.w)
  33060. },
  33061. //------------
  33062. getVec2Angle : function(dir1,dir2){
  33063. return Math.acos( MathUtils.clamp(this.getVec2Cos(dir1,dir2), -1,1) )
  33064. },
  33065. getVec2Cos : function(dir1,dir2){
  33066. return dir1.dot(dir2) / dir1.length() / dir2.length()
  33067. },
  33068. getAngle:function(vec1, vec2, axis){//带方向的角度 vector3
  33069. var angle = vec1.angleTo(vec2);
  33070. var axis_ = vec1.clone().cross(vec2);
  33071. if(typeof axis == 'string'){
  33072. if(axis_[axis] < 0){
  33073. angle *= -1;
  33074. }
  33075. }else {//vector3
  33076. if(axis_.dot(axis)< 0){
  33077. angle *= -1;
  33078. }
  33079. }
  33080. return angle
  33081. },
  33082. closeTo : function(a,b, precision=1e-6){
  33083. let f = (a,b)=>{
  33084. return Math.abs(a-b) < precision;
  33085. };
  33086. if(typeof (a) == 'number'){
  33087. return f(a, b);
  33088. }else {
  33089. let judge = (name)=>{
  33090. if(a[name] == void 0)return true //有值就判断,没值就不判断
  33091. else return f(a[name],b[name])
  33092. };
  33093. return judge('x') && judge('y') && judge('z') && judge('w')
  33094. }
  33095. },
  33096. toPrecision: function (e, t) {//xzw change 保留小数
  33097. var f = function (e, t) {
  33098. var i = Math.pow(10, t);
  33099. return Math.round(e * i) / i
  33100. };
  33101. if (e instanceof Array) {
  33102. for (var s = 0; s < e.length; s++) {
  33103. e[s] = f(e[s], t);
  33104. }
  33105. return e;
  33106. } else if (e instanceof Object) {
  33107. for (var s in e) {
  33108. e[s] = f(e[s], t);
  33109. }
  33110. return e;
  33111. } else if(typeof e == 'number'){
  33112. return f(e, t)
  33113. }else {
  33114. return e
  33115. }
  33116. },
  33117. isEmptyQuaternion: function(e) {
  33118. return 0 === Math.abs(e.x) && 0 === Math.abs(e.y) && 0 === Math.abs(e.z) && 0 === Math.abs(e.w)
  33119. },
  33120. projectPositionToCanvas: function(e, t, i) {
  33121. i = i || new Vector3,
  33122. i.copy(e);
  33123. var r = .5 * $('#player').width()
  33124. , o = .5 * $('#player').height();
  33125. return i.project(t),
  33126. i.x = i.x * r + r,
  33127. i.y = -(i.y * o) + o,
  33128. i
  33129. },
  33130. handelPadResize:false,
  33131. /* handelPadding : function () { //去除player左边和上面的宽高,因为pc的player左上有其他element 许钟文
  33132. var pads = [];//记录下来避免反复计算
  33133. var index = [];
  33134. var resetPad = function(){
  33135. pads = [];
  33136. index = [];
  33137. math.handelPadResize = false; //switchview时resized为true
  33138. }
  33139. if(config.isEdit && !config.isMobile){
  33140. window.addEventListener('resize',resetPad);
  33141. }
  33142. return function(x, y, domE){
  33143. if(!config.isEdit || config.isMobile) {
  33144. return {
  33145. x: x,
  33146. y: y
  33147. }
  33148. }
  33149. if(this.handelPadResize)resetPad();
  33150. domE = domE || $('#player')[0];
  33151. var pad;
  33152. var i = index.indexOf(domE);
  33153. if (i == -1){
  33154. index.push(domE);
  33155. pad = {
  33156. x: this.getOffset("left", domE),
  33157. y: this.getOffset("top", domE)
  33158. }
  33159. pads.push(pad)
  33160. }
  33161. else pad = pads[i];
  33162. return {
  33163. x: x - pad.x,
  33164. y: y - pad.y
  33165. }
  33166. }
  33167. }(), */
  33168. getOffset: function (type, element, parent) {//获取元素的边距 许钟文
  33169. var offset = (type == "left") ? element.offsetLeft : element.offsetTop;
  33170. if (!parent) parent = $("body")[0];
  33171. while (element = element.offsetParent) {
  33172. if (element == parent) break;
  33173. offset += (type == "left") ? element.offsetLeft : element.offsetTop;
  33174. }
  33175. return offset;
  33176. }
  33177. ,
  33178. constrainedTurn: function(e) {
  33179. var t = e % (2 * Math.PI);
  33180. return t = t > Math.PI ? t -= 2 * Math.PI : t < -Math.PI ? t += 2 * Math.PI : t
  33181. },
  33182. getFOVDotThreshold: function(e) {
  33183. return Math.cos(MathUtils.degToRad(e / 2))
  33184. },
  33185. transform2DForwardVectorByCubeFace: function(e, t, i, n) {
  33186. switch (e) {
  33187. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  33188. i.set(1, t.y, t.x);
  33189. break;
  33190. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  33191. i.set(-1, t.y, -t.x);
  33192. break;
  33193. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  33194. i.set(-t.x, 1, -t.y);
  33195. break;
  33196. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  33197. i.set(-t.x, -1, t.y);
  33198. break;
  33199. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  33200. i.set(-t.x, t.y, 1);
  33201. break;
  33202. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  33203. i.set(t.x, t.y, -1);
  33204. }
  33205. n && i.normalize();
  33206. },
  33207. getFootPoint : function(oldPos, p1, p2, restricInline){ //找oldPos在线段p1, p2上的垂足
  33208. /* if(isWorld){//输出全局坐标 需要考虑meshGroup.position
  33209. p1 = p1.clone();
  33210. p2 = p2.clone();
  33211. p1.y += mainDesign.meshGroup.position.y;
  33212. p2.y += mainDesign.meshGroup.position.y;
  33213. } */
  33214. if(p1.equals(p2))return p1.clone()
  33215. var op1 = oldPos.clone().sub(p1);
  33216. var p1p2 = p1.clone().sub(p2);
  33217. var p1p2Len = p1p2.length();
  33218. var leftLen = op1.dot(p1p2) / p1p2Len;
  33219. var pos = p1.clone().add(p1p2.multiplyScalar( leftLen/p1p2Len ));
  33220. if(restricInline && pos.clone().sub(p1).dot( pos.clone().sub(p2) ) > 0){//foot不在线段上
  33221. if(pos.distanceTo(p1) < pos.distanceTo(p2)) pos = p1.clone();
  33222. else pos = p2.clone();
  33223. }
  33224. return pos;
  33225. },
  33226. /**
  33227. * 计算多边形的重心
  33228. * @param {*} points
  33229. */
  33230. getCenterOfGravityPoint : function(mPoints){
  33231. var area = 0.0;//多边形面积
  33232. var Gx = 0.0, Gy = 0.0;// 重心的x、y
  33233. for (var i = 1; i <= mPoints.length; i++) {
  33234. var ix = mPoints[i % mPoints.length].x;
  33235. var iy = mPoints[i % mPoints.length].y;
  33236. var nx = mPoints[i - 1].x;
  33237. var ny = mPoints[i - 1].y;
  33238. var temp = (ix * ny - iy * nx) / 2.0;
  33239. area += temp;
  33240. Gx += temp * (ix + nx) / 3.0;
  33241. Gy += temp * (iy + ny) / 3.0;
  33242. }
  33243. Gx = Gx / area;
  33244. Gy = Gy / area;
  33245. return { x: Gx, y: Gy };
  33246. },
  33247. getBound : function(ring){
  33248. var bound = new Box2();
  33249. for(var j=0,len = ring.length; j<len; j++){
  33250. bound.expandByPoint(ring[j]);
  33251. }
  33252. return bound;
  33253. },
  33254. isPointInArea : function(ring, holes, point, ifAtLine){//判断点是否在某个环内, 若传递了holes代表还要不能在内环内
  33255. var bound = this.getBound(ring);
  33256. if(point.x < bound.min.x || point.x > bound.max.x || point.y < bound.min.y || point.y > bound.max.y)return false;
  33257. var inside = false;
  33258. var x = point.x,
  33259. y = point.y;
  33260. for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
  33261. var xi = ring[i].x,
  33262. yi = ring[i].y;
  33263. var xj = ring[j].x,
  33264. yj = ring[j].y;
  33265. if((xi - x)*(yj - y) == (xi - x)*(yi - y) && x>=Math.min(xi,xj) && x<=Math.max(xi,xj)//xzw add
  33266. && y>=Math.min(yi,yj) && y<=Math.max(yi,yj)
  33267. ){
  33268. //return !!ifAtLine;//在线段上,则判断为…… (默认在外)
  33269. return {atLine:true}
  33270. }
  33271. if (((yi > y) != (yj > y)) &&
  33272. (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
  33273. ) {
  33274. inside = !inside;
  33275. }
  33276. }
  33277. if(inside && holes){
  33278. return !holes.some(ring=>this.isPointInArea(ring, null, point, ifAtLine) ) //不能存在于任何一个二级内环内
  33279. }else {
  33280. return inside;
  33281. }
  33282. },
  33283. getArea : function (ring) { //求面积 顺时针为正 来自three shape
  33284. for (var t = ring.length, i = 0, n = t - 1, r = 0; r < t; n = r++)
  33285. i += ring[n].x * ring[r].y - ring[r].x * ring[n].y;
  33286. return -.5 * i
  33287. },
  33288. getVolume:function(faceArr){//求三角多面体的体积。和求面积同理都用鞋带计算法 https://blog.csdn.net/weixin_43414513/article/details/123758897
  33289. //问题:怎么确定方向
  33290. //每个三角形的顺序必须是右手螺旋法则指向物体外(外向里看为逆时针),分别为ABC,则每个三角形和原点O构成的三棱锥体积为 (OA cross OB) dot(OC) / 6 . 结果一般朝向原点的为负,反之为正
  33291. },
  33292. isInBetween : function(a, b, c, precision) {
  33293. // 如果b几乎等于a或c,返回false.为了避免浮点运行时两值几乎相等,但存在相差0.00000...0001的这种情况出现使用下面方式进行避免
  33294. /* if (Math.abs(a - b) < 0.000001 || Math.abs(b - c) < 0.000001) {
  33295. return false;
  33296. }
  33297. return (a <= b && b <= c) || (c <= b && b <= a);*/
  33298. //更改:如果b和a或c中一个接近 就算在a和c之间
  33299. return (a <= b && b <= c) || (c <= b && b <= a) || this.closeTo(a,b,precision) || this.closeTo(b,c,precision);
  33300. },
  33301. ifPointAtLineBound:function(point, linePoints, precision){
  33302. //待验证 横线和竖线比较特殊
  33303. return math.isInBetween(linePoints[0].x, point.x, linePoints[1].x, precision) && math.isInBetween(linePoints[0].y, point.y, linePoints[1].y, precision)
  33304. }
  33305. ,
  33306. isLineIntersect: function (line1, line2, notSegment, precision) {//线段和线段是否有交点. notSegment代表是直线而不是线段
  33307. var a1 = line1[1].y - line1[0].y;
  33308. var b1 = line1[0].x - line1[1].x;
  33309. var c1 = a1 * line1[0].x + b1 * line1[0].y;
  33310. //转换成一般式: Ax+By = C
  33311. var a2 = line2[1].y - line2[0].y;
  33312. var b2 = line2[0].x - line2[1].x;
  33313. var c2 = a2 * line2[0].x + b2 * line2[0].y;
  33314. // 计算交点
  33315. var d = a1 * b2 - a2 * b1;
  33316. // 当d==0时,两线平行
  33317. if (d == 0) {
  33318. return false;
  33319. } else {
  33320. var x = (b2 * c1 - b1 * c2) / d;
  33321. var y = (a1 * c2 - a2 * c1) / d;
  33322. // 检测交点是否在两条线段上
  33323. /* if (notSegment || (isInBetween(line1[0].x, x, line1[1].x) || isInBetween(line1[0].y, y, line1[1].y)) &&
  33324. (isInBetween(line2[0].x, x, line2[1].x) || isInBetween(line2[0].y, y, line2[1].y))) {
  33325. return {x,y};
  33326. } */
  33327. if (notSegment || math.ifPointAtLineBound({x,y}, line1, precision) && math.ifPointAtLineBound({x,y}, line2, precision)){
  33328. return {x,y};
  33329. }
  33330. }
  33331. },
  33332. getNormal2d : function(o={} ){//获取二维法向量 方向向内
  33333. var x,y, x1,y1;
  33334. //line2d的向量
  33335. if(o.vec){
  33336. x1 = o.vec.x; y1 = o.vec.y;
  33337. }else {
  33338. x1 = o.p1.x - o.p2.x;
  33339. y1 = o.p1.y - o.p2.y;
  33340. }
  33341. //假设法向量的x或y固定为1或-1
  33342. if(y1 != 0){
  33343. x = 1;
  33344. y = - (x1 * x) / y1;
  33345. }else if(x1 != 0){//y如果为0,正常情况x不会是0
  33346. y = 1;
  33347. x = - (y1 * y) / x1;
  33348. }else {
  33349. console.log("两个点一样");
  33350. return null;
  33351. }
  33352. //判断方向里或者外:
  33353. var vNormal = new Vector3(x, 0, y);
  33354. var vLine = new Vector3(x1, 0, y1);
  33355. var vDir = vNormal.cross(vLine);
  33356. if(vDir.y>0){
  33357. x *= -1;
  33358. y *= -1;
  33359. }
  33360. return new Vector2(x, y).normalize();
  33361. },
  33362. getQuaBetween2Vector:function(oriVec, newVec, upVec){ //获取从oriVec旋转到newVec可以应用的quaternion
  33363. var angle = oriVec.angleTo(newVec);
  33364. var axis = oriVec.clone().cross( newVec).normalize();//两个up之间
  33365. if(axis.length() == 0){//当夹角为180 或 0 度时,得到的axis为(0,0,0),故使用备用的指定upVec
  33366. return new Quaternion().setFromAxisAngle( upVec, angle );
  33367. }
  33368. return new Quaternion().setFromAxisAngle( axis, angle );
  33369. } ,
  33370. /*
  33371. getQuaBetween2Vector2 : function(oriVec, newVec ){//not camera
  33372. var _ = (new THREE.Matrix4).lookAt( oriVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  33373. var aimQua = (new THREE.Quaternion).setFromRotationMatrix(_)
  33374. var _2 = (new THREE.Matrix4).lookAt( newVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  33375. var aimQua2 = (new THREE.Quaternion).setFromRotationMatrix(_2)
  33376. return aimQua2.multiply(aimQua.clone().inverse())
  33377. } */
  33378. getQuaByAim: function (aim, center=new Vector3) {
  33379. let forward = new Vector3(0, 1, 0);
  33380. let qua1 = new Quaternion().setFromUnitVectors(forward, aim.clone().sub(center).normalize());
  33381. /* var _ = (new THREE.Matrix4).lookAt(center,aim, new THREE.Vector3(0,1,0));
  33382. let qua2 = (new THREE.Quaternion).setFromRotationMatrix(_);
  33383. let rot1 = new THREE.Euler().setFromQuaternion(qua1)
  33384. let rot2 = new THREE.Euler().setFromQuaternion(qua2) //奇怪,qua2怎么都不对
  33385. console.log(rot1,rot2) */
  33386. return qua1
  33387. },
  33388. getAimByQua: function (quaternion, center=new Vector3) {
  33389. return new Vector3(0, 0, -1).applyQuaternion(quaternion).add(center)
  33390. },
  33391. getScaleForConstantSize : function(){ //获得规定二维大小的mesh的scale值。可以避免因camera的projection造成的mesh视觉大小改变。 来源:tag.updateDisc
  33392. var w;
  33393. var i = new Vector3, o = new Vector3, l = new Vector3, c = new Vector3, h = new Vector3;
  33394. return function(op={}){
  33395. if(op.width2d) w = op.width2d; //如果恒定二维宽度
  33396. else {//否则考虑上距离,加一丢丢近大远小的效果
  33397. var currentDis, nearBound, farBound;
  33398. if(op.camera.type == "OrthographicCamera"){
  33399. currentDis = 200 / op.camera.zoom; //(op.camera.right - op.camera.left) / op.camera.zoom
  33400. }else {
  33401. currentDis = op.position.distanceTo(op.camera.position);
  33402. }
  33403. w = op.maxSize - ( op.maxSize - op.minSize) * MathUtils.smoothstep(currentDis, op.nearBound, op.farBound);
  33404. //maxSize : mesh要表现的最大像素宽度; nearBound: 最近距离,若比nearBound近,则使用maxSize
  33405. }
  33406. i.copy(op.position).project(op.camera); //tag中心在屏幕上的二维坐标
  33407. o.set(op.resolution.x / 2, op.resolution.y / 2, 1).multiply(i); //转化成px -w/2 到 w/2的范围
  33408. l.set(w / 2, 0, 0).add(o); //加上tag宽度的一半
  33409. c.set(2 / op.resolution.x, 2 / op.resolution.y, 1).multiply(l); //再转回 -1 到 1的范围
  33410. h.copy(c).unproject(op.camera);//再转成三维坐标,求得tag边缘的位置
  33411. var g = h.distanceTo(op.position);//就能得到tag的三维半径
  33412. //这里使用的都是resolution2, 好处是手机端不会太小, 坏处是pc更改网页显示百分比时显示的大小会变(或许可以自己算出设备真实的deviceRatio, 因window.screen是不会改变的),但考虑到用户可以自行调节字大小也许是好的
  33413. return g //可能NAN 当相机和position重叠时
  33414. }
  33415. }()
  33416. ,
  33417. //W , H, left, top分别是rect的宽、高、左、上
  33418. getCrossPointAtRect : function(p1, aim, W , H, left, top){//求射线p1-aim在rect边界上的交点,其中aim在rect范围内,p1则不一定(交点在aim这边的延长线上)
  33419. var x,y, borderX;
  33420. var r = (aim.x - p1.x) / (aim.y - p1.y);//根据相似三角形原理先求出这个比值
  33421. var getX = function(y){
  33422. return r * (y-p1.y) + p1.x;
  33423. };
  33424. var getY = function(x){
  33425. return 1/r * (x-p1.x) + p1.y;
  33426. };
  33427. if(aim.x >= p1.x){
  33428. borderX = W+left;
  33429. }else {
  33430. borderX = left;
  33431. }
  33432. x = borderX;
  33433. y = getY(x);
  33434. if(y < top || y > top+H){
  33435. if(y < top){
  33436. y = top;
  33437. }else {
  33438. y = top+H;
  33439. }
  33440. x = getX(y);
  33441. }
  33442. return new Vector2(x, y);
  33443. },
  33444. getDirFromUV : function(uv){ //获取dir 反向计算 - - 二维转三维比较麻烦
  33445. var dirB; //所求 单位向量
  33446. var y = Math.cos(uv.y * Math.PI); //uv中纵向可以直接确定y, 根据上面getUVfromDir的反向计算
  33447. // 故 uv.y * Math.PI 就是到垂直线(向上)的夹角
  33448. var angle = 2 * Math.PI * uv.x - Math.PI; //x/z代表的是角度
  33449. var axisX, axisZ; //axis为1代表是正,-1是负数
  33450. if (-Math.PI <= angle && angle < 0) {
  33451. axisX = -1; //下半圆
  33452. } else {
  33453. axisX = 1; //上半圆
  33454. }
  33455. if (-Math.PI / 2 <= angle && angle < Math.PI / 2) {
  33456. axisZ = 1; //右半圆
  33457. } else {
  33458. axisZ = -1; //左半圆
  33459. }
  33460. var XDivideZ = Math.tan(angle);
  33461. var z = Math.sqrt((1 - y * y) / (1 + XDivideZ * XDivideZ));
  33462. var x = XDivideZ * z;
  33463. if (z * axisZ < 0) { //异号
  33464. z *= -1;
  33465. x *= -1;
  33466. if (x * axisX < 0) {
  33467. // console.log("wrong!!!!!??????????")
  33468. }
  33469. }
  33470. x *= -1; //计算完成后这里不能漏掉 *= -1
  33471. dirB = this.convertVector.YupToZup(new Vector3(x, y, z));
  33472. //理想状态下x和z和anotherDir相同
  33473. return dirB
  33474. },
  33475. getUVfromDir : function(dir) { //获取UV 同shader里的计算
  33476. var dir = this.convertVector.ZupToYup(dir);
  33477. dir.x *= -1; //计算前这里不能漏掉 *= -1 见shader
  33478. var tx = Math.atan2(dir.x, dir.z) / (Math.PI * 2.0) + 0.5; //atan2(y,x) 返回从 X 轴正向逆时针旋转到点 (x,y) 时经过的角度。区间是-PI 到 PI 之间的值
  33479. var ty = Math.acos(dir.y) / Math.PI;
  33480. return new Vector2(tx, ty)
  33481. //理想状态下tx相同
  33482. },
  33483. getDirByLonLat : function(lon,lat){
  33484. var dir = new Vector3;
  33485. var phi = MathUtils.degToRad(90 - lat);
  33486. var theta = MathUtils.degToRad(lon);
  33487. dir.x = Math.sin(phi) * Math.cos(theta);
  33488. dir.y = Math.cos(phi);
  33489. dir.z = Math.sin(phi) * Math.sin(theta);
  33490. return dir
  33491. } //0,0 => (1,0,0) 270=>(0,0,-1)
  33492. ,
  33493. projectPointAtPlane:function(o={}){//获取一个点在一个面上的投影 {facePoints:[a,b,c], point:}
  33494. var plane = new Plane().setFromCoplanarPoints(...o.facePoints);
  33495. return plane.projectPoint(o.point, new Vector3() )
  33496. }
  33497. ,
  33498. getPolygonsMixedRings:function( polygons, onlyGetOutRing){//{points:[vector2,...],holes:[[],[]]}
  33499. let points = [];
  33500. let lines = [];
  33501. let i = 0;
  33502. polygons.forEach(e=> points.push(...e.map(a=>new Vector2().copy(a) )) );
  33503. polygons.forEach((ps,j)=>{
  33504. let length = ps.length;
  33505. let index = 0;
  33506. while(index<length){
  33507. lines.push({p1:index+i,p2:(index+1)%length+i});
  33508. index ++;
  33509. }
  33510. i+=length;
  33511. });
  33512. points.forEach((p,j)=>{p.id = j;});
  33513. let rings = searchRings({
  33514. points,
  33515. lines,
  33516. onlyGetOutRing
  33517. });
  33518. //console.log(rings)
  33519. rings = rings.filter(e=>e.closetParent == void 0);// 子环不加,被外环包含了
  33520. return rings
  33521. },
  33522. getQuaFromPosAim( position, target ){
  33523. /* let matrix = (new THREE.Matrix4).lookAt(position, target, new THREE.Vector3(0,0,1)) //这里垂直的话会默认给一个右向所以不这么写
  33524. return (new THREE.Quaternion).setFromRotationMatrix(matrix) */
  33525. let view = new ExtendView();
  33526. view.direction = new Vector3().subVectors(target,position);
  33527. return view.quaternion
  33528. },
  33529. getBoundByPoints(points, minSize){
  33530. var bound = new Box3;
  33531. points.forEach(point=>{
  33532. bound.expandByPoint(point);
  33533. });
  33534. let center = bound.getCenter(new Vector3);
  33535. if(minSize){
  33536. let minBound = (new Box3()).setFromCenterAndSize(center, minSize);
  33537. bound.union(minBound);
  33538. }
  33539. return {
  33540. bounding:bound,
  33541. size: bound.getSize(new Vector3),
  33542. center,
  33543. }
  33544. },
  33545. linearClamp(value, x1,x2, y1, y2){//x为bound.min, bound.max
  33546. value = MathUtils.clamp(value, x1,x2);
  33547. return y1 + ( y2 - y1) * (value - x1) / (x2 - x1)
  33548. }
  33549. };
  33550. Potree.math = math;
  33551. function mobileVersion(e, t) {
  33552. //ios的版本
  33553. var i = window.navigator.userAgent,
  33554. n = i.match(e);
  33555. return (
  33556. (n = n ? n[1].split(t) : []),
  33557. {
  33558. major: parseInt(n[0]) || 0,
  33559. minor: parseInt(n[1]) || 0,
  33560. patch: parseInt(n[2]) || 0,
  33561. }
  33562. )
  33563. }
  33564. var browser = {
  33565. isFullscreen: function() {
  33566. return (
  33567. document.fullscreenElement ||
  33568. document.mozFullscreenElement ||
  33569. document.mozFullScreenElement ||
  33570. document.webkitFullscreenElement ||
  33571. document.msFullscreenElement
  33572. )
  33573. },
  33574. supportsFullscreen: function() {
  33575. return (
  33576. document.fullscreenEnabled ||
  33577. document.mozFullscreenEnabled ||
  33578. document.mozFullScreenEnabled ||
  33579. document.webkitFullscreenEnabled ||
  33580. document.msFullscreenEnabled
  33581. )
  33582. },
  33583. isPointerLocked: function() {
  33584. return (
  33585. document.pointerLockElement ||
  33586. document.mozPointerLockElement ||
  33587. document.webkitPointerLockElement
  33588. )
  33589. },
  33590. requestFullscreen: function(dom, t) {
  33591. dom.requestFullscreen ?
  33592. dom.requestFullscreen() :
  33593. dom.mozRequestFullScreen ?
  33594. dom.mozRequestFullScreen() :
  33595. dom.webkitRequestFullscreen ?
  33596. dom.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT) :
  33597. dom.msRequestFullscreen && dom.msRequestFullscreen(),
  33598. t &&
  33599. $(document).on(
  33600. "fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange",
  33601. browser.requestPointerLock
  33602. );
  33603. },
  33604. requestPointerLock: function() {
  33605. var e;
  33606. if (document.fullscreenElement) e = document.fullscreenElement();
  33607. else if (document.mozFullscreenElement) e = document.mozFullscreenElement();
  33608. else if (document.mozFullScreenElement) e = document.mozFullScreenElement();
  33609. else {
  33610. if (!document.webkitFullscreenElement) return
  33611. e = document.webkitFullscreenElement();
  33612. };
  33613. (e.requestPointerLock =
  33614. e.requestPointerLock || e.mozRequestPointerLock || e.webkitRequestPointerLock),
  33615. e.requestPointerLock(),
  33616. $(document).off(
  33617. "fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange",
  33618. this
  33619. );
  33620. },
  33621. exitPointerLock: function() {
  33622. ;
  33623. (document.exitPointerLock =
  33624. document.exitPointerLock ||
  33625. document.mozExitPointerLock ||
  33626. document.webkitExitPointerLock),
  33627. document.exitPointerLock();
  33628. },
  33629. exitFullscreen: function() {
  33630. document.exitFullscreen ?
  33631. document.exitFullscreen() :
  33632. document.msExitFullscreen ?
  33633. document.msExitFullscreen() :
  33634. document.mozCancelFullScreen ?
  33635. document.mozCancelFullScreen() :
  33636. document.webkitExitFullscreen && document.webkitExitFullscreen();
  33637. },
  33638. details: function() {
  33639. var e = navigator.userAgent.match("(Firefox|Chrome|Safari)/([\\d]+)");
  33640. return e ?
  33641. {
  33642. name: e[1],
  33643. version: parseInt(e[2]),
  33644. platform: navigator.platform,
  33645. } : {}
  33646. },
  33647. is: function(e) {
  33648. return this.details() && this.details().name === e
  33649. },
  33650. inIframe: function() {
  33651. return window.parent !== window
  33652. },
  33653. aspectRatio: function($elem) {
  33654. $elem = $elem || $("#player");
  33655. var e = $elem.width() / $elem.height();
  33656. return isFinite(e) ? e : 0
  33657. },
  33658. userAgent: function() {
  33659. return window.navigator.userAgent
  33660. },
  33661. isMobile: function() {
  33662. var e = navigator.userAgent || navigator.vendor || window.opera;
  33663. return (
  33664. /(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(
  33665. e
  33666. ) ||
  33667. /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(
  33668. e.substr(0, 4)
  33669. )
  33670. )
  33671. },
  33672. isLandscape: function() {
  33673. return this.isMobile && this.aspectRatio() > 1
  33674. },
  33675. isSmallScreen: function() {
  33676. var e = screen.width / window.devicePixelRatio;
  33677. return e < 240
  33678. },
  33679. detectIE: function() {
  33680. var e = window.navigator.userAgent,
  33681. t = e.indexOf("MSIE ");
  33682. return t !== -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./)
  33683. },
  33684. detectSafari: function() {
  33685. var e = window.navigator.userAgent,
  33686. t = e.indexOf("Safari");
  33687. return t !== -1 && !this.detectOpera() && !this.detectChrome() //xzw add detectOpera
  33688. },
  33689. detectFirefox: function() {
  33690. var e = window.navigator.userAgent;
  33691. return e.indexOf("Firefox") !== -1
  33692. },
  33693. detectChrome: function() {
  33694. var e = window.navigator.userAgent;
  33695. return e.indexOf("Chrome") !== -1 && !this.detectOpera()
  33696. },
  33697. detectOpera: function() {
  33698. var e = window.navigator.userAgent;
  33699. return e.indexOf("OPR") !== -1
  33700. },
  33701. detectIOS: function() {
  33702. return this.detectIPhone() || this.detectIPad() || this.detectIPod()
  33703. },
  33704. detectIPad: function() {
  33705. var e = window.navigator.userAgent,
  33706. t = /iPad/;
  33707. return t.test(e)
  33708. },
  33709. detectIPod: function() {
  33710. var e = window.navigator.userAgent,
  33711. t = /iPod/;
  33712. return t.test(e)
  33713. },
  33714. detectIPhone: function() {
  33715. var e = window.navigator.userAgent,
  33716. t = /iPhone/;
  33717. return t.test(e)
  33718. },
  33719. detectAndroid: function() {
  33720. var e = window.navigator.userAgent;
  33721. return e.indexOf("Android") !== -1
  33722. },
  33723. detectAndroidMobile: function() {
  33724. var e = window.navigator.userAgent;
  33725. return this.detectAndroid() && e.indexOf("Mobile") !== -1
  33726. },
  33727. detectSamsungNative: function() {
  33728. var e = window.navigator.userAgent;
  33729. return (
  33730. e.indexOf("SM-G900H") !== -1 ||
  33731. e.indexOf("GT-I9500") !== -1 ||
  33732. e.indexOf("SM-N900") !== -1
  33733. )
  33734. },
  33735. detectSamsungS6: function() {
  33736. var e = window.navigator.userAgent;
  33737. return e.indexOf("SM-G92") !== -1
  33738. },
  33739. /************************************************************徐世廷*************************************************************/
  33740. detectHUAWEI5X: function() {
  33741. return -1 !== window.navigator.userAgent.indexOf("KIW-TL00H")
  33742. },
  33743. /*******************************************************************************************************************************/
  33744. detectWebVR: function() {
  33745. return !(!window.navigator.getVRDisplays || !window.VRDisplay)
  33746. },
  33747. getVRDisplay: function() {
  33748. var e = $.Deferred();
  33749. return this.detectWebVR() ?
  33750. (navigator.getVRDisplays().then(function(t) {
  33751. t.length >= 1 && e.resolve(t[0]), e.reject(null);
  33752. }),
  33753. e) :
  33754. e.reject(null)
  33755. },
  33756. iosVersion: function() {
  33757. if (!this.detectIOS()) throw new DeviceMismatchException("Did not detect an iDevice")
  33758. var e = /((?:\d+\_?){1,3}) like Mac OS/,
  33759. t = "_";
  33760. return mobileVersion(e, t)
  33761. },
  33762. androidVersion: function() {
  33763. if (!this.detectAndroid())
  33764. throw new DeviceMismatchException("Did not detect an Android based device")
  33765. var e = /Android ((?:\d+\.?){1,3})/,
  33766. t = ".";
  33767. return mobileVersion(e, t)
  33768. },
  33769. valueFromCookie: function(e, t) {
  33770. var i = new RegExp(e + "=([0-9a-f]+)(; ?|$)").exec(document.cookie);
  33771. if (!i) return t
  33772. var n = i[1];
  33773. return "boolean" == typeof t ?
  33774. "true" === n || "1" === n :
  33775. "number" == typeof t ?
  33776. parseFloat(n) :
  33777. n
  33778. },
  33779. valueFromHash: function(e, t) {
  33780. var i = new RegExp("[#&?]" + e + "=([^#&?]*)"),
  33781. n = i.exec(window.location.href);
  33782. if (!n) return t
  33783. var r = n[1];
  33784. return "boolean" == typeof t ?
  33785. "true" === r || "1" === r :
  33786. "number" == typeof t ?
  33787. parseFloat(r) :
  33788. window.decodeURIComponent(r)
  33789. },
  33790. //-------许钟文:-------------------------------------------------
  33791. getProjectNum: function() {
  33792. //获取场景projectNum
  33793. if (window.__ProjectNum && window.__ProjectNum != "__ProjectNum__") {
  33794. return window.__ProjectNum
  33795. }
  33796. var number = window.location.href.substring(window.location.href.indexOf("=") + 1);
  33797. if (number.indexOf("&") != -1) {
  33798. number = number.substring(0, number.indexOf("&"));
  33799. }
  33800. if (number.indexOf("#") != -1) {
  33801. number = number.substring(0, number.indexOf("#"));
  33802. }
  33803. return number
  33804. },
  33805. urlHasValue: function(key, isGetValue) {
  33806. let querys = window.location.search.substr(1).split("&");
  33807. if (isGetValue) {
  33808. for (let i = 0; i < querys.length; i++) {
  33809. let keypair = querys[i].split("=");
  33810. if (keypair.length === 2 && keypair[0] === key) {
  33811. return keypair[1]
  33812. }
  33813. }
  33814. return ""
  33815. } else {
  33816. for (let i = 0; i < querys.length; i++) {
  33817. let keypair = querys[i].split("=");
  33818. if (keypair[0] == key) {
  33819. return true
  33820. }
  33821. }
  33822. return false
  33823. }
  33824. },
  33825. /**
  33826. * 获取查询参数的值
  33827. * @param {String} key
  33828. * @returns String
  33829. */
  33830. urlQueryValue(key) {
  33831. return this.urlHasValue(key, true) || ""
  33832. },
  33833. /**
  33834. * 获取hash参数的值
  33835. * @param {String} key
  33836. * @returns String
  33837. */
  33838. urlHashValue(key) {
  33839. let querys = window.location.hash.substr(1).replace('/?', '').split("&");
  33840. for (let i = 0; i < querys.length; i++) {
  33841. let keypair = querys[i].split("=");
  33842. if (keypair.length === 2 && keypair[0] === key) {
  33843. return keypair[1]
  33844. }
  33845. }
  33846. return ""
  33847. },
  33848. /**
  33849. * 判断是否存在hash
  33850. * @param {String} key
  33851. * @returns Boolean
  33852. */
  33853. urlIsHasHash(key) {
  33854. let querys = window.location.hash.substr(1).replace('/?', '').split("&");
  33855. return querys.includes(key)
  33856. },
  33857. islongPhone: function() {
  33858. //是否是刘海全面屏幕 仅仅根据比例判断 - -
  33859. //screen.height == 812 && screen.width == 375)
  33860. var r = screen.height / screen.width; //可能横屏
  33861. return this.isMobile() && (r > 1.99 || r < 0.502512) //18/9=2.165 //???
  33862. },
  33863. detectWeixin: function() {
  33864. //微信 包括PC的微信
  33865. return window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
  33866. },
  33867. detectWeixinMiniProgram: function() {
  33868. return window.navigator.userAgent.match("miniProgram")
  33869. },
  33870. detectEdge: function() {
  33871. return window.navigator.userAgent.indexOf("Edge") > -1
  33872. },
  33873. detectApp: function() {
  33874. return this.urlHasValue("app")
  33875. },
  33876. /**
  33877. * 判断标签页是否切换状态
  33878. */
  33879. isTabHidden: function() {
  33880. var prefixes = ["webkit", "moz", "ms", "o"];
  33881. if ("hidden" in document) return document.hidden
  33882. for (var i = 0; i < prefixes.length; i++) {
  33883. if (prefixes[i] + "Hidden" in document) return document[prefixes[i] + "Hidden"]
  33884. }
  33885. return false
  33886. },
  33887. };
  33888. WebGLRenderer.prototype.paramThreeToGL = function(e) {
  33889. var t, i = this.extensions, r = this.getContext();//context;
  33890. if (e === RepeatWrapping)
  33891. return r.REPEAT;
  33892. if (e === ClampToEdgeWrapping)
  33893. return r.CLAMP_TO_EDGE;
  33894. if (e === MirroredRepeatWrapping)
  33895. return r.MIRRORED_REPEAT;
  33896. if (e === NearestFilter)
  33897. return r.NEAREST;
  33898. if (e === NearestMipMapNearestFilter)
  33899. return r.NEAREST_MIPMAP_NEAREST;
  33900. if (e === NearestMipMapLinearFilter)
  33901. return r.NEAREST_MIPMAP_LINEAR;
  33902. if (e === LinearFilter)
  33903. return r.LINEAR;
  33904. if (e === LinearMipMapNearestFilter)
  33905. return r.LINEAR_MIPMAP_NEAREST;
  33906. if (e === LinearMipMapLinearFilter)
  33907. return r.LINEAR_MIPMAP_LINEAR;
  33908. if (e === UnsignedByteType)
  33909. return r.UNSIGNED_BYTE;
  33910. if (e === UnsignedShort4444Type)
  33911. return r.UNSIGNED_SHORT_4_4_4_4;
  33912. if (e === UnsignedShort5551Type)
  33913. return r.UNSIGNED_SHORT_5_5_5_1;
  33914. if (e === UnsignedShort565Type)
  33915. return r.UNSIGNED_SHORT_5_6_5;
  33916. if (e === ByteType)
  33917. return r.BYTE;
  33918. if (e === ShortType)
  33919. return r.SHORT;
  33920. if (e === UnsignedShortType)
  33921. return r.UNSIGNED_SHORT;
  33922. if (e === IntType)
  33923. return r.INT;
  33924. if (e === UnsignedIntType)
  33925. return r.UNSIGNED_INT;
  33926. if (e === FloatType)
  33927. return r.FLOAT;
  33928. if (t = i.get("OES_texture_half_float"),
  33929. null !== t && e === HalfFloatType)
  33930. return t.HALF_FLOAT_OES;
  33931. if (e === AlphaFormat)
  33932. return r.ALPHA;
  33933. if (e === RGBFormat)
  33934. return r.RGB;
  33935. if (e === RGBAFormat)
  33936. return r.RGBA;
  33937. if (e === LuminanceFormat)
  33938. return r.LUMINANCE;
  33939. if (e === LuminanceAlphaFormat)
  33940. return r.LUMINANCE_ALPHA;
  33941. if (e === AddEquation)
  33942. return r.FUNC_ADD;
  33943. if (e === SubtractEquation)
  33944. return r.FUNC_SUBTRACT;
  33945. if (e === ReverseSubtractEquation)
  33946. return r.FUNC_REVERSE_SUBTRACT;
  33947. if (e === ZeroFactor)
  33948. return r.ZERO;
  33949. if (e === OneFactor)
  33950. return r.ONE;
  33951. if (e === SrcColorFactor)
  33952. return r.SRC_COLOR;
  33953. if (e === OneMinusSrcColorFactor)
  33954. return r.ONE_MINUS_SRC_COLOR;
  33955. if (e === SrcAlphaFactor)
  33956. return r.SRC_ALPHA;
  33957. if (e === OneMinusSrcAlphaFactor)
  33958. return r.ONE_MINUS_SRC_ALPHA;
  33959. if (e === DstAlphaFactor)
  33960. return r.DST_ALPHA;
  33961. if (e === OneMinusDstAlphaFactor)
  33962. return r.ONE_MINUS_DST_ALPHA;
  33963. if (e === DstColorFactor)
  33964. return r.DST_COLOR;
  33965. if (e === OneMinusDstColorFactor)
  33966. return r.ONE_MINUS_DST_COLOR;
  33967. if (e === SrcAlphaSaturateFactor)
  33968. return r.SRC_ALPHA_SATURATE;
  33969. if (t = i.get("WEBGL_compressed_texture_s3tc"),
  33970. null !== t) {
  33971. if (e === RGB_S3TC_DXT1_Format)
  33972. return t.COMPRESSED_RGB_S3TC_DXT1_EXT;
  33973. if (e === RGBA_S3TC_DXT1_Format$1)
  33974. return t.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33975. if (e === RGBA_S3TC_DXT3_Format)
  33976. return t.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33977. if (e === RGBA_S3TC_DXT5_Format$1)
  33978. return t.COMPRESSED_RGBA_S3TC_DXT5_EXT
  33979. }
  33980. if (t = i.get("WEBGL_compressed_texture_pvrtc"),
  33981. null !== t) {
  33982. if (e === RGB_PVRTC_4BPPV1_Format)
  33983. return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  33984. if (e === RGB_PVRTC_2BPPV1_Format)
  33985. return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  33986. if (e === RGBA_PVRTC_4BPPV1_Format)
  33987. return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  33988. if (e === RGBA_PVRTC_2BPPV1_Format)
  33989. return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
  33990. }
  33991. if (t = i.get("WEBGL_compressed_texture_etc1"),
  33992. null !== t && e === RGB_ETC1_Format)
  33993. return t.COMPRESSED_RGB_ETC1_WEBGL;
  33994. if (t = i.get("EXT_blend_minmax"),
  33995. null !== t) {
  33996. if (e === MinEquation)
  33997. return t.MIN_EXT;
  33998. if (e === MaxEquation)
  33999. return t.MAX_EXT
  34000. }
  34001. return 0
  34002. };
  34003. EventDispatcher.prototype.addEventListener = function(type, listener, {importance=0, once}={}){ //add importance
  34004. if ( this._listeners === undefined ) this._listeners = {};
  34005. const listeners = this._listeners;
  34006. if ( listeners[ type ] === undefined ) {
  34007. listeners[ type ] = [];
  34008. }
  34009. /* if(type == 'flyingDone'){
  34010. console.log('addEventListener flyingDone')
  34011. } */
  34012. if ( !listeners[ type ].some(e=>e.listener == listener ) ) {
  34013. listeners[type].push({ listener, importance, once});
  34014. listeners[type] = listeners[type].sort((e,a)=> a.importance - e.importance);//add
  34015. }
  34016. };
  34017. EventDispatcher.prototype.hasEventListener = function(type, listener){
  34018. if ( this._listeners === undefined ) return false;
  34019. const listeners = this._listeners;
  34020. return listeners[ type ] !== undefined && listeners[ type ].some(e=>e.listener == listener )
  34021. };
  34022. EventDispatcher.prototype.removeEventListener = function(type, listener){
  34023. if ( this._listeners === undefined ) return;
  34024. const listeners = this._listeners;
  34025. const listenerArray = listeners[ type ];
  34026. if ( listenerArray !== undefined ) {
  34027. /* const index = listenerArray.indexOf( listener );
  34028. if ( index !== - 1 ) {
  34029. listenerArray.splice( index, 1 );
  34030. } */
  34031. let item = listenerArray.find(e=>e.listener == listener);
  34032. item && listenerArray.splice(listenerArray.indexOf(item), 1);
  34033. }
  34034. };
  34035. EventDispatcher.prototype.removeEventListeners = function(type){ //add
  34036. if(this._listeners && this._listeners[type] !== undefined){
  34037. delete this._listeners[type];
  34038. }
  34039. };
  34040. EventDispatcher.prototype.removeAllListeners = function(){ //add
  34041. this._listeners = {};
  34042. };
  34043. EventDispatcher.prototype.dispatchEvent = function(event){
  34044. if(typeof event == 'string'){//add
  34045. event = {type:event};
  34046. }
  34047. if ( this._listeners === undefined ) return;
  34048. const listeners = this._listeners;
  34049. const listenerArray = listeners[ event.type ];
  34050. if ( listenerArray !== undefined ) {
  34051. event.target = this;
  34052. // Make a copy, in case listeners are removed while iterating.
  34053. for(let {listener, once} of listenerArray.slice(0)){
  34054. if(once){
  34055. this.removeEventListener(event.type,listener);
  34056. }
  34057. let result = listener.call(this, event); //add stopContinue
  34058. if(result && result.stopContinue){
  34059. break
  34060. }
  34061. }
  34062. }
  34063. };
  34064. EventDispatcher.prototype.traverse = function(callback){
  34065. let result = callback( this );
  34066. if(result && result.stopContinue){//xzw add
  34067. return
  34068. }
  34069. const children = this.children;
  34070. if(children){
  34071. for ( let i = 0, l = children.length; i < l; i ++ ) {
  34072. children[ i ].traverse( callback );
  34073. }
  34074. }
  34075. };
  34076. Object3D.prototype.traverse = function ( callback ) {
  34077. let result = callback( this );
  34078. if(result && result.stopContinue){//xzw add
  34079. return
  34080. }
  34081. const children = this.children;
  34082. for ( let i = 0, l = children.length; i < l; i ++ ) {
  34083. children[ i ] && children[ i ].traverse( callback );
  34084. }
  34085. };
  34086. Material.prototype.setValues = function ( values ) {
  34087. if ( values === undefined ) return;
  34088. for ( const key in values ) {
  34089. const newValue = values[ key ];
  34090. if ( newValue === undefined ) {
  34091. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  34092. continue;
  34093. }
  34094. // for backward compatability if shading is set in the constructor
  34095. if ( key === 'shading' ) {
  34096. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  34097. this.flatShading = ( newValue === FlatShading ) ? true : false;
  34098. continue;
  34099. }
  34100. const currentValue = this[ key ];
  34101. /* if ( currentValue === undefined ) { //-----主要删了这段,否则很难和 set 一起使用
  34102. //console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  34103. continue;
  34104. } */
  34105. if ( currentValue && currentValue.isColor ) {
  34106. currentValue.set( newValue );
  34107. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  34108. currentValue.copy( newValue );
  34109. } else {
  34110. this[ key ] = newValue;
  34111. }
  34112. }
  34113. };
  34114. function ascSort$1( a, b ) {
  34115. return a.distance - b.distance;
  34116. }
  34117. function intersectObject$1( object, raycaster, intersects, recursive, ignoreUnvisible ) {
  34118. if(ignoreUnvisible && !object.visible)return //add
  34119. if ( object.layers.test( raycaster.layers ) ) {
  34120. object.raycast( raycaster, intersects );
  34121. }
  34122. if ( recursive === true ) {
  34123. const children = object.children;
  34124. for ( let i = 0, l = children.length; i < l; i ++ ) {
  34125. intersectObject$1( children[ i ], raycaster, intersects, true, ignoreUnvisible);
  34126. }
  34127. }
  34128. }
  34129. Raycaster.prototype.intersectObject = function ( object, recursive, optionalTarget, ignoreUnvisible ) {
  34130. const intersects = optionalTarget || [];
  34131. intersectObject$1( object, this, intersects, recursive, ignoreUnvisible );
  34132. intersects.sort( ascSort$1 );
  34133. return intersects;
  34134. };
  34135. Raycaster.prototype.intersectObjects = function ( objects, recursive, optionalTarget, ignoreUnvisible ) {//add ignoreUnvisible 跳过不可见
  34136. const intersects = optionalTarget || [];
  34137. if ( Array.isArray( objects ) === false ) {
  34138. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  34139. return intersects;
  34140. }
  34141. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  34142. intersectObject$1( objects[ i ], this, intersects, recursive, ignoreUnvisible );
  34143. }
  34144. intersects.sort( ascSort$1 );
  34145. return intersects;
  34146. };
  34147. Object3D.prototype.realVisible = function(){
  34148. let v = true;
  34149. let parent = this;
  34150. let lastParent;
  34151. while(parent){
  34152. if(parent.visible === false){
  34153. v = false;
  34154. break;
  34155. }
  34156. lastParent = parent;
  34157. parent = parent.parent;
  34158. }
  34159. if(v && !(lastParent instanceof Scene)){//已被删除
  34160. v = false;
  34161. }
  34162. return v
  34163. };
  34164. var MathLight = {};
  34165. MathLight.RADIANS_PER_DEGREE = Math.PI / 180;
  34166. MathLight.DEGREES_PER_RADIAN = 180 / Math.PI;
  34167. MathLight.Vector3 = function(e, t, i) {
  34168. this.x = e || 0,
  34169. this.y = t || 0,
  34170. this.z = i || 0;
  34171. };
  34172. MathLight.Matrix4 = function() {
  34173. this.elements = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
  34174. arguments.length > 0 && console.error("MathLight.Matrix4: the constructor no longer reads arguments. use .set() instead.");
  34175. };
  34176. MathLight.Matrix4.prototype = {
  34177. identity: function() {
  34178. return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1),
  34179. this
  34180. },
  34181. copy: function(e) {
  34182. return this.elements.set(e.elements),
  34183. this
  34184. },
  34185. applyToVector3: function(e) {
  34186. var t = e.x
  34187. , i = e.y
  34188. , n = e.z
  34189. , r = this.elements;
  34190. return e.x = r[0] * t + r[4] * i + r[8] * n + r[12],
  34191. e.y = r[1] * t + r[5] * i + r[9] * n + r[13],
  34192. e.z = r[2] * t + r[6] * i + r[10] * n + r[14],
  34193. this
  34194. },
  34195. getInverse: function(e, t) {
  34196. var i = this.elements
  34197. , n = e.elements
  34198. , r = n[0]
  34199. , o = n[1]
  34200. , a = n[2]
  34201. , s = n[3]
  34202. , l = n[4]
  34203. , c = n[5]
  34204. , h = n[6]
  34205. , u = n[7]
  34206. , d = n[8]
  34207. , p = n[9]
  34208. , f = n[10]
  34209. , g = n[11]
  34210. , m = n[12]
  34211. , v = n[13]
  34212. , A = n[14]
  34213. , y = n[15]
  34214. , C = p * A * u - v * f * u + v * h * g - c * A * g - p * h * y + c * f * y
  34215. , I = m * f * u - d * A * u - m * h * g + l * A * g + d * h * y - l * f * y
  34216. , E = d * v * u - m * p * u + m * c * g - l * v * g - d * c * y + l * p * y
  34217. , b = m * p * h - d * v * h - m * c * f + l * v * f + d * c * A - l * p * A
  34218. , w = r * C + o * I + a * E + s * b;
  34219. if (0 === w) {
  34220. var _ = "MathLight.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  34221. if (t)
  34222. throw new Error(_);
  34223. return console.warn(_),
  34224. this.identity()
  34225. }
  34226. var T = 1 / w;
  34227. return i[0] = C * T,
  34228. i[1] = (v * f * s - p * A * s - v * a * g + o * A * g + p * a * y - o * f * y) * T,
  34229. i[2] = (c * A * s - v * h * s + v * a * u - o * A * u - c * a * y + o * h * y) * T,
  34230. i[3] = (p * h * s - c * f * s - p * a * u + o * f * u + c * a * g - o * h * g) * T,
  34231. i[4] = I * T,
  34232. i[5] = (d * A * s - m * f * s + m * a * g - r * A * g - d * a * y + r * f * y) * T,
  34233. i[6] = (m * h * s - l * A * s - m * a * u + r * A * u + l * a * y - r * h * y) * T,
  34234. i[7] = (l * f * s - d * h * s + d * a * u - r * f * u - l * a * g + r * h * g) * T,
  34235. i[8] = E * T,
  34236. i[9] = (m * p * s - d * v * s - m * o * g + r * v * g + d * o * y - r * p * y) * T,
  34237. i[10] = (l * v * s - m * c * s + m * o * u - r * v * u - l * o * y + r * c * y) * T,
  34238. i[11] = (d * c * s - l * p * s - d * o * u + r * p * u + l * o * g - r * c * g) * T,
  34239. i[12] = b * T,
  34240. i[13] = (d * v * a - m * p * a + m * o * f - r * v * f - d * o * A + r * p * A) * T,
  34241. i[14] = (m * c * a - l * v * a - m * o * h + r * v * h + l * o * A - r * c * A) * T,
  34242. i[15] = (l * p * a - d * c * a + d * o * h - r * p * h - l * o * f + r * c * f) * T,
  34243. this
  34244. },
  34245. makeRotationFromQuaternion: function(e) {
  34246. var t = this.elements
  34247. , i = e.x
  34248. , n = e.y
  34249. , r = e.z
  34250. , o = e.w
  34251. , a = i + i
  34252. , s = n + n
  34253. , l = r + r
  34254. , c = i * a
  34255. , h = i * s
  34256. , u = i * l
  34257. , d = n * s
  34258. , p = n * l
  34259. , f = r * l
  34260. , g = o * a
  34261. , m = o * s
  34262. , v = o * l;
  34263. return t[0] = 1 - (d + f),
  34264. t[4] = h - v,
  34265. t[8] = u + m,
  34266. t[1] = h + v,
  34267. t[5] = 1 - (c + f),
  34268. t[9] = p - g,
  34269. t[2] = u - m,
  34270. t[6] = p + g,
  34271. t[10] = 1 - (c + d),
  34272. t[3] = 0,
  34273. t[7] = 0,
  34274. t[11] = 0,
  34275. t[12] = 0,
  34276. t[13] = 0,
  34277. t[14] = 0,
  34278. t[15] = 1,
  34279. this
  34280. }
  34281. };
  34282. MathLight.Quaternion = function(e, t, i, n) {
  34283. this._x = e || 0,
  34284. this._y = t || 0,
  34285. this._z = i || 0,
  34286. this._w = void 0 !== n ? n : 1;
  34287. };
  34288. MathLight.Quaternion.prototype = {
  34289. get x() {
  34290. return this._x
  34291. },
  34292. set x(e) {
  34293. this._x = e;
  34294. },
  34295. get y() {
  34296. return this._y
  34297. },
  34298. set y(e) {
  34299. this._y = e;
  34300. },
  34301. get z() {
  34302. return this._z
  34303. },
  34304. set z(e) {
  34305. this._z = e;
  34306. },
  34307. get w() {
  34308. return this._w
  34309. },
  34310. set w(e) {
  34311. this._w = e;
  34312. },
  34313. copy: function(e) {
  34314. this._x = e.x,
  34315. this._y = e.y,
  34316. this._z = e.z,
  34317. this._w = e.w;
  34318. },
  34319. inverse: function() {
  34320. return this.conjugate().normalize()
  34321. },
  34322. conjugate: function() {
  34323. return this._x *= -1,
  34324. this._y *= -1,
  34325. this._z *= -1,
  34326. this
  34327. },
  34328. length: function() {
  34329. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w)
  34330. },
  34331. normalize: function() {
  34332. var e = this.length();
  34333. return 0 === e ? (this._x = 0,
  34334. this._y = 0,
  34335. this._z = 0,
  34336. this._w = 1) : (e = 1 / e,
  34337. this._x = this._x * e,
  34338. this._y = this._y * e,
  34339. this._z = this._z * e,
  34340. this._w = this._w * e),
  34341. this
  34342. },
  34343. setFromAxisAngle: function(e, t) {
  34344. var i = t / 2
  34345. , n = Math.sin(i);
  34346. return this._x = e.x * n,
  34347. this._y = e.y * n,
  34348. this._z = e.z * n,
  34349. this._w = Math.cos(i),
  34350. this
  34351. },
  34352. setFromUnitVectors: function() {
  34353. var e, t, i = 1e-6;
  34354. return function(n, o) {
  34355. return void 0 === e && (e = new MathLight.Vector3),
  34356. t = MathLight.dot(n, o) + 1,
  34357. t < i ? (t = 0,
  34358. 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),
  34359. this._x = e.x,
  34360. this._y = e.y,
  34361. this._z = e.z,
  34362. this._w = t,
  34363. this.normalize()
  34364. }
  34365. }(),
  34366. multiply: function(e) {
  34367. return this.multiplyQuaternions(this, e)
  34368. },
  34369. premultiply: function(e) {
  34370. return this.multiplyQuaternions(e, this)
  34371. },
  34372. multiplyQuaternions: function(e, t) {
  34373. var i = e._x
  34374. , n = e._y
  34375. , r = e._z
  34376. , o = e._w
  34377. , a = t._x
  34378. , s = t._y
  34379. , l = t._z
  34380. , c = t._w;
  34381. return this._x = i * c + o * a + n * l - r * s,
  34382. this._y = n * c + o * s + r * a - i * l,
  34383. this._z = r * c + o * l + i * s - n * a,
  34384. this._w = o * c - i * a - n * s - r * l,
  34385. this
  34386. }
  34387. };
  34388. MathLight.convertWorkshopVector = function(e) {
  34389. return new MathLight.Vector3(-e.x,e.y,e.z)
  34390. };
  34391. MathLight.convertWorkshopQuaternion = function(e) {
  34392. 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))
  34393. };
  34394. MathLight.convertWorkshopOrthoZoom = function(e) {
  34395. //return e === -1 ? -1 : e / 16 * ($('#player').width() / $('#player').height()) / n.workshopApsect
  34396. return e === -1 ? -1 : e * ($("#player").width() / $("#player").height()) ;
  34397. };
  34398. MathLight.convertWorkshopPanoramaQuaternion = function(e) {
  34399. 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))
  34400. };
  34401. MathLight.normalize = function(e) {
  34402. var t = e.x * e.x + e.y * e.y + e.z * e.z
  34403. , i = Math.sqrt(t);
  34404. e.x /= i,
  34405. e.y /= i,
  34406. e.z /= i;
  34407. };
  34408. MathLight.dot = function(e, t) {
  34409. return e.x * t.x + e.y * t.y + e.z * t.z
  34410. };
  34411. MathLight.cross = function(e, t, i) {
  34412. var n = e.x
  34413. , r = e.y
  34414. , o = e.z;
  34415. i.x = r * t.z - o * t.y,
  34416. i.y = o * t.x - n * t.z,
  34417. i.z = n * t.y - r * t.x;
  34418. };
  34419. MathLight.setVector = function(e, t, i, n) {
  34420. e.x = t,
  34421. e.y = i,
  34422. e.z = n;
  34423. };
  34424. MathLight.copyVector = function(e, t) {
  34425. t.x = e.x,
  34426. t.y = e.y,
  34427. t.z = e.z;
  34428. };
  34429. MathLight.addVector = function(e, t) {
  34430. e.x += t.x,
  34431. e.y += t.y,
  34432. e.z += t.z;
  34433. };
  34434. MathLight.subVector = function(e, t) {
  34435. e.x -= t.x,
  34436. e.y -= t.y,
  34437. e.z -= t.z;
  34438. };
  34439. MathLight.applyQuaternionToVector = function(e, t) {
  34440. var i = t.x
  34441. , n = t.y
  34442. , r = t.z
  34443. , o = e.x
  34444. , a = e.y
  34445. , s = e.z
  34446. , l = e.w
  34447. , c = l * i + a * r - s * n
  34448. , h = l * n + s * i - o * r
  34449. , u = l * r + o * n - a * i
  34450. , d = -o * i - a * n - s * r;
  34451. t.x = c * l + d * -o + h * -s - u * -a,
  34452. t.y = h * l + d * -a + u * -o - c * -s,
  34453. t.z = u * l + d * -s + c * -a - h * -o;
  34454. };
  34455. MathLight.angleBetweenVectors = function(e, t) {
  34456. return Math.acos(MathLight.dot(e, t))
  34457. };
  34458. var cameraLight = {
  34459. clampVFOV: function(currentFov, maxHFov, width, height) {//限制currentFov, 使之造成的横向fov不大于指定值maxHFov
  34460. var r = cameraLight.getHFOVFromVFOV(currentFov, width, height);
  34461. return r > maxHFov ? cameraLight.getVFOVFromHFOV(maxHFov, width, height) : currentFov
  34462. },
  34463. getHFOVForCamera: function(camera, getRad) {
  34464. return cameraLight.getHFOVByScreenPrecent(camera.fov, camera.aspect, getRad)
  34465. },
  34466. //add
  34467. getHFOVByScreenPrecent: function(fov, percent, getRad) { //当fov为占比百分百时,percent代表在屏幕上从中心到边缘的占比
  34468. let rad = 2 * Math.atan(percent * Math.tan(fov * MathLight.RADIANS_PER_DEGREE / 2));
  34469. if(getRad)return rad
  34470. else return rad * MathLight.DEGREES_PER_RADIAN;
  34471. }
  34472. };
  34473. const XHRFactory = {
  34474. config: {
  34475. withCredentials: false,
  34476. customHeaders: [
  34477. { header: null, value: null }
  34478. ]
  34479. },
  34480. createXMLHttpRequest: function () {
  34481. let xhr = new XMLHttpRequest();
  34482. if (this.config.customHeaders &&
  34483. Array.isArray(this.config.customHeaders) &&
  34484. this.config.customHeaders.length > 0) {
  34485. let baseOpen = xhr.open;
  34486. let customHeaders = this.config.customHeaders;
  34487. xhr.open = function () {
  34488. baseOpen.apply(this, [].slice.call(arguments));
  34489. customHeaders.forEach(function (customHeader) {
  34490. if (!!customHeader.header && !!customHeader.value) {
  34491. xhr.setRequestHeader(customHeader.header, customHeader.value);
  34492. }
  34493. });
  34494. };
  34495. }
  34496. return xhr;
  34497. }
  34498. };
  34499. class TextSprite$1 extends Object3D{//old
  34500. constructor(text){
  34501. super();
  34502. let texture = new Texture();
  34503. texture.minFilter = LinearFilter;
  34504. texture.magFilter = LinearFilter;
  34505. let spriteMaterial = new SpriteMaterial({
  34506. map: texture,
  34507. depthTest: false,
  34508. depthWrite: false});
  34509. this.texture = texture;
  34510. this.material = spriteMaterial;
  34511. //this.material = getRawMaterial(texture);
  34512. this.sprite = new Sprite$1(this.material);
  34513. this.add(this.sprite);
  34514. this.borderThickness = 4;
  34515. this.fontface = 'Arial';
  34516. this.fontsize = 28;
  34517. this.borderColor = { r: 0, g: 0, b: 0, a: 1.0 };
  34518. this.backgroundColor = { r: 255, g: 255, b: 255, a: 1.0 };
  34519. this.textColor = {r: 255, g: 255, b: 255, a: 1.0};
  34520. this.text = '';
  34521. this.setText(text);
  34522. }
  34523. setText(text){
  34524. if (this.text !== text){
  34525. this.text = text;
  34526. this.update();
  34527. }
  34528. }
  34529. setTextColor(color){
  34530. this.textColor = color;
  34531. this.update();
  34532. }
  34533. setBorderColor(color){
  34534. this.borderColor = color;
  34535. this.update();
  34536. }
  34537. setBackgroundColor(color){
  34538. this.backgroundColor = color;
  34539. this.update();
  34540. }
  34541. update(){
  34542. let canvas = document.createElement('canvas');
  34543. let context = canvas.getContext('2d');
  34544. context.font = 'Bold ' + this.fontsize + 'px ' + this.fontface;
  34545. // get size data (height depends only on font size)
  34546. let metrics = context.measureText(this.text);
  34547. let textWidth = metrics.width;
  34548. let margin = 5;
  34549. let spriteWidth = 2 * margin + textWidth + 2 * this.borderThickness;
  34550. let spriteHeight = this.fontsize * 1.4 + 2 * this.borderThickness;
  34551. context.canvas.width = spriteWidth;
  34552. context.canvas.height = spriteHeight;
  34553. context.font = 'Bold ' + this.fontsize + 'px ' + this.fontface;
  34554. // background color
  34555. context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' +
  34556. this.backgroundColor.b + ',' + this.backgroundColor.a + ')';
  34557. // border color
  34558. context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' +
  34559. this.borderColor.b + ',' + this.borderColor.a + ')';
  34560. context.lineWidth = this.borderThickness;
  34561. this.roundRect(context, this.borderThickness / 2, this.borderThickness / 2,
  34562. textWidth + this.borderThickness + 2 * margin, this.fontsize * 1.4 + this.borderThickness, 6);
  34563. // text color
  34564. context.strokeStyle = 'rgba(0, 0, 0, 1.0)';
  34565. context.strokeText(this.text, this.borderThickness + margin, this.fontsize + this.borderThickness);
  34566. context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' +
  34567. this.textColor.b + ',' + this.textColor.a + ')';
  34568. context.fillText(this.text, this.borderThickness + margin, this.fontsize + this.borderThickness);
  34569. let texture = new Texture(canvas);
  34570. texture.minFilter = LinearFilter;
  34571. texture.magFilter = LinearFilter;
  34572. texture.needsUpdate = true;
  34573. //this.material.needsUpdate = true;
  34574. // { // screen-space sprite
  34575. // let [screenWidth, screenHeight] = [1620, 937];
  34576. // let uniforms = this.sprite.material.uniforms;
  34577. // let aspect = spriteHeight / spriteWidth;
  34578. // let factor = 0.5;
  34579. // let w = spriteWidth / screenWidth;
  34580. // let h = spriteHeight / screenHeight;
  34581. // uniforms.uScale.value = [2 * w, 2 * h];
  34582. // //uniforms.uScale.value = [factor * 1, factor * aspect];
  34583. // this.sprite.material.uniforms.map.value = texture;
  34584. // }
  34585. this.sprite.material.map = texture;
  34586. this.texture = texture;
  34587. this.sprite.scale.set(spriteWidth * 0.01, spriteHeight * 0.01, 1.0);
  34588. }
  34589. roundRect(ctx, x, y, w, h, r){
  34590. ctx.beginPath();
  34591. ctx.moveTo(x + r, y);
  34592. ctx.lineTo(x + w - r, y);
  34593. ctx.quadraticCurveTo(x + w, y, x + w, y + r);
  34594. ctx.lineTo(x + w, y + h - r);
  34595. ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
  34596. ctx.lineTo(x + r, y + h);
  34597. ctx.quadraticCurveTo(x, y + h, x, y + h - r);
  34598. ctx.lineTo(x, y + r);
  34599. ctx.quadraticCurveTo(x, y, x + r, y);
  34600. ctx.closePath();
  34601. ctx.fill();
  34602. ctx.stroke();
  34603. }
  34604. }
  34605. class Volume extends Object3D {
  34606. constructor (args = {}) {
  34607. super();
  34608. if(this.constructor.name === "Volume"){
  34609. console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead.");
  34610. }
  34611. //console.log(this);
  34612. //console.log(this.constructor);
  34613. //console.log(this.constructor.name);
  34614. this._clip = args.clip || false;
  34615. this._visible = true;
  34616. this.showVolumeLabel = true;
  34617. this._modifiable = args.modifiable || true;
  34618. this.label = new TextSprite$1('0');
  34619. this.label.setBorderColor({r: 0, g: 255, b: 0, a: 0.0});
  34620. this.label.setBackgroundColor({r: 0, g: 255, b: 0, a: 0.0});
  34621. this.label.material.depthTest = false;
  34622. this.label.material.depthWrite = false;
  34623. this.label.material.transparent = true;
  34624. this.label.position.y -= 0.5;
  34625. this.add(this.label);
  34626. this.label.updateMatrixWorld = () => {
  34627. let volumeWorldPos = new Vector3();
  34628. volumeWorldPos.setFromMatrixPosition(this.matrixWorld);
  34629. this.label.position.copy(volumeWorldPos);
  34630. this.label.updateMatrix();
  34631. this.label.matrixWorld.copy(this.label.matrix);
  34632. this.label.matrixWorldNeedsUpdate = false;
  34633. for (let i = 0, l = this.label.children.length; i < l; i++) {
  34634. this.label.children[ i ].updateMatrixWorld(true);
  34635. }
  34636. };
  34637. { // event listeners
  34638. this.addEventListener('select', e => {});
  34639. this.addEventListener('deselect', e => {});
  34640. }
  34641. }
  34642. get visible(){
  34643. return this._visible;
  34644. }
  34645. set visible(value){
  34646. if(this._visible !== value){
  34647. this._visible = value;
  34648. this.dispatchEvent({type: "visibility_changed", object: this});
  34649. }
  34650. }
  34651. getVolume () {
  34652. console.warn("override this in subclass");
  34653. }
  34654. update () {
  34655. };
  34656. raycast (raycaster, intersects) {
  34657. }
  34658. get clip () {
  34659. return this._clip;
  34660. }
  34661. set clip (value) {
  34662. if(this._clip !== value){
  34663. this._clip = value;
  34664. this.update();
  34665. this.dispatchEvent({
  34666. type: "clip_changed",
  34667. object: this
  34668. });
  34669. }
  34670. }
  34671. get modifieable () {
  34672. return this._modifiable;
  34673. }
  34674. set modifieable (value) {
  34675. this._modifiable = value;
  34676. this.update();
  34677. }
  34678. };
  34679. class BoxVolume extends Volume{
  34680. constructor(args = {}){
  34681. super(args);
  34682. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  34683. this.name = 'box_' + this.constructor.counter;
  34684. let boxGeometry = new BoxGeometry(1, 1, 1);
  34685. boxGeometry.computeBoundingBox();
  34686. let boxFrameGeometry = new Geometry();
  34687. {
  34688. let Vector3$1 = Vector3;
  34689. boxFrameGeometry.vertices.push(
  34690. // bottom
  34691. new Vector3$1(-0.5, -0.5, 0.5),
  34692. new Vector3$1(0.5, -0.5, 0.5),
  34693. new Vector3$1(0.5, -0.5, 0.5),
  34694. new Vector3$1(0.5, -0.5, -0.5),
  34695. new Vector3$1(0.5, -0.5, -0.5),
  34696. new Vector3$1(-0.5, -0.5, -0.5),
  34697. new Vector3$1(-0.5, -0.5, -0.5),
  34698. new Vector3$1(-0.5, -0.5, 0.5),
  34699. // top
  34700. new Vector3$1(-0.5, 0.5, 0.5),
  34701. new Vector3$1(0.5, 0.5, 0.5),
  34702. new Vector3$1(0.5, 0.5, 0.5),
  34703. new Vector3$1(0.5, 0.5, -0.5),
  34704. new Vector3$1(0.5, 0.5, -0.5),
  34705. new Vector3$1(-0.5, 0.5, -0.5),
  34706. new Vector3$1(-0.5, 0.5, -0.5),
  34707. new Vector3$1(-0.5, 0.5, 0.5),
  34708. // sides
  34709. new Vector3$1(-0.5, -0.5, 0.5),
  34710. new Vector3$1(-0.5, 0.5, 0.5),
  34711. new Vector3$1(0.5, -0.5, 0.5),
  34712. new Vector3$1(0.5, 0.5, 0.5),
  34713. new Vector3$1(0.5, -0.5, -0.5),
  34714. new Vector3$1(0.5, 0.5, -0.5),
  34715. new Vector3$1(-0.5, -0.5, -0.5),
  34716. new Vector3$1(-0.5, 0.5, -0.5),
  34717. );
  34718. }
  34719. this.material = new MeshBasicMaterial({
  34720. color: 0x00ff00,
  34721. transparent: true,
  34722. opacity: 0.3,
  34723. depthTest: true,
  34724. depthWrite: false});
  34725. this.box = new Mesh(boxGeometry, this.material);
  34726. this.box.geometry.computeBoundingBox();
  34727. this.boundingBox = this.box.geometry.boundingBox;
  34728. this.add(this.box);
  34729. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({color: 0x000000}));
  34730. // this.frame.mode = THREE.Lines;
  34731. this.add(this.frame);
  34732. this.update();
  34733. }
  34734. update(){
  34735. this.boundingBox = this.box.geometry.boundingBox;
  34736. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  34737. if (this._clip) {
  34738. this.box.visible = false;
  34739. this.label.visible = false;
  34740. } else {
  34741. this.box.visible = true;
  34742. this.label.visible = this.showVolumeLabel;
  34743. }
  34744. }
  34745. raycast (raycaster, intersects) {
  34746. let is = [];
  34747. this.box.raycast(raycaster, is);
  34748. if (is.length > 0) {
  34749. let I = is[0];
  34750. intersects.push({
  34751. distance: I.distance,
  34752. object: this,
  34753. point: I.point.clone()
  34754. });
  34755. }
  34756. }
  34757. getVolume(){
  34758. return Math.abs(this.scale.x * this.scale.y * this.scale.z);
  34759. }
  34760. };
  34761. class SphereVolume$1 extends Volume{
  34762. constructor(args = {}){
  34763. super(args);
  34764. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  34765. this.name = 'sphere_' + this.constructor.counter;
  34766. let sphereGeometry = new SphereGeometry(1, 32, 32);
  34767. sphereGeometry.computeBoundingBox();
  34768. this.material = new MeshBasicMaterial({
  34769. color: 0x00ff00,
  34770. transparent: true,
  34771. opacity: 0.3,
  34772. depthTest: true,
  34773. depthWrite: false});
  34774. this.sphere = new Mesh(sphereGeometry, this.material);
  34775. this.sphere.visible = false;
  34776. this.sphere.geometry.computeBoundingBox();
  34777. this.boundingBox = this.sphere.geometry.boundingBox;
  34778. this.add(this.sphere);
  34779. this.label.visible = false;
  34780. let frameGeometry = new Geometry();
  34781. {
  34782. let steps = 64;
  34783. let uSegments = 8;
  34784. let vSegments = 5;
  34785. let r = 1;
  34786. for(let uSegment = 0; uSegment < uSegments; uSegment++){
  34787. let alpha = (uSegment / uSegments) * Math.PI * 2;
  34788. let dirx = Math.cos(alpha);
  34789. let diry = Math.sin(alpha);
  34790. for(let i = 0; i <= steps; i++){
  34791. let v = (i / steps) * Math.PI * 2;
  34792. let vNext = v + 2 * Math.PI / steps;
  34793. let height = Math.sin(v);
  34794. let xyAmount = Math.cos(v);
  34795. let heightNext = Math.sin(vNext);
  34796. let xyAmountNext = Math.cos(vNext);
  34797. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  34798. frameGeometry.vertices.push(vertex);
  34799. let vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext);
  34800. frameGeometry.vertices.push(vertexNext);
  34801. }
  34802. }
  34803. // creates rings at poles, just because it's easier to implement
  34804. for(let vSegment = 0; vSegment <= vSegments + 1; vSegment++){
  34805. //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1
  34806. let uh = (vSegment / (vSegments + 1)); // -1 to 1
  34807. uh = (1 - uh) * (-Math.PI / 2) + uh *(Math.PI / 2);
  34808. let height = Math.sin(uh);
  34809. console.log(uh, height);
  34810. for(let i = 0; i <= steps; i++){
  34811. let u = (i / steps) * Math.PI * 2;
  34812. let uNext = u + 2 * Math.PI / steps;
  34813. let dirx = Math.cos(u);
  34814. let diry = Math.sin(u);
  34815. let dirxNext = Math.cos(uNext);
  34816. let diryNext = Math.sin(uNext);
  34817. let xyAmount = Math.sqrt(1 - height * height);
  34818. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  34819. frameGeometry.vertices.push(vertex);
  34820. let vertexNext = new Vector3(dirxNext * xyAmount, diryNext * xyAmount, height);
  34821. frameGeometry.vertices.push(vertexNext);
  34822. }
  34823. }
  34824. }
  34825. this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({color: 0x000000}));
  34826. this.add(this.frame);
  34827. let frameMaterial = new MeshBasicMaterial({wireframe: true, color: 0x000000});
  34828. this.frame = new Mesh(sphereGeometry, frameMaterial);
  34829. //this.add(this.frame);
  34830. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000}));
  34831. // this.frame.mode = THREE.Lines;
  34832. //this.add(this.frame);
  34833. this.update();
  34834. }
  34835. update(){
  34836. this.boundingBox = this.sphere.geometry.boundingBox;
  34837. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  34838. //if (this._clip) {
  34839. // this.sphere.visible = false;
  34840. // this.label.visible = false;
  34841. //} else {
  34842. // this.sphere.visible = true;
  34843. // this.label.visible = this.showVolumeLabel;
  34844. //}
  34845. }
  34846. raycast (raycaster, intersects) {
  34847. let is = [];
  34848. this.sphere.raycast(raycaster, is);
  34849. if (is.length > 0) {
  34850. let I = is[0];
  34851. intersects.push({
  34852. distance: I.distance,
  34853. object: this,
  34854. point: I.point.clone()
  34855. });
  34856. }
  34857. }
  34858. // see https://en.wikipedia.org/wiki/Ellipsoid#Volume
  34859. getVolume(){
  34860. return (4 / 3) * Math.PI * this.scale.x * this.scale.y * this.scale.z;
  34861. }
  34862. };
  34863. class Profile extends Object3D{
  34864. constructor () {
  34865. super();
  34866. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  34867. this.name = 'Profile_' + this.constructor.counter;
  34868. this.points = [];
  34869. this.spheres = [];
  34870. this.edges = [];
  34871. this.boxes = [];
  34872. this.width = 1;
  34873. this.height = 20;
  34874. this._modifiable = true;
  34875. this.sphereGeometry = new SphereGeometry(0.4, 10, 10);
  34876. this.color = new Color(0xff0000);
  34877. this.lineColor = new Color(0xff0000);
  34878. }
  34879. createSphereMaterial () {
  34880. let sphereMaterial = new MeshLambertMaterial({
  34881. //shading: THREE.SmoothShading,
  34882. color: 0xff0000,
  34883. depthTest: false,
  34884. depthWrite: false}
  34885. );
  34886. return sphereMaterial;
  34887. };
  34888. getSegments () {
  34889. let segments = [];
  34890. for (let i = 0; i < this.points.length - 1; i++) {
  34891. let start = this.points[i].clone();
  34892. let end = this.points[i + 1].clone();
  34893. segments.push({start: start, end: end});
  34894. }
  34895. return segments;
  34896. }
  34897. getSegmentMatrices () {
  34898. let segments = this.getSegments();
  34899. let matrices = [];
  34900. for (let segment of segments) {
  34901. let {start, end} = segment;
  34902. let box = new Object3D();
  34903. let length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  34904. box.scale.set(length, 10000, this.width);
  34905. box.up.set(0, 0, 1);
  34906. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  34907. let diff = new Vector3().subVectors(end, start);
  34908. let target = new Vector3(diff.y, -diff.x, 0);
  34909. box.position.set(0, 0, 0);
  34910. box.lookAt(target);
  34911. box.position.copy(center);
  34912. box.updateMatrixWorld();
  34913. matrices.push(box.matrixWorld);
  34914. }
  34915. return matrices;
  34916. }
  34917. addMarker (point) {
  34918. this.points.push(point);
  34919. let sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial());
  34920. this.add(sphere);
  34921. this.spheres.push(sphere);
  34922. // edges & boxes
  34923. if (this.points.length > 1) {
  34924. let lineGeometry = new Geometry();
  34925. lineGeometry.vertices.push(new Vector3(), new Vector3());
  34926. lineGeometry.colors.push(this.lineColor, this.lineColor, this.lineColor);
  34927. let lineMaterial = new LineBasicMaterial({
  34928. vertexColors: VertexColors,
  34929. linewidth: 2,
  34930. transparent: true,
  34931. opacity: 0.4
  34932. });
  34933. lineMaterial.depthTest = false;
  34934. let edge = new Line(lineGeometry, lineMaterial);
  34935. edge.visible = false;
  34936. this.add(edge);
  34937. this.edges.push(edge);
  34938. let boxGeometry = new BoxGeometry(1, 1, 1);
  34939. let boxMaterial = new MeshBasicMaterial({color: 0xff0000, transparent: true, opacity: 0.2});
  34940. let box = new Mesh(boxGeometry, boxMaterial);
  34941. box.visible = false;
  34942. this.add(box);
  34943. this.boxes.push(box);
  34944. }
  34945. { // event listeners
  34946. let drag = (e) => {
  34947. let I = Utils.getMousePointCloudIntersection(
  34948. e.drag.end,
  34949. e.viewer.scene.getActiveCamera(),
  34950. e.viewer,
  34951. e.viewer.scene.pointclouds);
  34952. if (I) {
  34953. let i = this.spheres.indexOf(e.drag.object);
  34954. if (i !== -1) {
  34955. this.setPosition(i, I.location);
  34956. //this.dispatchEvent({
  34957. // 'type': 'marker_moved',
  34958. // 'profile': this,
  34959. // 'index': i
  34960. //});
  34961. }
  34962. }
  34963. };
  34964. let drop = e => {
  34965. let i = this.spheres.indexOf(e.drag.object);
  34966. if (i !== -1) {
  34967. this.dispatchEvent({
  34968. 'type': 'marker_dropped',
  34969. 'profile': this,
  34970. 'index': i
  34971. });
  34972. }
  34973. };
  34974. let mouseover = (e) => e.object.material.emissive.setHex(0x888888);
  34975. let mouseleave = (e) => e.object.material.emissive.setHex(0x000000);
  34976. sphere.addEventListener('drag', drag);
  34977. sphere.addEventListener('drop', drop);
  34978. sphere.addEventListener('mouseover', mouseover);
  34979. sphere.addEventListener('mouseleave', mouseleave);
  34980. }
  34981. let event = {
  34982. type: 'marker_added',
  34983. profile: this,
  34984. sphere: sphere
  34985. };
  34986. this.dispatchEvent(event);
  34987. this.setPosition(this.points.length - 1, point);
  34988. }
  34989. removeMarker (index) {
  34990. this.points.splice(index, 1);
  34991. this.remove(this.spheres[index]);
  34992. let edgeIndex = (index === 0) ? 0 : (index - 1);
  34993. this.remove(this.edges[edgeIndex]);
  34994. this.edges.splice(edgeIndex, 1);
  34995. this.remove(this.boxes[edgeIndex]);
  34996. this.boxes.splice(edgeIndex, 1);
  34997. this.spheres.splice(index, 1);
  34998. this.update();
  34999. this.dispatchEvent({
  35000. 'type': 'marker_removed',
  35001. 'profile': this
  35002. });
  35003. }
  35004. setPosition (index, position) {
  35005. let point = this.points[index];
  35006. point.copy(position);
  35007. let event = {
  35008. type: 'marker_moved',
  35009. profile: this,
  35010. index: index,
  35011. position: point.clone()
  35012. };
  35013. this.dispatchEvent(event);
  35014. this.update();
  35015. }
  35016. setWidth (width) {
  35017. this.width = width;
  35018. let event = {
  35019. type: 'width_changed',
  35020. profile: this,
  35021. width: width
  35022. };
  35023. this.dispatchEvent(event);
  35024. this.update();
  35025. }
  35026. getWidth () {
  35027. return this.width;
  35028. }
  35029. update () {
  35030. if (this.points.length === 0) {
  35031. return;
  35032. } else if (this.points.length === 1) {
  35033. let point = this.points[0];
  35034. this.spheres[0].position.copy(point);
  35035. return;
  35036. }
  35037. let min = this.points[0].clone();
  35038. let max = this.points[0].clone();
  35039. let centroid = new Vector3();
  35040. let lastIndex = this.points.length - 1;
  35041. for (let i = 0; i <= lastIndex; i++) {
  35042. let point = this.points[i];
  35043. let sphere = this.spheres[i];
  35044. let leftIndex = (i === 0) ? lastIndex : i - 1;
  35045. // let rightIndex = (i === lastIndex) ? 0 : i + 1;
  35046. let leftVertex = this.points[leftIndex];
  35047. // let rightVertex = this.points[rightIndex];
  35048. let leftEdge = this.edges[leftIndex];
  35049. let rightEdge = this.edges[i];
  35050. let leftBox = this.boxes[leftIndex];
  35051. // rightBox = this.boxes[i];
  35052. // let leftEdgeLength = point.distanceTo(leftVertex);
  35053. // let rightEdgeLength = point.distanceTo(rightVertex);
  35054. // let leftEdgeCenter = new THREE.Vector3().addVectors(leftVertex, point).multiplyScalar(0.5);
  35055. // let rightEdgeCenter = new THREE.Vector3().addVectors(point, rightVertex).multiplyScalar(0.5);
  35056. sphere.position.copy(point);
  35057. if (this._modifiable) {
  35058. sphere.visible = true;
  35059. } else {
  35060. sphere.visible = false;
  35061. }
  35062. if (leftEdge) {
  35063. leftEdge.geometry.vertices[1].copy(point);
  35064. leftEdge.geometry.verticesNeedUpdate = true;
  35065. leftEdge.geometry.computeBoundingSphere();
  35066. }
  35067. if (rightEdge) {
  35068. rightEdge.geometry.vertices[0].copy(point);
  35069. rightEdge.geometry.verticesNeedUpdate = true;
  35070. rightEdge.geometry.computeBoundingSphere();
  35071. }
  35072. if (leftBox) {
  35073. let start = leftVertex;
  35074. let end = point;
  35075. let length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  35076. leftBox.scale.set(length, 1000000, this.width);
  35077. leftBox.up.set(0, 0, 1);
  35078. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  35079. let diff = new Vector3().subVectors(end, start);
  35080. let target = new Vector3(diff.y, -diff.x, 0);
  35081. leftBox.position.set(0, 0, 0);
  35082. leftBox.lookAt(target);
  35083. leftBox.position.copy(center);
  35084. }
  35085. centroid.add(point);
  35086. min.min(point);
  35087. max.max(point);
  35088. }
  35089. centroid.multiplyScalar(1 / this.points.length);
  35090. for (let i = 0; i < this.boxes.length; i++) {
  35091. let box = this.boxes[i];
  35092. box.position.z = min.z + (max.z - min.z) / 2;
  35093. }
  35094. }
  35095. raycast (raycaster, intersects) {
  35096. for (let i = 0; i < this.points.length; i++) {
  35097. let sphere = this.spheres[i];
  35098. sphere.raycast(raycaster, intersects);
  35099. }
  35100. // recalculate distances because they are not necessarely correct
  35101. // for scaled objects.
  35102. // see https://github.com/mrdoob/three.js/issues/5827
  35103. // TODO: remove this once the bug has been fixed
  35104. for (let i = 0; i < intersects.length; i++) {
  35105. let I = intersects[i];
  35106. I.distance = raycaster.ray.origin.distanceTo(I.point);
  35107. }
  35108. intersects.sort(function (a, b) { return a.distance - b.distance; });
  35109. };
  35110. get modifiable () {
  35111. return this._modifiable;
  35112. }
  35113. set modifiable (value) {
  35114. this._modifiable = value;
  35115. this.update();
  35116. }
  35117. }
  35118. const _box$4 = new Box3();
  35119. const _vector$d = new Vector3();
  35120. class LineSegmentsGeometry extends InstancedBufferGeometry {
  35121. constructor() {
  35122. super();
  35123. this.isLineSegmentsGeometry = true;
  35124. this.type = 'LineSegmentsGeometry';
  35125. const 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 ];
  35126. const uvs = [ - 1, 2, 1, 2, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 2, 1, - 2 ];
  35127. const index = [ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ];
  35128. this.setIndex( index );
  35129. this.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  35130. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  35131. }
  35132. applyMatrix4( matrix ) {
  35133. const start = this.attributes.instanceStart;
  35134. const end = this.attributes.instanceEnd;
  35135. if ( start !== undefined ) {
  35136. start.applyMatrix4( matrix );
  35137. end.applyMatrix4( matrix );
  35138. start.needsUpdate = true;
  35139. }
  35140. if ( this.boundingBox !== null ) {
  35141. this.computeBoundingBox();
  35142. }
  35143. if ( this.boundingSphere !== null ) {
  35144. this.computeBoundingSphere();
  35145. }
  35146. return this;
  35147. }
  35148. setPositions( array ) {
  35149. let lineSegments;
  35150. if ( array instanceof Float32Array ) {
  35151. lineSegments = array;
  35152. } else if ( Array.isArray( array ) ) {
  35153. lineSegments = new Float32Array( array );
  35154. }
  35155. const instanceBuffer = new InstancedInterleavedBuffer( lineSegments, 6, 1 ); // xyz, xyz
  35156. this.setAttribute( 'instanceStart', new InterleavedBufferAttribute( instanceBuffer, 3, 0 ) ); // xyz
  35157. this.setAttribute( 'instanceEnd', new InterleavedBufferAttribute( instanceBuffer, 3, 3 ) ); // xyz
  35158. //
  35159. this.computeBoundingBox();
  35160. this.computeBoundingSphere();
  35161. return this;
  35162. }
  35163. setColors( array ) {
  35164. let colors;
  35165. if ( array instanceof Float32Array ) {
  35166. colors = array;
  35167. } else if ( Array.isArray( array ) ) {
  35168. colors = new Float32Array( array );
  35169. }
  35170. const instanceColorBuffer = new InstancedInterleavedBuffer( colors, 6, 1 ); // rgb, rgb
  35171. this.setAttribute( 'instanceColorStart', new InterleavedBufferAttribute( instanceColorBuffer, 3, 0 ) ); // rgb
  35172. this.setAttribute( 'instanceColorEnd', new InterleavedBufferAttribute( instanceColorBuffer, 3, 3 ) ); // rgb
  35173. return this;
  35174. }
  35175. fromWireframeGeometry( geometry ) {
  35176. this.setPositions( geometry.attributes.position.array );
  35177. return this;
  35178. }
  35179. fromEdgesGeometry( geometry ) {
  35180. this.setPositions( geometry.attributes.position.array );
  35181. return this;
  35182. }
  35183. fromMesh( mesh ) {
  35184. this.fromWireframeGeometry( new WireframeGeometry( mesh.geometry ) );
  35185. // set colors, maybe
  35186. return this;
  35187. }
  35188. fromLineSegments( lineSegments ) {
  35189. const geometry = lineSegments.geometry;
  35190. this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
  35191. // set colors, maybe
  35192. return this;
  35193. }
  35194. computeBoundingBox() {
  35195. if ( this.boundingBox === null ) {
  35196. this.boundingBox = new Box3();
  35197. }
  35198. const start = this.attributes.instanceStart;
  35199. const end = this.attributes.instanceEnd;
  35200. if ( start !== undefined && end !== undefined ) {
  35201. this.boundingBox.setFromBufferAttribute( start );
  35202. _box$4.setFromBufferAttribute( end );
  35203. this.boundingBox.union( _box$4 );
  35204. }
  35205. }
  35206. computeBoundingSphere() {
  35207. if ( this.boundingSphere === null ) {
  35208. this.boundingSphere = new Sphere();
  35209. }
  35210. if ( this.boundingBox === null ) {
  35211. this.computeBoundingBox();
  35212. }
  35213. const start = this.attributes.instanceStart;
  35214. const end = this.attributes.instanceEnd;
  35215. if ( start !== undefined && end !== undefined ) {
  35216. const center = this.boundingSphere.center;
  35217. this.boundingBox.getCenter( center );
  35218. let maxRadiusSq = 0;
  35219. for ( let i = 0, il = start.count; i < il; i ++ ) {
  35220. _vector$d.fromBufferAttribute( start, i );
  35221. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$d ) );
  35222. _vector$d.fromBufferAttribute( end, i );
  35223. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$d ) );
  35224. }
  35225. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  35226. if ( isNaN( this.boundingSphere.radius ) ) {
  35227. console.error( 'THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this );
  35228. }
  35229. }
  35230. }
  35231. toJSON() {
  35232. // todo
  35233. }
  35234. applyMatrix( matrix ) {
  35235. console.warn( 'THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().' );
  35236. return this.applyMatrix4( matrix );
  35237. }
  35238. }
  35239. /**
  35240. * parameters = {
  35241. * color: <hex>,
  35242. * lineWidth: <float>,
  35243. * dashed: <boolean>,
  35244. * dashScale: <float>,
  35245. * dashSize: <float>,
  35246. * dashOffset: <float>,
  35247. * gapSize: <float>,
  35248. * resolution: <Vector2>, // to be set by renderer
  35249. * }
  35250. */
  35251. UniformsLib.line = {
  35252. /*
  35253. worldUnits: { value: 1 },
  35254. lineWidth: { value: 1 },
  35255. resolution: { value: new Vector2( 1, 1 ) },
  35256. dashOffset: { value: 0 },
  35257. dashScale: { value: 1 },
  35258. dashSize: { value: 1 },
  35259. gapSize: { value: 1 } // todo FIX - maybe change to totalSize
  35260. */
  35261. worldUnits: { value: 1 },
  35262. lineWidth: { value: 1 },
  35263. resolution: { value: new Vector2( 1, 1 ) },
  35264. viewportOffset: { value: new Vector2(0, 0 ) }, //left, top
  35265. devicePixelRatio:{ value:window.devicePixelRatio},
  35266. dashScale: { value: 1 },
  35267. dashSize: { value: 1 },
  35268. dashOffset: { value: 0 },
  35269. gapSize: { value: 1 },
  35270. opacity: { value: 1 },
  35271. backColor: {type:'v3', value: new Color("#ddd")},
  35272. clipDistance : { type: 'f', value: 4}, //消失距离
  35273. occlusionDistance : { type: 'f', value: 1 }, //变为backColor距离
  35274. maxClipFactor : { type: 'f', value: 1 }, //0-1
  35275. maxOcclusionFactor : { type: 'f', value: 1 }, //0-1
  35276. depthTexture:{ value: null },
  35277. nearPlane:{value: 0.1},
  35278. farPlane:{value: 100000},
  35279. //uUseOrthographicCamera:{ type: "b", value: false },
  35280. };
  35281. ShaderLib[ 'line' ] = {
  35282. uniforms: UniformsUtils.merge( [
  35283. UniformsLib.common,
  35284. UniformsLib.fog,
  35285. UniformsLib.line
  35286. ] ),
  35287. vertexShader:
  35288. /* glsl */`
  35289. #include <common>
  35290. #include <color_pars_vertex>
  35291. #include <fog_pars_vertex>
  35292. #include <logdepthbuf_pars_vertex>
  35293. #include <clipping_planes_pars_vertex>
  35294. uniform float lineWidth;
  35295. uniform vec2 resolution;
  35296. uniform float devicePixelRatio; //add
  35297. attribute vec3 instanceStart;
  35298. attribute vec3 instanceEnd;
  35299. attribute vec3 instanceColorStart;
  35300. attribute vec3 instanceColorEnd;
  35301. #ifdef WORLD_UNITS
  35302. varying vec4 worldPos;
  35303. varying vec3 worldStart;
  35304. varying vec3 worldEnd;
  35305. #ifdef USE_DASH
  35306. varying vec2 vUv;
  35307. #endif
  35308. #else
  35309. varying vec2 vUv;
  35310. #endif
  35311. #ifdef USE_DASH
  35312. uniform float dashScale;
  35313. attribute float instanceDistanceStart;
  35314. attribute float instanceDistanceEnd;
  35315. varying float vLineDistance;
  35316. #endif
  35317. void trimSegment( const in vec4 start, inout vec4 end ) {
  35318. // trim end segment so it terminates between the camera plane and the near plane
  35319. // conservative estimate of the near plane
  35320. float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
  35321. float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
  35322. float nearEstimate = - 0.5 * b / a;
  35323. float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
  35324. end.xyz = mix( start.xyz, end.xyz, alpha );
  35325. }
  35326. void main() {
  35327. #ifdef USE_COLOR
  35328. vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
  35329. #endif
  35330. #ifdef USE_DASH
  35331. vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
  35332. vUv = uv;
  35333. #endif
  35334. float aspect = resolution.x / resolution.y;
  35335. // camera space
  35336. vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
  35337. vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
  35338. #ifdef WORLD_UNITS
  35339. worldStart = start.xyz;
  35340. worldEnd = end.xyz;
  35341. #else
  35342. vUv = uv;
  35343. #endif
  35344. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  35345. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  35346. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  35347. // perhaps there is a more elegant solution -- WestLangley
  35348. bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
  35349. if ( perspective ) {
  35350. if ( start.z < 0.0 && end.z >= 0.0 ) {
  35351. trimSegment( start, end );
  35352. } else if ( end.z < 0.0 && start.z >= 0.0 ) {
  35353. trimSegment( end, start );
  35354. }
  35355. }
  35356. // clip space
  35357. vec4 clipStart = projectionMatrix * start;
  35358. vec4 clipEnd = projectionMatrix * end;
  35359. // ndc space
  35360. vec3 ndcStart = clipStart.xyz / clipStart.w;
  35361. vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
  35362. // direction
  35363. vec2 dir = ndcEnd.xy - ndcStart.xy;
  35364. // account for clip-space aspect ratio
  35365. dir.x *= aspect;
  35366. dir = normalize( dir );
  35367. #ifdef WORLD_UNITS
  35368. // get the offset direction as perpendicular to the view vector
  35369. vec3 worldDir = normalize( end.xyz - start.xyz );
  35370. vec3 offset;
  35371. if ( position.y < 0.5 ) {
  35372. offset = normalize( cross( start.xyz, worldDir ) );
  35373. } else {
  35374. offset = normalize( cross( end.xyz, worldDir ) );
  35375. }
  35376. // sign flip
  35377. if ( position.x < 0.0 ) offset *= - 1.0;
  35378. float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
  35379. // don't extend the line if we're rendering dashes because we
  35380. // won't be rendering the endcaps
  35381. #ifndef USE_DASH
  35382. // extend the line bounds to encompass endcaps
  35383. start.xyz += - worldDir * lineWidth * 0.5;
  35384. end.xyz += worldDir * lineWidth * 0.5;
  35385. // shift the position of the quad so it hugs the forward edge of the line
  35386. offset.xy -= dir * forwardOffset;
  35387. offset.z += 0.5;
  35388. #endif
  35389. // endcaps
  35390. if ( position.y > 1.0 || position.y < 0.0 ) {
  35391. offset.xy += dir * 2.0 * forwardOffset;
  35392. }
  35393. // adjust for lineWidth
  35394. offset *= lineWidth * 0.5;
  35395. // set the world position
  35396. worldPos = ( position.y < 0.5 ) ? start : end;
  35397. worldPos.xyz += offset;
  35398. // project the worldpos
  35399. vec4 clip = projectionMatrix * worldPos;
  35400. // shift the depth of the projected points so the line
  35401. // segments overlap neatly
  35402. vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
  35403. clip.z = clipPose.z * clip.w;
  35404. #else
  35405. vec2 offset = vec2( dir.y, - dir.x );
  35406. // undo aspect ratio adjustment
  35407. dir.x /= aspect;
  35408. offset.x /= aspect;
  35409. // sign flip
  35410. if ( position.x < 0.0 ) offset *= - 1.0;
  35411. // endcaps
  35412. if ( position.y < 0.0 ) {
  35413. offset += - dir;
  35414. } else if ( position.y > 1.0 ) {
  35415. offset += dir;
  35416. }
  35417. // adjust for lineWidth
  35418. offset *= lineWidth;
  35419. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  35420. offset /= resolution.y; //* devicePixelRatio;
  35421. // select end
  35422. vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
  35423. // back to clip space
  35424. offset *= clip.w;
  35425. clip.xy += offset;
  35426. #endif
  35427. gl_Position = clip;
  35428. vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
  35429. #include <logdepthbuf_vertex>
  35430. #include <clipping_planes_vertex>
  35431. #include <fog_vertex>
  35432. }
  35433. `,
  35434. fragmentShader:
  35435. /* glsl */`
  35436. uniform vec3 diffuse;
  35437. uniform float opacity;
  35438. uniform float lineWidth;
  35439. uniform bool uUseOrthographicCamera;
  35440. #ifdef USE_DASH
  35441. uniform float dashOffset;
  35442. uniform float dashSize;
  35443. uniform float gapSize;
  35444. #endif
  35445. //加
  35446. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  35447. uniform sampler2D depthTexture;
  35448. uniform float nearPlane;
  35449. uniform float farPlane;
  35450. uniform vec2 resolution;
  35451. uniform vec2 viewportOffset;
  35452. uniform vec3 backColor;
  35453. uniform float occlusionDistance;
  35454. uniform float clipDistance;
  35455. uniform float maxClipFactor;
  35456. uniform float maxOcclusionFactor;
  35457. #endif
  35458. varying float vLineDistance;
  35459. #ifdef WORLD_UNITS
  35460. varying vec4 worldPos;
  35461. varying vec3 worldStart;
  35462. varying vec3 worldEnd;
  35463. #ifdef USE_DASH
  35464. varying vec2 vUv;
  35465. #endif
  35466. #else
  35467. varying vec2 vUv;
  35468. #endif
  35469. #include <common>
  35470. #include <color_pars_fragment>
  35471. #include <fog_pars_fragment>
  35472. #include <logdepthbuf_pars_fragment>
  35473. #include <clipping_planes_pars_fragment>
  35474. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  35475. float convertToLinear(float zValue)
  35476. {
  35477. //if(uUseOrthographicCamera){
  35478. // return zValue*(farPlane-nearPlane)+nearPlane;
  35479. //}else{
  35480. float z = zValue * 2.0 - 1.0;
  35481. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  35482. //}
  35483. }
  35484. #endif
  35485. vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
  35486. float mua;
  35487. float mub;
  35488. vec3 p13 = p1 - p3;
  35489. vec3 p43 = p4 - p3;
  35490. vec3 p21 = p2 - p1;
  35491. float d1343 = dot( p13, p43 );
  35492. float d4321 = dot( p43, p21 );
  35493. float d1321 = dot( p13, p21 );
  35494. float d4343 = dot( p43, p43 );
  35495. float d2121 = dot( p21, p21 );
  35496. float denom = d2121 * d4343 - d4321 * d4321;
  35497. float numer = d1343 * d4321 - d1321 * d4343;
  35498. mua = numer / denom;
  35499. mua = clamp( mua, 0.0, 1.0 );
  35500. mub = ( d1343 + d4321 * ( mua ) ) / d4343;
  35501. mub = clamp( mub, 0.0, 1.0 );
  35502. return vec2( mua, mub );
  35503. }
  35504. void main() {
  35505. #include <clipping_planes_fragment>
  35506. /*#ifdef USE_DASH
  35507. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  35508. if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
  35509. #endif*/
  35510. #ifdef USE_DASH
  35511. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  35512. bool unvisible = mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize;
  35513. //加
  35514. #ifdef DASH_with_depth
  35515. #else
  35516. if (unvisible) discard; // todo - FIX
  35517. #endif
  35518. #endif
  35519. float alpha = opacity;
  35520. #ifdef WORLD_UNITS
  35521. // Find the closest points on the view ray and the line segment
  35522. vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
  35523. vec3 lineDir = worldEnd - worldStart;
  35524. vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
  35525. vec3 p1 = worldStart + lineDir * params.x;
  35526. vec3 p2 = rayEnd * params.y;
  35527. vec3 delta = p1 - p2;
  35528. float len = length( delta );
  35529. float norm = len / lineWidth;
  35530. #ifndef USE_DASH
  35531. #ifdef USE_ALPHA_TO_COVERAGE
  35532. float dnorm = fwidth( norm );
  35533. alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
  35534. #else
  35535. if ( norm > 0.5 ) {
  35536. discard;
  35537. }
  35538. #endif
  35539. #endif
  35540. #else
  35541. #ifdef USE_ALPHA_TO_COVERAGE
  35542. // artifacts appear on some hardware if a derivative is taken within a conditional
  35543. float a = vUv.x;
  35544. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  35545. float len2 = a * a + b * b;
  35546. float dlen = fwidth( len2 );
  35547. if ( abs( vUv.y ) > 1.0 ) {
  35548. alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
  35549. }
  35550. #else
  35551. if ( abs( vUv.y ) > 1.0 ) {
  35552. float a = vUv.x;
  35553. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  35554. float len2 = a * a + b * b;
  35555. if ( len2 > 1.0 ) discard;
  35556. }
  35557. #endif
  35558. #endif
  35559. vec4 diffuseColor = vec4( diffuse, alpha );
  35560. //加
  35561. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  35562. float mixFactor = 0.0;
  35563. float clipFactor = 0.0;
  35564. float fragDepth = convertToLinear(gl_FragCoord.z);
  35565. //gl_FragCoord大小为 viewport client大小
  35566. vec2 depthTxtCoords = vec2(gl_FragCoord.x - viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  35567. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  35568. float delta = fragDepth - textureDepth;
  35569. if (delta > 0.0)
  35570. {
  35571. mixFactor = clamp(delta / occlusionDistance, 0.0, maxOcclusionFactor);
  35572. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  35573. }
  35574. if (clipFactor == 1.0)
  35575. {
  35576. discard;
  35577. }
  35578. vec4 backColor_ = vec4(backColor, opacity); //vec4(0.8,0.8,0.8, 0.8*opacity);
  35579. #ifdef DASH_with_depth
  35580. // 只在被遮住的部分显示虚线, 所以若同时是虚线不可见部分和被遮住时, a为0
  35581. if(unvisible) backColor_.a = 0.0;
  35582. #endif
  35583. //vec4 diffuseColor = vec4(mix(diffuse, backColor_, mixFactor), opacity*(1.0 - clipFactor));
  35584. diffuseColor = mix(diffuseColor, backColor_ , mixFactor);
  35585. diffuseColor.a *= (1.0 - clipFactor);
  35586. #endif
  35587. #include <logdepthbuf_fragment>
  35588. #include <color_fragment>
  35589. //gl_FragColor = vec4( diffuseColor.rgb, alpha );
  35590. gl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );
  35591. #include <tonemapping_fragment>
  35592. #include <encodings_fragment>
  35593. #include <fog_fragment>
  35594. #include <premultiplied_alpha_fragment>
  35595. }
  35596. `
  35597. };
  35598. class LineMaterial extends ShaderMaterial {
  35599. constructor( parameters ) {
  35600. super( {
  35601. type: 'LineMaterial',
  35602. uniforms: UniformsUtils.clone( ShaderLib[ 'line' ].uniforms ),
  35603. vertexShader: ShaderLib[ 'line' ].vertexShader,
  35604. fragmentShader: ShaderLib[ 'line' ].fragmentShader,
  35605. clipping: true // required for clipping support
  35606. } );
  35607. this.isLineMaterial = true;
  35608. this.lineWidth_ = 0;
  35609. this.supportExtDepth = parameters.supportExtDepth;
  35610. this.depthTestWhenPick = false; //pick时是否识别点云等
  35611. if(parameters.color){
  35612. this.color = new Color(parameters.color);
  35613. }
  35614. if(parameters.backColor){
  35615. this.uniforms.backColor.value = new Color(parameters.backColor);
  35616. }
  35617. if(parameters.clipDistance){
  35618. this.uniforms.clipDistance.value = parameters.clipDistance;
  35619. }
  35620. if(parameters.occlusionDistance){
  35621. this.uniforms.occlusionDistance.value = parameters.occlusionDistance;
  35622. }
  35623. if(parameters.maxClipFactor){
  35624. this.uniforms.maxClipFactor.value = parameters.maxClipFactor;
  35625. }
  35626. Object.defineProperties( this, {
  35627. color: {
  35628. enumerable: true,
  35629. get: function () {
  35630. return this.uniforms.diffuse.value;
  35631. },
  35632. set: function ( value ) {
  35633. this.uniforms.diffuse.value = value;
  35634. }
  35635. },
  35636. worldUnits: {
  35637. enumerable: true,
  35638. get: function () {
  35639. return 'WORLD_UNITS' in this.defines;
  35640. },
  35641. set: function ( value ) {
  35642. if ( value === true ) {
  35643. this.defines.WORLD_UNITS = '';
  35644. } else {
  35645. delete this.defines.WORLD_UNITS;
  35646. }
  35647. }
  35648. },
  35649. lineWidth: {
  35650. enumerable: true,
  35651. get: function () {
  35652. return this.lineWidth_;//this.uniforms.lineWidth.value;
  35653. },
  35654. set: function ( value ) {
  35655. this.uniforms.lineWidth.value = value * window.devicePixelRatio;
  35656. this.lineWidth_ = value;
  35657. }
  35658. },
  35659. dashed: {
  35660. enumerable: true,
  35661. get: function () {
  35662. return Boolean( 'USE_DASH' in this.defines );
  35663. },
  35664. set( value ) {
  35665. if ( Boolean( value ) !== Boolean( 'USE_DASH' in this.defines ) ) {
  35666. this.needsUpdate = true;
  35667. }
  35668. if ( value === true ) {
  35669. this.defines.USE_DASH = '';
  35670. } else {
  35671. delete this.defines.USE_DASH;
  35672. }
  35673. }
  35674. },
  35675. dashScale: {
  35676. enumerable: true,
  35677. get: function () {
  35678. return this.uniforms.dashScale.value;
  35679. },
  35680. set: function ( value ) {
  35681. this.uniforms.dashScale.value = value;
  35682. }
  35683. },
  35684. dashSize: {
  35685. enumerable: true,
  35686. get: function () {
  35687. return this.uniforms.dashSize.value;
  35688. },
  35689. set: function ( value ) {
  35690. this.uniforms.dashSize.value = value;
  35691. }
  35692. },
  35693. dashOffset: {
  35694. enumerable: true,
  35695. get: function () {
  35696. return this.uniforms.dashOffset.value;
  35697. },
  35698. set: function ( value ) {
  35699. this.uniforms.dashOffset.value = value;
  35700. }
  35701. },
  35702. gapSize: {
  35703. enumerable: true,
  35704. get: function () {
  35705. return this.uniforms.gapSize.value;
  35706. },
  35707. set: function ( value ) {
  35708. this.uniforms.gapSize.value = value;
  35709. }
  35710. },
  35711. opacity: {
  35712. enumerable: true,
  35713. get: function () {
  35714. return this.uniforms.opacity.value;
  35715. },
  35716. set: function ( value ) {
  35717. this.uniforms.opacity.value = value;
  35718. }
  35719. },
  35720. resolution: {
  35721. enumerable: true,
  35722. get: function () {
  35723. return this.uniforms.resolution.value;
  35724. },
  35725. set: function ( value ) {
  35726. this.uniforms.resolution.value.copy( value );
  35727. }
  35728. },
  35729. alphaToCoverage: {
  35730. enumerable: true,
  35731. get: function () {
  35732. return Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines );
  35733. },
  35734. set: function ( value ) {
  35735. if ( Boolean( value ) !== Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines ) ) {
  35736. this.needsUpdate = true;
  35737. }
  35738. if ( value === true ) {
  35739. this.defines.USE_ALPHA_TO_COVERAGE = '';
  35740. this.extensions.derivatives = true;
  35741. } else {
  35742. delete this.defines.USE_ALPHA_TO_COVERAGE;
  35743. this.extensions.derivatives = false;
  35744. }
  35745. }
  35746. },
  35747. dashWithDepth:{//add
  35748. enumerable: true,
  35749. get: function () {
  35750. return 'DASH_with_depth' in this.defines
  35751. },
  35752. set: function ( value ) {
  35753. value = value && !!this.supportExtDepth;
  35754. if(value != this.dashWithDepth){
  35755. if(value){
  35756. this.defines.DASH_with_depth = '';
  35757. }else {
  35758. delete this.defines.DASH_with_depth;
  35759. }
  35760. this.needsUpdate = true;
  35761. }
  35762. }
  35763. },
  35764. } );
  35765. this.events = {
  35766. setSize:(e)=>{//如果出现横条状的异常,往往是viewportOffset出错 //地图不需要
  35767. let viewport = e.viewport;
  35768. //console.log(viewport.name, viewport.resolution2)
  35769. this.uniforms.resolution.value.copy(viewport.resolution2);
  35770. this.uniforms.devicePixelRatio.value = window.devicePixelRatio;
  35771. this.lineWidth = this.lineWidth_; //update
  35772. if(!this.realUseDepth || !e.viewport)return
  35773. let viewportOffset = viewport.offset || new THREE.Vector2();
  35774. this.uniforms.viewportOffset.value.copy(viewportOffset);
  35775. },
  35776. render:(e)=>{//before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  35777. this.updateDepthParams(e);
  35778. }
  35779. };
  35780. this.setValues( parameters );
  35781. let viewport = viewer.mainViewport;
  35782. this.events.setSize({viewport});
  35783. viewer.addEventListener('resize', this.events.setSize);
  35784. }
  35785. get useDepth(){
  35786. return this.useDepth_
  35787. }
  35788. set useDepth(value){
  35789. value = value && this.supportExtDepth; //如果不支持 EXT_DEPTH 的话会失效
  35790. if(this.useDepth_ != value){
  35791. this.setRealDepth(value);
  35792. this.useDepth_ = value;
  35793. if(value){
  35794. viewer.addEventListener("render.begin", this.events.render);
  35795. this.updateDepthParams();
  35796. }else {
  35797. viewer.removeEventListener("render.begin", this.events.render);
  35798. }
  35799. }
  35800. }
  35801. setRealDepth(useDepth, viewport){//确实使用到depthTex
  35802. if(this.realUseDepth != useDepth){
  35803. if(useDepth ){
  35804. this.defines.useDepth = '';
  35805. }else {
  35806. delete this.defines.useDepth;
  35807. }
  35808. this.realUseDepth = useDepth;
  35809. if(this.autoDepthTest)this.depthWrite = this.depthTest = !useDepth; //如果useDepth = false,使用原始的depthTest
  35810. this.needsUpdate = true;
  35811. if(!viewport)viewport = viewer.mainViewport; //暂时这么设置
  35812. useDepth && this.events.setSize({viewport});
  35813. }
  35814. }
  35815. updateDepthParams(e={}){
  35816. var viewport = e.viewport || viewer.mainViewport;
  35817. var camera = viewport.camera;
  35818. let hasDepth = this.useDepth && camera.isPerspectiveCamera &&
  35819. (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL);
  35820. this.setRealDepth(hasDepth, viewport);
  35821. if(hasDepth){
  35822. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行
  35823. this.uniforms.nearPlane.value = camera.near;
  35824. this.uniforms.farPlane.value = camera.far;
  35825. }
  35826. //this.uniforms.uUseOrthographicCamera.value = !camera.isPerspectiveCamera
  35827. }
  35828. }
  35829. const _start$2 = new Vector3();
  35830. const _end$2 = new Vector3();
  35831. const _start4 = new Vector4();
  35832. const _end4 = new Vector4();
  35833. const _ssOrigin = new Vector4();
  35834. const _ssOrigin3 = new Vector3();
  35835. const _mvMatrix = new Matrix4();
  35836. const _line = new Line3();
  35837. const _closestPoint = new Vector3();
  35838. const _box$5 = new Box3();
  35839. const _sphere$4 = new Sphere();
  35840. const _clipToWorldVector = new Vector4();
  35841. let _ray$3, _instanceStart, _instanceEnd, _lineWidth;
  35842. // Returns the margin required to expand by in world space given the distance from the camera,
  35843. // line width, resolution, and camera projection
  35844. function getWorldSpaceHalfWidth( camera, distance, resolution ) {
  35845. // transform into clip space, adjust the x and y values by the pixel width offset, then
  35846. // transform back into world space to get world offset. Note clip space is [-1, 1] so full
  35847. // width does not need to be halved.
  35848. _clipToWorldVector.set( 0, 0, - distance, 1.0 ).applyMatrix4( camera.projectionMatrix );
  35849. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  35850. _clipToWorldVector.x = _lineWidth / resolution.width;
  35851. _clipToWorldVector.y = _lineWidth / resolution.height;
  35852. _clipToWorldVector.applyMatrix4( camera.projectionMatrixInverse );
  35853. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  35854. return Math.abs( Math.max( _clipToWorldVector.x, _clipToWorldVector.y ) );
  35855. }
  35856. function raycastWorldUnits( lineSegments, intersects ) {
  35857. for ( let i = 0, l = _instanceStart.count; i < l; i ++ ) {
  35858. _line.start.fromBufferAttribute( _instanceStart, i );
  35859. _line.end.fromBufferAttribute( _instanceEnd, i );
  35860. const pointOnLine = new Vector3();
  35861. const point = new Vector3();
  35862. _ray$3.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  35863. const isInside = point.distanceTo( pointOnLine ) < _lineWidth * 0.5;
  35864. if ( isInside ) {
  35865. intersects.push( {
  35866. point,
  35867. pointOnLine,
  35868. distance: _ray$3.origin.distanceTo( point ),
  35869. object: lineSegments,
  35870. face: null,
  35871. faceIndex: i,
  35872. uv: null,
  35873. uv2: null,
  35874. } );
  35875. }
  35876. }
  35877. }
  35878. function raycastScreenSpace( lineSegments, camera, intersects ) {
  35879. const projectionMatrix = camera.projectionMatrix;
  35880. const material = lineSegments.material;
  35881. const resolution = material.resolution;
  35882. const matrixWorld = lineSegments.matrixWorld;
  35883. const geometry = lineSegments.geometry;
  35884. const instanceStart = geometry.attributes.instanceStart;
  35885. const instanceEnd = geometry.attributes.instanceEnd;
  35886. const near = - camera.near;
  35887. //
  35888. // pick a point 1 unit out along the ray to avoid the ray origin
  35889. // sitting at the camera origin which will cause "w" to be 0 when
  35890. // applying the projection matrix.
  35891. _ray$3.at( 1, _ssOrigin );
  35892. // ndc space [ - 1.0, 1.0 ]
  35893. _ssOrigin.w = 1;
  35894. _ssOrigin.applyMatrix4( camera.matrixWorldInverse );
  35895. _ssOrigin.applyMatrix4( projectionMatrix );
  35896. _ssOrigin.multiplyScalar( 1 / _ssOrigin.w );
  35897. // screen space
  35898. _ssOrigin.x *= resolution.x / 2;
  35899. _ssOrigin.y *= resolution.y / 2;
  35900. _ssOrigin.z = 0;
  35901. _ssOrigin3.copy( _ssOrigin );
  35902. _mvMatrix.multiplyMatrices( camera.matrixWorldInverse, matrixWorld );
  35903. for ( let i = 0, l = instanceStart.count; i < l; i ++ ) {
  35904. _start4.fromBufferAttribute( instanceStart, i );
  35905. _end4.fromBufferAttribute( instanceEnd, i );
  35906. _start4.w = 1;
  35907. _end4.w = 1;
  35908. // camera space
  35909. _start4.applyMatrix4( _mvMatrix );
  35910. _end4.applyMatrix4( _mvMatrix );
  35911. // skip the segment if it's entirely behind the camera
  35912. const isBehindCameraNear = _start4.z > near && _end4.z > near;
  35913. if ( isBehindCameraNear ) {
  35914. continue;
  35915. }
  35916. // trim the segment if it extends behind camera near
  35917. if ( _start4.z > near ) {
  35918. const deltaDist = _start4.z - _end4.z;
  35919. const t = ( _start4.z - near ) / deltaDist;
  35920. _start4.lerp( _end4, t );
  35921. } else if ( _end4.z > near ) {
  35922. const deltaDist = _end4.z - _start4.z;
  35923. const t = ( _end4.z - near ) / deltaDist;
  35924. _end4.lerp( _start4, t );
  35925. }
  35926. // clip space
  35927. _start4.applyMatrix4( projectionMatrix );
  35928. _end4.applyMatrix4( projectionMatrix );
  35929. // ndc space [ - 1.0, 1.0 ]
  35930. _start4.multiplyScalar( 1 / _start4.w );
  35931. _end4.multiplyScalar( 1 / _end4.w );
  35932. // screen space
  35933. _start4.x *= resolution.x / 2;
  35934. _start4.y *= resolution.y / 2;
  35935. _end4.x *= resolution.x / 2;
  35936. _end4.y *= resolution.y / 2;
  35937. // create 2d segment
  35938. _line.start.copy( _start4 );
  35939. _line.start.z = 0;
  35940. _line.end.copy( _end4 );
  35941. _line.end.z = 0;
  35942. // get closest point on ray to segment
  35943. const param = _line.closestPointToPointParameter( _ssOrigin3, true );
  35944. _line.at( param, _closestPoint );
  35945. // check if the intersection point is within clip space
  35946. const zPos = MathUtils.lerp( _start4.z, _end4.z, param );
  35947. const isInClipSpace = zPos >= - 1 && zPos <= 1;
  35948. const isInside = _ssOrigin3.distanceTo( _closestPoint ) < _lineWidth * 0.5;
  35949. if ( isInClipSpace && isInside ) {
  35950. _line.start.fromBufferAttribute( instanceStart, i );
  35951. _line.end.fromBufferAttribute( instanceEnd, i );
  35952. _line.start.applyMatrix4( matrixWorld );
  35953. _line.end.applyMatrix4( matrixWorld );
  35954. const pointOnLine = new Vector3();
  35955. const point = new Vector3();
  35956. _ray$3.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  35957. intersects.push( {
  35958. point: point,
  35959. pointOnLine: pointOnLine,
  35960. distance: _ray$3.origin.distanceTo( point ),
  35961. object: lineSegments,
  35962. face: null,
  35963. faceIndex: i,
  35964. uv: null,
  35965. uv2: null,
  35966. } );
  35967. }
  35968. }
  35969. }
  35970. class LineSegments2 extends Mesh {
  35971. constructor( geometry = new LineSegmentsGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  35972. super( geometry, material );
  35973. this.isLineSegments2 = true;
  35974. this.type = 'LineSegments2';
  35975. }
  35976. // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  35977. computeLineDistances() {
  35978. const geometry = this.geometry;
  35979. const instanceStart = geometry.attributes.instanceStart;
  35980. const instanceEnd = geometry.attributes.instanceEnd;
  35981. const lineDistances = new Float32Array( 2 * instanceStart.count );
  35982. for ( let i = 0, j = 0, l = instanceStart.count; i < l; i ++, j += 2 ) {
  35983. _start$2.fromBufferAttribute( instanceStart, i );
  35984. _end$2.fromBufferAttribute( instanceEnd, i );
  35985. lineDistances[ j ] = ( j === 0 ) ? 0 : lineDistances[ j - 1 ];
  35986. lineDistances[ j + 1 ] = lineDistances[ j ] + _start$2.distanceTo( _end$2 );
  35987. }
  35988. const instanceDistanceBuffer = new InstancedInterleavedBuffer( lineDistances, 2, 1 ); // d0, d1
  35989. geometry.setAttribute( 'instanceDistanceStart', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 0 ) ); // d0
  35990. geometry.setAttribute( 'instanceDistanceEnd', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 1 ) ); // d1
  35991. return this;
  35992. }
  35993. raycast( raycaster, intersects ) {
  35994. const worldUnits = this.material.worldUnits;
  35995. const camera = raycaster.camera;
  35996. if ( camera === null && ! worldUnits ) {
  35997. console.error( 'LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.' );
  35998. }
  35999. const threshold = ( raycaster.params.Line2 !== undefined ) ? raycaster.params.Line2.threshold || 0 : 0;
  36000. _ray$3 = raycaster.ray;
  36001. const matrixWorld = this.matrixWorld;
  36002. const geometry = this.geometry;
  36003. const material = this.material;
  36004. _lineWidth = material.lineWidth + threshold;
  36005. _instanceStart = geometry.attributes.instanceStart;
  36006. _instanceEnd = geometry.attributes.instanceEnd;
  36007. // check if we intersect the sphere bounds
  36008. if ( geometry.boundingSphere === null ) {
  36009. geometry.computeBoundingSphere();
  36010. }
  36011. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( matrixWorld );
  36012. // increase the sphere bounds by the worst case line screen space width
  36013. let sphereMargin;
  36014. if ( worldUnits ) {
  36015. sphereMargin = _lineWidth * 0.5;
  36016. } else {
  36017. const distanceToSphere = Math.max( camera.near, _sphere$4.distanceToPoint( _ray$3.origin ) );
  36018. sphereMargin = getWorldSpaceHalfWidth( camera, distanceToSphere, material.resolution );
  36019. }
  36020. _sphere$4.radius += sphereMargin;
  36021. if ( _ray$3.intersectsSphere( _sphere$4 ) === false ) {
  36022. return;
  36023. }
  36024. // check if we intersect the box bounds
  36025. if ( geometry.boundingBox === null ) {
  36026. geometry.computeBoundingBox();
  36027. }
  36028. _box$5.copy( geometry.boundingBox ).applyMatrix4( matrixWorld );
  36029. // increase the box bounds by the worst case line width
  36030. let boxMargin;
  36031. if ( worldUnits ) {
  36032. boxMargin = _lineWidth * 0.5;
  36033. } else {
  36034. const distanceToBox = Math.max( camera.near, _box$5.distanceToPoint( _ray$3.origin ) );
  36035. boxMargin = getWorldSpaceHalfWidth( camera, distanceToBox, material.resolution );
  36036. }
  36037. _box$5.expandByScalar( boxMargin );
  36038. if ( _ray$3.intersectsBox( _box$5 ) === false ) {
  36039. return;
  36040. }
  36041. if ( worldUnits ) {
  36042. raycastWorldUnits( this, intersects );
  36043. } else {
  36044. raycastScreenSpace( this, camera, intersects );
  36045. }
  36046. }
  36047. }
  36048. class LineGeometry extends LineSegmentsGeometry {
  36049. constructor() {
  36050. super();
  36051. this.isLineGeometry = true;
  36052. this.type = 'LineGeometry';
  36053. }
  36054. setPositions( array ) {//见potree.shim.js
  36055. // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format
  36056. const length = array.length - 3;
  36057. const points = new Float32Array( 2 * length );
  36058. for ( let i = 0; i < length; i += 3 ) {
  36059. points[ 2 * i ] = array[ i ];
  36060. points[ 2 * i + 1 ] = array[ i + 1 ];
  36061. points[ 2 * i + 2 ] = array[ i + 2 ];
  36062. points[ 2 * i + 3 ] = array[ i + 3 ];
  36063. points[ 2 * i + 4 ] = array[ i + 4 ];
  36064. points[ 2 * i + 5 ] = array[ i + 5 ];
  36065. }
  36066. super.setPositions( points );
  36067. return this;
  36068. }
  36069. setColors( array ) {
  36070. // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format
  36071. const length = array.length - 3;
  36072. const colors = new Float32Array( 2 * length );
  36073. for ( let i = 0; i < length; i += 3 ) {
  36074. colors[ 2 * i ] = array[ i ];
  36075. colors[ 2 * i + 1 ] = array[ i + 1 ];
  36076. colors[ 2 * i + 2 ] = array[ i + 2 ];
  36077. colors[ 2 * i + 3 ] = array[ i + 3 ];
  36078. colors[ 2 * i + 4 ] = array[ i + 4 ];
  36079. colors[ 2 * i + 5 ] = array[ i + 5 ];
  36080. }
  36081. super.setColors( colors );
  36082. return this;
  36083. }
  36084. fromLine( line ) {
  36085. const geometry = line.geometry;
  36086. this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
  36087. // set colors, maybe
  36088. return this;
  36089. }
  36090. }
  36091. class Line2 extends LineSegments2 {
  36092. constructor( geometry = new LineGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  36093. super( geometry, material );
  36094. this.isLine2 = true;
  36095. this.type = 'Line2';
  36096. }
  36097. }
  36098. //old
  36099. function createHeightLine(){
  36100. let lineGeometry = new LineGeometry();
  36101. lineGeometry.setPositions([
  36102. 0, 0, 0,
  36103. 0, 0, 0,
  36104. ]);
  36105. let lineMaterial = new LineMaterial({
  36106. color: 0x00ff00,
  36107. dashSize: 5,
  36108. gapSize: 2,
  36109. linewidth: 2,
  36110. resolution: new Vector2(1000, 1000),
  36111. });
  36112. lineMaterial.depthTest = false;
  36113. const heightEdge = new Line2(lineGeometry, lineMaterial);
  36114. heightEdge.visible = false;
  36115. //this.add(this.heightEdge);
  36116. return heightEdge;
  36117. }
  36118. function createHeightLabel(){
  36119. const heightLabel = new TextSprite$1('');
  36120. heightLabel.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  36121. heightLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  36122. heightLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  36123. heightLabel.fontsize = 16;
  36124. heightLabel.material.depthTest = false;
  36125. heightLabel.material.opacity = 1;
  36126. heightLabel.visible = false;
  36127. return heightLabel;
  36128. }
  36129. function createAreaLabel(){
  36130. const areaLabel = new TextSprite$1('');
  36131. areaLabel.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  36132. areaLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  36133. areaLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  36134. areaLabel.fontsize = 16;
  36135. areaLabel.material.depthTest = false;
  36136. areaLabel.material.opacity = 1;
  36137. areaLabel.visible = false;
  36138. return areaLabel;
  36139. }
  36140. function createCircleRadiusLabel(){
  36141. const circleRadiusLabel = new TextSprite$1("");
  36142. circleRadiusLabel.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  36143. circleRadiusLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  36144. circleRadiusLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  36145. circleRadiusLabel.fontsize = 16;
  36146. circleRadiusLabel.material.depthTest = false;
  36147. circleRadiusLabel.material.opacity = 1;
  36148. circleRadiusLabel.visible = false;
  36149. return circleRadiusLabel;
  36150. }
  36151. function createCircleRadiusLine(){
  36152. const lineGeometry = new LineGeometry();
  36153. lineGeometry.setPositions([
  36154. 0, 0, 0,
  36155. 0, 0, 0,
  36156. ]);
  36157. const lineMaterial = new LineMaterial({
  36158. color: 0xff0000,
  36159. linewidth: 2,
  36160. resolution: new Vector2(1000, 1000),
  36161. gapSize: 1,
  36162. dashed: true,
  36163. });
  36164. lineMaterial.depthTest = false;
  36165. const circleRadiusLine = new Line2(lineGeometry, lineMaterial);
  36166. circleRadiusLine.visible = false;
  36167. return circleRadiusLine;
  36168. }
  36169. function createCircleLine(){
  36170. const coordinates = [];
  36171. let n = 128;
  36172. for(let i = 0; i <= n; i++){
  36173. let u0 = 2 * Math.PI * (i / n);
  36174. let u1 = 2 * Math.PI * (i + 1) / n;
  36175. let p0 = new Vector3(
  36176. Math.cos(u0),
  36177. Math.sin(u0),
  36178. 0
  36179. );
  36180. let p1 = new Vector3(
  36181. Math.cos(u1),
  36182. Math.sin(u1),
  36183. 0
  36184. );
  36185. coordinates.push(
  36186. ...p0.toArray(),
  36187. ...p1.toArray(),
  36188. );
  36189. }
  36190. const geometry = new LineGeometry();
  36191. geometry.setPositions(coordinates);
  36192. const material = new LineMaterial({
  36193. color: 0xff0000,
  36194. dashSize: 5,
  36195. gapSize: 2,
  36196. linewidth: 2,
  36197. resolution: new Vector2(1000, 1000),
  36198. });
  36199. material.depthTest = false;
  36200. const circleLine = new Line2(geometry, material);
  36201. circleLine.visible = false;
  36202. circleLine.computeLineDistances();
  36203. return circleLine;
  36204. }
  36205. function createCircleCenter(){
  36206. const sg = new SphereGeometry(1, 32, 32);
  36207. const sm = new MeshNormalMaterial();
  36208. const circleCenter = new Mesh(sg, sm);
  36209. circleCenter.visible = false;
  36210. return circleCenter;
  36211. }
  36212. function createLine(){
  36213. const geometry = new LineGeometry();
  36214. geometry.setPositions([
  36215. 0, 0, 0,
  36216. 0, 0, 0,
  36217. ]);
  36218. const material = new LineMaterial({
  36219. color: 0xff0000,
  36220. linewidth: 2,
  36221. resolution: new Vector2(1000, 1000),
  36222. gapSize: 1,
  36223. dashed: true,
  36224. });
  36225. material.depthTest = false;
  36226. const line = new Line2(geometry, material);
  36227. return line;
  36228. }
  36229. function createCircle(){
  36230. const coordinates = [];
  36231. let n = 128;
  36232. for(let i = 0; i <= n; i++){
  36233. let u0 = 2 * Math.PI * (i / n);
  36234. let u1 = 2 * Math.PI * (i + 1) / n;
  36235. let p0 = new Vector3(
  36236. Math.cos(u0),
  36237. Math.sin(u0),
  36238. 0
  36239. );
  36240. let p1 = new Vector3(
  36241. Math.cos(u1),
  36242. Math.sin(u1),
  36243. 0
  36244. );
  36245. coordinates.push(
  36246. ...p0.toArray(),
  36247. ...p1.toArray(),
  36248. );
  36249. }
  36250. const geometry = new LineGeometry();
  36251. geometry.setPositions(coordinates);
  36252. const material = new LineMaterial({
  36253. color: 0xff0000,
  36254. dashSize: 5,
  36255. gapSize: 2,
  36256. linewidth: 2,
  36257. resolution: new Vector2(1000, 1000),
  36258. });
  36259. material.depthTest = false;
  36260. const line = new Line2(geometry, material);
  36261. line.computeLineDistances();
  36262. return line;
  36263. }
  36264. function createAzimuth(){
  36265. const azimuth = {
  36266. label: null,
  36267. center: null,
  36268. target: null,
  36269. north: null,
  36270. centerToNorth: null,
  36271. centerToTarget: null,
  36272. centerToTargetground: null,
  36273. targetgroundToTarget: null,
  36274. circle: null,
  36275. node: null,
  36276. };
  36277. const sg = new SphereGeometry(1, 32, 32);
  36278. const sm = new MeshNormalMaterial();
  36279. {
  36280. const label = new TextSprite$1("");
  36281. label.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  36282. label.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  36283. label.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  36284. label.fontsize = 16;
  36285. label.material.depthTest = false;
  36286. label.material.opacity = 1;
  36287. azimuth.label = label;
  36288. }
  36289. azimuth.center = new Mesh(sg, sm);
  36290. azimuth.target = new Mesh(sg, sm);
  36291. azimuth.north = new Mesh(sg, sm);
  36292. azimuth.centerToNorth = createLine();
  36293. azimuth.centerToTarget = createLine();
  36294. azimuth.centerToTargetground = createLine();
  36295. azimuth.targetgroundToTarget = createLine();
  36296. azimuth.circle = createCircle();
  36297. azimuth.node = new Object3D();
  36298. azimuth.node.add(
  36299. azimuth.centerToNorth,
  36300. azimuth.centerToTarget,
  36301. azimuth.centerToTargetground,
  36302. azimuth.targetgroundToTarget,
  36303. azimuth.circle,
  36304. azimuth.label,
  36305. azimuth.center,
  36306. azimuth.target,
  36307. azimuth.north,
  36308. );
  36309. return azimuth;
  36310. }
  36311. class Measure extends Object3D {
  36312. constructor () {
  36313. super();
  36314. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  36315. this.name = 'Measure_' + this.constructor.counter;
  36316. this.points = [];
  36317. this._showDistances = true;
  36318. this._showCoordinates = false;
  36319. this._showArea = false;
  36320. this._closed = true;
  36321. this._showAngles = false;
  36322. this._showCircle = false;
  36323. this._showHeight = false;
  36324. this._showEdges = true;
  36325. this._showAzimuth = false;
  36326. this.maxMarkers = Number.MAX_SAFE_INTEGER;
  36327. this.sphereGeometry = new SphereGeometry(0.4, 10, 10);
  36328. this.color = new Color(0xff0000);
  36329. this.spheres = [];
  36330. this.edges = [];
  36331. this.sphereLabels = [];
  36332. this.edgeLabels = [];
  36333. this.angleLabels = [];
  36334. this.coordinateLabels = [];
  36335. this.heightEdge = createHeightLine();
  36336. this.heightLabel = createHeightLabel();
  36337. this.areaLabel = createAreaLabel();
  36338. this.circleRadiusLabel = createCircleRadiusLabel();
  36339. this.circleRadiusLine = createCircleRadiusLine();
  36340. this.circleLine = createCircleLine();
  36341. this.circleCenter = createCircleCenter();
  36342. this.azimuth = createAzimuth();
  36343. this.add(this.heightEdge);
  36344. this.add(this.heightLabel);
  36345. this.add(this.areaLabel);
  36346. this.add(this.circleRadiusLabel);
  36347. this.add(this.circleRadiusLine);
  36348. this.add(this.circleLine);
  36349. this.add(this.circleCenter);
  36350. this.add(this.azimuth.node);
  36351. }
  36352. createSphereMaterial () {
  36353. let sphereMaterial = new MeshLambertMaterial({
  36354. //shading: THREE.SmoothShading,
  36355. color: this.color,
  36356. depthTest: false,
  36357. depthWrite: false}
  36358. );
  36359. return sphereMaterial;
  36360. };
  36361. addMarker (point) {
  36362. if (point.x != null) {
  36363. point = {position: point};
  36364. }else if(point instanceof Array){
  36365. point = {position: new Vector3(...point)};
  36366. }
  36367. this.points.push(point);
  36368. // sphere
  36369. let sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial());
  36370. this.add(sphere);
  36371. this.spheres.push(sphere);
  36372. { // edges
  36373. let lineGeometry = new LineGeometry();
  36374. lineGeometry.setPositions( [
  36375. 0, 0, 0,
  36376. 0, 0, 0,
  36377. ]);
  36378. let lineMaterial = new LineMaterial({
  36379. color: 0xff0000,
  36380. linewidth: 2,
  36381. resolution: new Vector2(1000, 1000),
  36382. });
  36383. lineMaterial.depthTest = false;
  36384. let edge = new Line2(lineGeometry, lineMaterial);
  36385. edge.visible = true;
  36386. this.add(edge);
  36387. this.edges.push(edge);
  36388. }
  36389. { // edge labels
  36390. let edgeLabel = new TextSprite$1();
  36391. edgeLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  36392. edgeLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  36393. edgeLabel.material.depthTest = false;
  36394. edgeLabel.visible = false;
  36395. edgeLabel.fontsize = 16;
  36396. this.edgeLabels.push(edgeLabel);
  36397. this.add(edgeLabel);
  36398. }
  36399. { // angle labels
  36400. let angleLabel = new TextSprite$1();
  36401. angleLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  36402. angleLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  36403. angleLabel.fontsize = 16;
  36404. angleLabel.material.depthTest = false;
  36405. angleLabel.material.opacity = 1;
  36406. angleLabel.visible = false;
  36407. this.angleLabels.push(angleLabel);
  36408. this.add(angleLabel);
  36409. }
  36410. { // coordinate labels
  36411. let coordinateLabel = new TextSprite$1();
  36412. coordinateLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  36413. coordinateLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  36414. coordinateLabel.fontsize = 16;
  36415. coordinateLabel.material.depthTest = false;
  36416. coordinateLabel.material.opacity = 1;
  36417. coordinateLabel.visible = false;
  36418. this.coordinateLabels.push(coordinateLabel);
  36419. this.add(coordinateLabel);
  36420. }
  36421. { // Event Listeners
  36422. let drag = (e) => {
  36423. let I = Utils.getMousePointCloudIntersection(
  36424. e.drag.end,
  36425. e.viewer.scene.getActiveCamera(),
  36426. e.viewer,
  36427. e.viewer.scene.pointclouds,
  36428. {pickClipped: true});
  36429. if (I) {
  36430. let i = this.spheres.indexOf(e.drag.object);
  36431. if (i !== -1) {
  36432. let point = this.points[i];
  36433. // loop through current keys and cleanup ones that will be orphaned
  36434. for (let key of Object.keys(point)) {
  36435. if (!I.point[key]) {
  36436. delete point[key];
  36437. }
  36438. }
  36439. for (let key of Object.keys(I.point).filter(e => e !== 'position')) {
  36440. point[key] = I.point[key];
  36441. }
  36442. this.setPosition(i, I.location);
  36443. }
  36444. }
  36445. };
  36446. let drop = e => {
  36447. let i = this.spheres.indexOf(e.drag.object);
  36448. if (i !== -1) {
  36449. this.dispatchEvent({
  36450. 'type': 'marker_dropped',
  36451. 'measurement': this,
  36452. 'index': i
  36453. });
  36454. }
  36455. };
  36456. let mouseover = (e) => e.object.material.emissive.setHex(0x888888);
  36457. let mouseleave = (e) => e.object.material.emissive.setHex(0x000000);
  36458. sphere.addEventListener('drag', drag);
  36459. sphere.addEventListener('drop', drop);
  36460. sphere.addEventListener('mouseover', mouseover);
  36461. sphere.addEventListener('mouseleave', mouseleave);
  36462. }
  36463. let event = {
  36464. type: 'marker_added',
  36465. measurement: this,
  36466. sphere: sphere
  36467. };
  36468. this.dispatchEvent(event);
  36469. this.setMarker(this.points.length - 1, point);
  36470. };
  36471. removeMarker (index) {
  36472. this.points.splice(index, 1);
  36473. this.remove(this.spheres[index]);
  36474. let edgeIndex = (index === 0) ? 0 : (index - 1);
  36475. this.remove(this.edges[edgeIndex]);
  36476. this.edges.splice(edgeIndex, 1);
  36477. this.remove(this.edgeLabels[edgeIndex]);
  36478. this.edgeLabels.splice(edgeIndex, 1);
  36479. this.coordinateLabels.splice(index, 1);
  36480. this.remove(this.angleLabels[index]);
  36481. this.angleLabels.splice(index, 1);
  36482. this.spheres.splice(index, 1);
  36483. this.update();
  36484. this.dispatchEvent({type: 'marker_removed', measurement: this});
  36485. };
  36486. setMarker (index, point) {
  36487. this.points[index] = point;
  36488. let event = {
  36489. type: 'marker_moved',
  36490. measure: this,
  36491. index: index,
  36492. position: point.position.clone()
  36493. };
  36494. this.dispatchEvent(event);
  36495. this.update();
  36496. }
  36497. setPosition (index, position) {
  36498. let point = this.points[index];
  36499. point.position.copy(position);
  36500. let event = {
  36501. type: 'marker_moved',
  36502. measure: this,
  36503. index: index,
  36504. position: position.clone()
  36505. };
  36506. this.dispatchEvent(event);
  36507. this.update();
  36508. };
  36509. getArea () {
  36510. let area = 0;
  36511. let j = this.points.length - 1;
  36512. for (let i = 0; i < this.points.length; i++) {
  36513. let p1 = this.points[i].position;
  36514. let p2 = this.points[j].position;
  36515. area += (p2.x + p1.x) * (p1.y - p2.y);
  36516. j = i;
  36517. }
  36518. return Math.abs(area / 2);
  36519. };
  36520. getTotalDistance () {
  36521. if (this.points.length === 0) {
  36522. return 0;
  36523. }
  36524. let distance = 0;
  36525. for (let i = 1; i < this.points.length; i++) {
  36526. let prev = this.points[i - 1].position;
  36527. let curr = this.points[i].position;
  36528. let d = prev.distanceTo(curr);
  36529. distance += d;
  36530. }
  36531. if (this.closed && this.points.length > 1) {
  36532. let first = this.points[0].position;
  36533. let last = this.points[this.points.length - 1].position;
  36534. let d = last.distanceTo(first);
  36535. distance += d;
  36536. }
  36537. return distance;
  36538. }
  36539. getAngleBetweenLines (cornerPoint, point1, point2) {
  36540. let v1 = new Vector3().subVectors(point1.position, cornerPoint.position);
  36541. let v2 = new Vector3().subVectors(point2.position, cornerPoint.position);
  36542. // avoid the error printed by threejs if denominator is 0
  36543. const denominator = Math.sqrt( v1.lengthSq() * v2.lengthSq() );
  36544. if(denominator === 0){
  36545. return 0;
  36546. }else {
  36547. return v1.angleTo(v2);
  36548. }
  36549. };
  36550. getAngle (index) {
  36551. if (this.points.length < 3 || index >= this.points.length) {
  36552. return 0;
  36553. }
  36554. let previous = (index === 0) ? this.points[this.points.length - 1] : this.points[index - 1];
  36555. let point = this.points[index];
  36556. let next = this.points[(index + 1) % (this.points.length)];
  36557. return this.getAngleBetweenLines(point, previous, next);
  36558. }
  36559. // updateAzimuth(){
  36560. // // if(this.points.length !== 2){
  36561. // // return;
  36562. // // }
  36563. // // const azimuth = this.azimuth;
  36564. // // const [p0, p1] = this.points;
  36565. // // const r = p0.position.distanceTo(p1.position);
  36566. // }
  36567. update () {
  36568. if (this.points.length === 0) {
  36569. return;
  36570. } else if (this.points.length === 1) {
  36571. let point = this.points[0];
  36572. let position = point.position;
  36573. this.spheres[0].position.copy(position);
  36574. { // coordinate labels
  36575. let coordinateLabel = this.coordinateLabels[0];
  36576. let msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / ");
  36577. coordinateLabel.setText(msg);
  36578. coordinateLabel.visible = this.showCoordinates;
  36579. }
  36580. return;
  36581. }
  36582. let lastIndex = this.points.length - 1;
  36583. let centroid = new Vector3();
  36584. for (let i = 0; i <= lastIndex; i++) {
  36585. let point = this.points[i];
  36586. centroid.add(point.position);
  36587. }
  36588. centroid.divideScalar(this.points.length);
  36589. for (let i = 0; i <= lastIndex; i++) {
  36590. let index = i;
  36591. let nextIndex = (i + 1 > lastIndex) ? 0 : i + 1;
  36592. let previousIndex = (i === 0) ? lastIndex : i - 1;
  36593. let point = this.points[index];
  36594. let nextPoint = this.points[nextIndex];
  36595. let previousPoint = this.points[previousIndex];
  36596. let sphere = this.spheres[index];
  36597. // spheres
  36598. sphere.position.copy(point.position);
  36599. sphere.material.color = this.color;
  36600. { // edges
  36601. let edge = this.edges[index];
  36602. edge.material.color = this.color;
  36603. edge.position.copy(point.position);
  36604. edge.geometry.setPositions([
  36605. 0, 0, 0,
  36606. ...nextPoint.position.clone().sub(point.position).toArray(),
  36607. ]);
  36608. edge.geometry.verticesNeedUpdate = true;
  36609. edge.geometry.computeBoundingSphere();
  36610. edge.computeLineDistances();
  36611. edge.visible = index < lastIndex || this.closed;
  36612. if(!this.showEdges){
  36613. edge.visible = false;
  36614. }
  36615. }
  36616. { // edge labels
  36617. let edgeLabel = this.edgeLabels[i];
  36618. let center = new Vector3().add(point.position);
  36619. center.add(nextPoint.position);
  36620. center = center.multiplyScalar(0.5);
  36621. let distance = point.position.distanceTo(nextPoint.position);
  36622. edgeLabel.position.copy(center);
  36623. let suffix = "";
  36624. if(this.lengthUnit != null && this.lengthUnitDisplay != null){
  36625. distance = distance / this.lengthUnit.unitspermeter * this.lengthUnitDisplay.unitspermeter; //convert to meters then to the display unit
  36626. suffix = this.lengthUnitDisplay.code;
  36627. }
  36628. let txtLength = Utils.addCommas(distance.toFixed(2));
  36629. edgeLabel.setText(`${txtLength} ${suffix}`);
  36630. edgeLabel.visible = this.showDistances && (index < lastIndex || this.closed) && this.points.length >= 2 && distance > 0;
  36631. }
  36632. { // angle labels
  36633. let angleLabel = this.angleLabels[i];
  36634. let angle = this.getAngleBetweenLines(point, previousPoint, nextPoint);
  36635. let dir = nextPoint.position.clone().sub(previousPoint.position);
  36636. dir.multiplyScalar(0.5);
  36637. dir = previousPoint.position.clone().add(dir).sub(point.position).normalize();
  36638. let dist = Math.min(point.position.distanceTo(previousPoint.position), point.position.distanceTo(nextPoint.position));
  36639. dist = dist / 9;
  36640. let labelPos = point.position.clone().add(dir.multiplyScalar(dist));
  36641. angleLabel.position.copy(labelPos);
  36642. let msg = Utils.addCommas((angle * (180.0 / Math.PI)).toFixed(1)) + '\u00B0';
  36643. angleLabel.setText(msg);
  36644. angleLabel.visible = this.showAngles && (index < lastIndex || this.closed) && this.points.length >= 3 && angle > 0;
  36645. }
  36646. }
  36647. { // update height stuff
  36648. let heightEdge = this.heightEdge;
  36649. heightEdge.visible = this.showHeight;
  36650. this.heightLabel.visible = this.showHeight;
  36651. if (this.showHeight) {
  36652. let sorted = this.points.slice().sort((a, b) => a.position.z - b.position.z);
  36653. let lowPoint = sorted[0].position.clone();
  36654. let highPoint = sorted[sorted.length - 1].position.clone();
  36655. let min = lowPoint.z;
  36656. let max = highPoint.z;
  36657. let height = max - min;
  36658. let start = new Vector3(highPoint.x, highPoint.y, min);
  36659. let end = new Vector3(highPoint.x, highPoint.y, max);
  36660. heightEdge.position.copy(lowPoint);
  36661. heightEdge.geometry.setPositions([
  36662. 0, 0, 0,
  36663. ...start.clone().sub(lowPoint).toArray(),
  36664. ...start.clone().sub(lowPoint).toArray(),
  36665. ...end.clone().sub(lowPoint).toArray(),
  36666. ]);
  36667. heightEdge.geometry.verticesNeedUpdate = true;
  36668. // heightEdge.geometry.computeLineDistances();
  36669. // heightEdge.geometry.lineDistancesNeedUpdate = true;
  36670. heightEdge.geometry.computeBoundingSphere();
  36671. heightEdge.computeLineDistances();
  36672. // heightEdge.material.dashSize = height / 40;
  36673. // heightEdge.material.gapSize = height / 40;
  36674. let heightLabelPosition = start.clone().add(end).multiplyScalar(0.5);
  36675. this.heightLabel.position.copy(heightLabelPosition);
  36676. let suffix = "";
  36677. if(this.lengthUnit != null && this.lengthUnitDisplay != null){
  36678. height = height / this.lengthUnit.unitspermeter * this.lengthUnitDisplay.unitspermeter; //convert to meters then to the display unit
  36679. suffix = this.lengthUnitDisplay.code;
  36680. }
  36681. let txtHeight = Utils.addCommas(height.toFixed(2));
  36682. let msg = `${txtHeight} ${suffix}`;
  36683. this.heightLabel.setText(msg);
  36684. }
  36685. }
  36686. { // update circle stuff
  36687. const circleRadiusLabel = this.circleRadiusLabel;
  36688. const circleRadiusLine = this.circleRadiusLine;
  36689. const circleLine = this.circleLine;
  36690. const circleCenter = this.circleCenter;
  36691. const circleOkay = this.points.length === 3;
  36692. circleRadiusLabel.visible = this.showCircle && circleOkay;
  36693. circleRadiusLine.visible = this.showCircle && circleOkay;
  36694. circleLine.visible = this.showCircle && circleOkay;
  36695. circleCenter.visible = this.showCircle && circleOkay;
  36696. if(this.showCircle && circleOkay){
  36697. const A = this.points[0].position;
  36698. const B = this.points[1].position;
  36699. const C = this.points[2].position;
  36700. const AB = B.clone().sub(A);
  36701. const AC = C.clone().sub(A);
  36702. const N = AC.clone().cross(AB).normalize();
  36703. const center = Potree.Utils.computeCircleCenter(A, B, C);
  36704. const radius = center.distanceTo(A);
  36705. const scale = radius / 20;
  36706. circleCenter.position.copy(center);
  36707. circleCenter.scale.set(scale, scale, scale);
  36708. //circleRadiusLine.geometry.vertices[0].set(0, 0, 0);
  36709. //circleRadiusLine.geometry.vertices[1].copy(B.clone().sub(center));
  36710. circleRadiusLine.geometry.setPositions( [
  36711. 0, 0, 0,
  36712. ...B.clone().sub(center).toArray()
  36713. ] );
  36714. circleRadiusLine.geometry.verticesNeedUpdate = true;
  36715. circleRadiusLine.geometry.computeBoundingSphere();
  36716. circleRadiusLine.position.copy(center);
  36717. circleRadiusLine.computeLineDistances();
  36718. const target = center.clone().add(N);
  36719. circleLine.position.copy(center);
  36720. circleLine.scale.set(radius, radius, radius);
  36721. circleLine.lookAt(target);
  36722. circleRadiusLabel.visible = true;
  36723. circleRadiusLabel.position.copy(center.clone().add(B).multiplyScalar(0.5));
  36724. circleRadiusLabel.setText(`${radius.toFixed(3)}`);
  36725. }
  36726. }
  36727. { // update area label
  36728. this.areaLabel.position.copy(centroid);
  36729. this.areaLabel.visible = this.showArea && this.points.length >= 3;
  36730. let area = this.getArea();
  36731. let suffix = "";
  36732. if(this.lengthUnit != null && this.lengthUnitDisplay != null){
  36733. area = area / Math.pow(this.lengthUnit.unitspermeter, 2) * Math.pow(this.lengthUnitDisplay.unitspermeter, 2); //convert to square meters then to the square display unit
  36734. suffix = this.lengthUnitDisplay.code;
  36735. }
  36736. let txtArea = Utils.addCommas(area.toFixed(1));
  36737. let msg = `${txtArea} ${suffix}\u00B2`;
  36738. this.areaLabel.setText(msg);
  36739. }
  36740. // this.updateAzimuth();
  36741. };
  36742. raycast (raycaster, intersects) {
  36743. for (let i = 0; i < this.points.length; i++) {
  36744. let sphere = this.spheres[i];
  36745. sphere.raycast(raycaster, intersects);
  36746. }
  36747. // recalculate distances because they are not necessarely correct
  36748. // for scaled objects.
  36749. // see https://github.com/mrdoob/three.js/issues/5827
  36750. // TODO: remove this once the bug has been fixed
  36751. for (let i = 0; i < intersects.length; i++) {
  36752. let I = intersects[i];
  36753. I.distance = raycaster.ray.origin.distanceTo(I.point);
  36754. }
  36755. intersects.sort(function (a, b) { return a.distance - b.distance; });
  36756. };
  36757. get showCoordinates () {
  36758. return this._showCoordinates;
  36759. }
  36760. set showCoordinates (value) {
  36761. this._showCoordinates = value;
  36762. this.update();
  36763. }
  36764. get showAngles () {
  36765. return this._showAngles;
  36766. }
  36767. set showAngles (value) {
  36768. this._showAngles = value;
  36769. this.update();
  36770. }
  36771. get showCircle () {
  36772. return this._showCircle;
  36773. }
  36774. set showCircle (value) {
  36775. this._showCircle = value;
  36776. this.update();
  36777. }
  36778. get showAzimuth(){
  36779. return this._showAzimuth;
  36780. }
  36781. set showAzimuth(value){
  36782. this._showAzimuth = value;
  36783. this.update();
  36784. }
  36785. get showEdges () {
  36786. return this._showEdges;
  36787. }
  36788. set showEdges (value) {
  36789. this._showEdges = value;
  36790. this.update();
  36791. }
  36792. get showHeight () {
  36793. return this._showHeight;
  36794. }
  36795. set showHeight (value) {
  36796. this._showHeight = value;
  36797. this.update();
  36798. }
  36799. get showArea () {
  36800. return this._showArea;
  36801. }
  36802. set showArea (value) {
  36803. this._showArea = value;
  36804. this.update();
  36805. }
  36806. get closed () {
  36807. return this._closed;
  36808. }
  36809. set closed (value) {
  36810. this._closed = value;
  36811. this.update();
  36812. }
  36813. get showDistances () {
  36814. return this._showDistances;
  36815. }
  36816. set showDistances (value) {
  36817. this._showDistances = value;
  36818. this.update();
  36819. }
  36820. }
  36821. class PolygonClipVolume extends Object3D{
  36822. constructor(camera){
  36823. super();
  36824. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  36825. this.name = "polygon_clip_volume_" + this.constructor.counter;
  36826. this.camera = camera.clone();
  36827. this.camera.rotation.set(...camera.rotation.toArray()); // [r85] workaround because camera.clone() doesn't work on rotation
  36828. this.camera.rotation.order = camera.rotation.order;
  36829. this.camera.updateMatrixWorld();
  36830. this.camera.updateProjectionMatrix();
  36831. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  36832. this.viewMatrix = this.camera.matrixWorldInverse.clone();
  36833. this.projMatrix = this.camera.projectionMatrix.clone();
  36834. // projected markers
  36835. this.markers = [];
  36836. this.initialized = false;
  36837. }
  36838. addMarker() {
  36839. let marker = new Mesh();
  36840. let cancel;
  36841. let drag = e => {
  36842. let size = e.viewer.renderer.getSize(new Vector2());
  36843. let projectedPos = new Vector3(
  36844. 2.0 * (e.drag.end.x / size.width) - 1.0,
  36845. -2.0 * (e.drag.end.y / size.height) + 1.0,
  36846. 0
  36847. );
  36848. marker.position.copy(projectedPos);
  36849. };
  36850. let drop = e => {
  36851. cancel();
  36852. };
  36853. cancel = e => {
  36854. marker.removeEventListener("drag", drag);
  36855. marker.removeEventListener("drop", drop);
  36856. };
  36857. marker.addEventListener("drag", drag);
  36858. marker.addEventListener("drop", drop);
  36859. this.markers.push(marker);
  36860. }
  36861. removeLastMarker() {
  36862. if(this.markers.length > 0) {
  36863. this.markers.splice(this.markers.length - 1, 1);
  36864. }
  36865. }
  36866. };
  36867. class Utils {
  36868. static async loadShapefileFeatures (file, callback) {
  36869. let features = [];
  36870. let handleFinish = () => {
  36871. callback(features);
  36872. };
  36873. let source = await shapefile.open(file);
  36874. while(true){
  36875. let result = await source.read();
  36876. if (result.done) {
  36877. handleFinish();
  36878. break;
  36879. }
  36880. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  36881. features.push(result.value);
  36882. }
  36883. }
  36884. }
  36885. static toString (value) {
  36886. if (value.x != null) {
  36887. return value.x.toFixed(2) + ', ' + value.y.toFixed(2) + ', ' + value.z.toFixed(2);
  36888. } else {
  36889. return '' + value + '';
  36890. }
  36891. }
  36892. static normalizeURL (url) {
  36893. let u = new URL(url);
  36894. return u.protocol + '//' + u.hostname + u.pathname.replace(/\/+/g, '/');
  36895. };
  36896. static pathExists (url) {
  36897. let req = XHRFactory.createXMLHttpRequest();
  36898. req.open('GET', url, false);
  36899. req.send(null);
  36900. if (req.status !== 200) {
  36901. return false;
  36902. }
  36903. return true;
  36904. };
  36905. static debugSphere(parent, position, scale, color){
  36906. let geometry = new SphereGeometry(1, 8, 8);
  36907. let material;
  36908. if(color !== undefined){
  36909. material = new MeshBasicMaterial({color: color});
  36910. }else {
  36911. material = new MeshNormalMaterial();
  36912. }
  36913. let sphere = new Mesh(geometry, material);
  36914. sphere.position.copy(position);
  36915. sphere.scale.set(scale, scale, scale);
  36916. parent.add(sphere);
  36917. return sphere;
  36918. }
  36919. static debugLine(parent, start, end, color){
  36920. let material = new LineBasicMaterial({ color: color });
  36921. let geometry = new Geometry();
  36922. const p1 = new Vector3(0, 0, 0);
  36923. const p2 = end.clone().sub(start);
  36924. geometry.vertices.push(p1, p2);
  36925. let tl = new Line( geometry, material );
  36926. tl.position.copy(start);
  36927. parent.add(tl);
  36928. let line = {
  36929. node: tl,
  36930. set: (start, end) => {
  36931. geometry.vertices[0].copy(start);
  36932. geometry.vertices[1].copy(end);
  36933. geometry.verticesNeedUpdate = true;
  36934. },
  36935. };
  36936. return line;
  36937. }
  36938. static debugCircle(parent, center, radius, normal, color){
  36939. let material = new LineBasicMaterial({ color: color });
  36940. let geometry = new Geometry();
  36941. let n = 32;
  36942. for(let i = 0; i <= n; i++){
  36943. let u0 = 2 * Math.PI * (i / n);
  36944. let u1 = 2 * Math.PI * (i + 1) / n;
  36945. let p0 = new Vector3(
  36946. Math.cos(u0),
  36947. Math.sin(u0),
  36948. 0
  36949. );
  36950. let p1 = new Vector3(
  36951. Math.cos(u1),
  36952. Math.sin(u1),
  36953. 0
  36954. );
  36955. geometry.vertices.push(p0, p1);
  36956. }
  36957. let tl = new Line( geometry, material );
  36958. tl.position.copy(center);
  36959. tl.scale.set(radius, radius, radius);
  36960. parent.add(tl);
  36961. }
  36962. static debugBox(parent, box, transform = new Matrix4(), color = 0xFFFF00){
  36963. let vertices = [
  36964. [box.min.x, box.min.y, box.min.z],
  36965. [box.min.x, box.min.y, box.max.z],
  36966. [box.min.x, box.max.y, box.min.z],
  36967. [box.min.x, box.max.y, box.max.z],
  36968. [box.max.x, box.min.y, box.min.z],
  36969. [box.max.x, box.min.y, box.max.z],
  36970. [box.max.x, box.max.y, box.min.z],
  36971. [box.max.x, box.max.y, box.max.z],
  36972. ].map(v => new Vector3(...v));
  36973. let edges = [
  36974. [0, 4], [4, 5], [5, 1], [1, 0],
  36975. [2, 6], [6, 7], [7, 3], [3, 2],
  36976. [0, 2], [4, 6], [5, 7], [1, 3]
  36977. ];
  36978. let center = box.getCenter(new Vector3());
  36979. let centroids = [
  36980. {position: [box.min.x, center.y, center.z], color: 0xFF0000},
  36981. {position: [box.max.x, center.y, center.z], color: 0x880000},
  36982. {position: [center.x, box.min.y, center.z], color: 0x00FF00},
  36983. {position: [center.x, box.max.y, center.z], color: 0x008800},
  36984. {position: [center.x, center.y, box.min.z], color: 0x0000FF},
  36985. {position: [center.x, center.y, box.max.z], color: 0x000088},
  36986. ];
  36987. for(let vertex of vertices){
  36988. let pos = vertex.clone().applyMatrix4(transform);
  36989. Utils.debugSphere(parent, pos, 0.1, 0xFF0000);
  36990. }
  36991. for(let edge of edges){
  36992. let start = vertices[edge[0]].clone().applyMatrix4(transform);
  36993. let end = vertices[edge[1]].clone().applyMatrix4(transform);
  36994. Utils.debugLine(parent, start, end, color);
  36995. }
  36996. for(let centroid of centroids){
  36997. let pos = new Vector3(...centroid.position).applyMatrix4(transform);
  36998. Utils.debugSphere(parent, pos, 0.1, centroid.color);
  36999. }
  37000. }
  37001. static debugPlane(parent, plane, size = 1, color = 0x0000FF){
  37002. let planehelper = new PlaneHelper(plane, size, color);
  37003. parent.add(planehelper);
  37004. }
  37005. /**
  37006. * adapted from mhluska at https://github.com/mrdoob/three.js/issues/1561
  37007. */
  37008. static computeTransformedBoundingBox (box, transform) {
  37009. let vertices = [
  37010. new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform),
  37011. new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform),
  37012. new Vector3(box.max.x, box.min.y, box.min.z).applyMatrix4(transform),
  37013. new Vector3(box.min.x, box.max.y, box.min.z).applyMatrix4(transform),
  37014. new Vector3(box.min.x, box.min.y, box.max.z).applyMatrix4(transform),
  37015. new Vector3(box.min.x, box.max.y, box.max.z).applyMatrix4(transform),
  37016. new Vector3(box.max.x, box.max.y, box.min.z).applyMatrix4(transform),
  37017. new Vector3(box.max.x, box.min.y, box.max.z).applyMatrix4(transform),
  37018. new Vector3(box.max.x, box.max.y, box.max.z).applyMatrix4(transform)
  37019. ];
  37020. let boundingBox = new Box3();
  37021. boundingBox.setFromPoints(vertices);
  37022. return boundingBox;
  37023. };//感觉就是bound.applyMatrix4(transform)
  37024. /**
  37025. * add separators to large numbers
  37026. *
  37027. * @param nStr
  37028. * @returns
  37029. */
  37030. static addCommas (nStr) {
  37031. nStr += '';
  37032. let x = nStr.split('.');
  37033. let x1 = x[0];
  37034. let x2 = x.length > 1 ? '.' + x[1] : '';
  37035. let rgx = /(\d+)(\d{3})/;
  37036. while (rgx.test(x1)) {
  37037. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  37038. }
  37039. return x1 + x2;
  37040. };
  37041. static removeCommas (str) {
  37042. return str.replace(/,/g, '');
  37043. }
  37044. /**
  37045. * create worker from a string
  37046. *
  37047. * code from http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
  37048. */
  37049. static createWorker (code) {
  37050. let blob = new Blob([code], {type: 'application/javascript'});
  37051. let worker = new Worker(URL.createObjectURL(blob));
  37052. return worker;
  37053. };
  37054. static moveTo(scene, endPosition, endTarget){
  37055. let view = scene.view;
  37056. let camera = scene.getActiveCamera();
  37057. let animationDuration = 500;
  37058. let easing = TWEEN.Easing.Quartic.Out;
  37059. { // animate camera position
  37060. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  37061. tween.easing(easing);
  37062. tween.start();
  37063. }
  37064. { // animate camera target
  37065. let camTargetDistance = camera.position.distanceTo(endTarget);
  37066. let target = new Vector3().addVectors(
  37067. camera.position,
  37068. camera.getWorldDirection(new Vector3()).clone().multiplyScalar(camTargetDistance)
  37069. );
  37070. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  37071. tween.easing(easing);
  37072. tween.onUpdate(() => {
  37073. view.lookAt(target);
  37074. });
  37075. tween.onComplete(() => {
  37076. view.lookAt(target);
  37077. });
  37078. tween.start();
  37079. }
  37080. }
  37081. static loadSkybox (path) {
  37082. let parent = new Object3D("skybox_root");
  37083. let camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
  37084. camera.up.set(0, 0, 1);
  37085. let scene = new Scene();
  37086. let format = '.jpg';
  37087. let urls = [
  37088. path + 'px' + format, path + 'nx' + format,
  37089. path + 'py' + format, path + 'ny' + format,
  37090. path + 'pz' + format, path + 'nz' + format
  37091. ];
  37092. let materialArray = [];
  37093. {
  37094. for (let i = 0; i < 6; i++) {
  37095. let material = new MeshBasicMaterial({
  37096. map: null,
  37097. side: BackSide,
  37098. depthTest: false,
  37099. depthWrite: false,
  37100. color: 0x424556
  37101. });
  37102. materialArray.push(material);
  37103. let loader = new TextureLoader();
  37104. loader.load(urls[i],
  37105. function loaded (texture) {
  37106. material.map = texture;
  37107. material.needsUpdate = true;
  37108. material.color.setHex(0xffffff);
  37109. }, function progress (xhr) {
  37110. // console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
  37111. }, function error (xhr) {
  37112. console.log('An error happened', xhr);
  37113. }
  37114. );
  37115. }
  37116. }
  37117. let skyGeometry = new BoxGeometry(700, 700, 700);
  37118. let skybox = new Mesh(skyGeometry, materialArray);
  37119. scene.add(skybox);
  37120. scene.traverse(n => n.frustumCulled = false);
  37121. // z up
  37122. scene.rotation.x = Math.PI / 2;
  37123. parent.children.push(camera);
  37124. camera.parent = parent;
  37125. return {camera, scene, parent};
  37126. };
  37127. static createGrid (width, length, spacing, color) {
  37128. let material = new LineBasicMaterial({
  37129. color: color || 0x888888
  37130. });
  37131. let geometry = new Geometry();
  37132. for (let i = 0; i <= length; i++) {
  37133. geometry.vertices.push(new Vector3(-(spacing * width) / 2, i * spacing - (spacing * length) / 2, 0));
  37134. geometry.vertices.push(new Vector3(+(spacing * width) / 2, i * spacing - (spacing * length) / 2, 0));
  37135. }
  37136. for (let i = 0; i <= width; i++) {
  37137. geometry.vertices.push(new Vector3(i * spacing - (spacing * width) / 2, -(spacing * length) / 2, 0));
  37138. geometry.vertices.push(new Vector3(i * spacing - (spacing * width) / 2, +(spacing * length) / 2, 0));
  37139. }
  37140. let line = new LineSegments(geometry, material, LinePieces);
  37141. line.receiveShadow = true;
  37142. return line;
  37143. }
  37144. static createBackgroundTexture (width, height) {
  37145. function gauss (x, y) {
  37146. return (1 / (2 * Math.PI)) * Math.exp(-(x * x + y * y) / 2);
  37147. };
  37148. // map.magFilter = THREE.NearestFilter;
  37149. let size = width * height;
  37150. let data = new Uint8Array(3 * size);
  37151. let chroma = [1, 1.5, 1.7];
  37152. let max = gauss(0, 0);
  37153. for (let x = 0; x < width; x++) {
  37154. for (let y = 0; y < height; y++) {
  37155. let u = 2 * (x / width) - 1;
  37156. let v = 2 * (y / height) - 1;
  37157. let i = x + width * y;
  37158. let d = gauss(2 * u, 2 * v) / max;
  37159. let r = (Math.random() + Math.random() + Math.random()) / 3;
  37160. r = (d * 0.5 + 0.5) * r * 0.03;
  37161. r = r * 0.4;
  37162. // d = Math.pow(d, 0.6);
  37163. data[3 * i + 0] = 255 * (d / 15 + 0.05 + r) * chroma[0];
  37164. data[3 * i + 1] = 255 * (d / 15 + 0.05 + r) * chroma[1];
  37165. data[3 * i + 2] = 255 * (d / 15 + 0.05 + r) * chroma[2];
  37166. }
  37167. }
  37168. let texture = new DataTexture(data, width, height, RGBFormat);
  37169. texture.needsUpdate = true;
  37170. return texture;
  37171. }
  37172. static getMousePointCloudIntersection (mouse, camera, viewer, pointclouds, params = {}) {
  37173. let renderer = viewer.renderer;
  37174. let nmouse = {
  37175. x: (mouse.x / renderer.domElement.clientWidth) * 2 - 1,
  37176. y: -(mouse.y / renderer.domElement.clientHeight) * 2 + 1
  37177. };
  37178. let pickParams = {};
  37179. if(params.pickClipped){
  37180. pickParams.pickClipped = params.pickClipped;
  37181. }
  37182. pickParams.x = mouse.x;
  37183. pickParams.y = renderer.domElement.clientHeight - mouse.y;
  37184. let raycaster = new Raycaster();
  37185. raycaster.setFromCamera(nmouse, camera);
  37186. let ray = raycaster.ray;
  37187. let selectedPointcloud = null;
  37188. let closestDistance = Infinity;
  37189. let closestIntersection = null;
  37190. let closestPoint = null;
  37191. for(let pointcloud of pointclouds){
  37192. let point = pointcloud.pick(viewer, camera, ray, pickParams);
  37193. if(!point){
  37194. continue;
  37195. }
  37196. let distance = camera.position.distanceTo(point.position);
  37197. if (distance < closestDistance) {
  37198. closestDistance = distance;
  37199. selectedPointcloud = pointcloud;
  37200. closestIntersection = point.position;
  37201. closestPoint = point;
  37202. }
  37203. }
  37204. if (selectedPointcloud) {
  37205. return {
  37206. location: closestIntersection,
  37207. distance: closestDistance,
  37208. pointcloud: selectedPointcloud,
  37209. point: closestPoint
  37210. };
  37211. } else {
  37212. return null;
  37213. }
  37214. }
  37215. static pixelsArrayToImage (pixels, width, height) {
  37216. let canvas = document.createElement('canvas');
  37217. canvas.width = width;
  37218. canvas.height = height;
  37219. let context = canvas.getContext('2d');
  37220. pixels = new pixels.constructor(pixels);
  37221. for (let i = 0; i < pixels.length; i++) {
  37222. pixels[i * 4 + 3] = 255;
  37223. }
  37224. let imageData = context.createImageData(width, height);
  37225. imageData.data.set(pixels);
  37226. context.putImageData(imageData, 0, 0);
  37227. let img = new Image();
  37228. img.src = canvas.toDataURL();
  37229. // img.style.transform = "scaleY(-1)";
  37230. return img;
  37231. }
  37232. static pixelsArrayToDataUrl(pixels, width, height) {
  37233. let canvas = document.createElement('canvas');
  37234. canvas.width = width;
  37235. canvas.height = height;
  37236. let context = canvas.getContext('2d');
  37237. pixels = new pixels.constructor(pixels);
  37238. for (let i = 0; i < pixels.length; i++) {
  37239. pixels[i * 4 + 3] = 255;
  37240. }
  37241. let imageData = context.createImageData(width, height);
  37242. imageData.data.set(pixels);
  37243. context.putImageData(imageData, 0, 0);
  37244. let dataURL = canvas.toDataURL();
  37245. return dataURL;
  37246. }
  37247. static pixelsArrayToCanvas(pixels, width, height){
  37248. let canvas = document.createElement('canvas');
  37249. canvas.width = width;
  37250. canvas.height = height;
  37251. let context = canvas.getContext('2d');
  37252. pixels = new pixels.constructor(pixels);
  37253. //for (let i = 0; i < pixels.length; i++) {
  37254. // pixels[i * 4 + 3] = 255;
  37255. //}
  37256. // flip vertically
  37257. let bytesPerLine = width * 4;
  37258. for(let i = 0; i < parseInt(height / 2); i++){
  37259. let j = height - i - 1;
  37260. let lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine);
  37261. let lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine);
  37262. pixels.set(lineJ, i * bytesPerLine);
  37263. pixels.set(lineI, j * bytesPerLine);
  37264. }
  37265. let imageData = context.createImageData(width, height);
  37266. imageData.data.set(pixels);
  37267. context.putImageData(imageData, 0, 0);
  37268. return canvas;
  37269. }
  37270. static removeListeners(dispatcher, type){
  37271. if (dispatcher._listeners === undefined) {
  37272. return;
  37273. }
  37274. if (dispatcher._listeners[ type ]) {
  37275. delete dispatcher._listeners[ type ];
  37276. }
  37277. }
  37278. static mouseToRay(mouse, camera, width, height){
  37279. let normalizedMouse = {
  37280. x: (mouse.x / width) * 2 - 1,
  37281. y: -(mouse.y / height) * 2 + 1
  37282. };
  37283. let vector = new Vector3(normalizedMouse.x, normalizedMouse.y, 0.5);
  37284. let origin = camera.position.clone();
  37285. vector.unproject(camera);
  37286. let direction = new Vector3().subVectors(vector, origin).normalize();
  37287. let ray = new Ray(origin, direction);
  37288. return ray;
  37289. }
  37290. static projectedRadius(radius, camera, distance, screenWidth, screenHeight){
  37291. if(camera instanceof OrthographicCamera){
  37292. return Utils.projectedRadiusOrtho(radius, camera.projectionMatrix, screenWidth, screenHeight);
  37293. }else if(camera instanceof PerspectiveCamera){
  37294. return Utils.projectedRadiusPerspective(radius, camera.fov * Math.PI / 180, distance, screenHeight);
  37295. }else {
  37296. throw new Error("invalid parameters");
  37297. }
  37298. }
  37299. static projectedRadiusPerspective(radius, fov, distance, screenHeight) {
  37300. let projFactor = (1 / Math.tan(fov / 2)) / distance;
  37301. projFactor = projFactor * screenHeight / 2;
  37302. return radius * projFactor;
  37303. }
  37304. static projectedRadiusOrtho(radius, proj, screenWidth, screenHeight) {
  37305. let p1 = new Vector4(0);
  37306. let p2 = new Vector4(radius);
  37307. p1.applyMatrix4(proj);
  37308. p2.applyMatrix4(proj);
  37309. p1 = new Vector3(p1.x, p1.y, p1.z);
  37310. p2 = new Vector3(p2.x, p2.y, p2.z);
  37311. p1.x = (p1.x + 1.0) * 0.5 * screenWidth;
  37312. p1.y = (p1.y + 1.0) * 0.5 * screenHeight;
  37313. p2.x = (p2.x + 1.0) * 0.5 * screenWidth;
  37314. p2.y = (p2.y + 1.0) * 0.5 * screenHeight;
  37315. return p1.distanceTo(p2);
  37316. }
  37317. static topView(camera, node){
  37318. camera.position.set(0, 1, 0);
  37319. camera.rotation.set(-Math.PI / 2, 0, 0);
  37320. camera.zoomTo(node, 1);
  37321. }
  37322. static frontView (camera, node) {
  37323. camera.position.set(0, 0, 1);
  37324. camera.rotation.set(0, 0, 0);
  37325. camera.zoomTo(node, 1);
  37326. }
  37327. static leftView (camera, node) {
  37328. camera.position.set(-1, 0, 0);
  37329. camera.rotation.set(0, -Math.PI / 2, 0);
  37330. camera.zoomTo(node, 1);
  37331. }
  37332. static rightView (camera, node) {
  37333. camera.position.set(1, 0, 0);
  37334. camera.rotation.set(0, Math.PI / 2, 0);
  37335. camera.zoomTo(node, 1);
  37336. }
  37337. static findClosestGpsTime(target, viewer){
  37338. const start = performance.now();
  37339. const nodes = [];
  37340. for(const pc of viewer.scene.pointclouds){
  37341. nodes.push(pc.root);
  37342. for(const child of pc.root.children){
  37343. if(child){
  37344. nodes.push(child);
  37345. }
  37346. }
  37347. }
  37348. let closestNode = null;
  37349. let closestIndex = Infinity;
  37350. let closestDistance = Infinity;
  37351. let closestValue = 0;
  37352. for(const node of nodes){
  37353. const isOkay = node.geometryNode != null
  37354. && node.geometryNode.geometry != null
  37355. && node.sceneNode != null;
  37356. if(!isOkay){
  37357. continue;
  37358. }
  37359. let geometry = node.geometryNode.geometry;
  37360. let gpsTime = geometry.attributes["gps-time"];
  37361. let range = gpsTime.potree.range;
  37362. for(let i = 0; i < gpsTime.array.length; i++){
  37363. let value = gpsTime.array[i];
  37364. value = value * (range[1] - range[0]) + range[0];
  37365. const distance = Math.abs(target - value);
  37366. if(distance < closestDistance){
  37367. closestIndex = i;
  37368. closestDistance = distance;
  37369. closestValue = value;
  37370. closestNode = node;
  37371. //console.log("found a closer one: " + value);
  37372. }
  37373. }
  37374. }
  37375. const geometry = closestNode.geometryNode.geometry;
  37376. const position = new Vector3(
  37377. geometry.attributes.position.array[3 * closestIndex + 0],
  37378. geometry.attributes.position.array[3 * closestIndex + 1],
  37379. geometry.attributes.position.array[3 * closestIndex + 2],
  37380. );
  37381. position.applyMatrix4(closestNode.sceneNode.matrixWorld);
  37382. const end = performance.now();
  37383. const duration = (end - start);
  37384. console.log(`duration: ${duration.toFixed(3)}ms`);
  37385. return {
  37386. node: closestNode,
  37387. index: closestIndex,
  37388. position: position,
  37389. };
  37390. }
  37391. /**
  37392. *
  37393. * 0: no intersection
  37394. * 1: intersection
  37395. * 2: fully inside
  37396. */
  37397. static frustumSphereIntersection (frustum, sphere) {
  37398. let planes = frustum.planes;
  37399. let center = sphere.center;
  37400. let negRadius = -sphere.radius;
  37401. let minDistance = Number.MAX_VALUE;
  37402. for (let i = 0; i < 6; i++) {
  37403. let distance = planes[ i ].distanceToPoint(center);
  37404. if (distance < negRadius) {
  37405. return 0;
  37406. }
  37407. minDistance = Math.min(minDistance, distance);
  37408. }
  37409. return (minDistance >= sphere.radius) ? 2 : 1;
  37410. }
  37411. // code taken from three.js
  37412. // ImageUtils - generateDataTexture()
  37413. static generateDataTexture (width, height, color) {
  37414. let size = width * height;
  37415. let data = new Uint8Array(4 * width * height);
  37416. let r = Math.floor(color.r * 255);
  37417. let g = Math.floor(color.g * 255);
  37418. let b = Math.floor(color.b * 255);
  37419. for (let i = 0; i < size; i++) {
  37420. data[ i * 3 ] = r;
  37421. data[ i * 3 + 1 ] = g;
  37422. data[ i * 3 + 2 ] = b;
  37423. }
  37424. let texture = new DataTexture(data, width, height, RGBAFormat);
  37425. texture.needsUpdate = true;
  37426. texture.magFilter = NearestFilter;
  37427. return texture;
  37428. }
  37429. // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
  37430. static getParameterByName (name) {
  37431. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  37432. let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  37433. let results = regex.exec(document.location.search);
  37434. return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' '));
  37435. }
  37436. static setParameter (name, value) {
  37437. // value = encodeURIComponent(value);
  37438. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  37439. let regex = new RegExp('([\\?&])(' + name + '=([^&#]*))');
  37440. let results = regex.exec(document.location.search);
  37441. let url = window.location.href;
  37442. if (results === null) {
  37443. if (window.location.search.length === 0) {
  37444. url = url + '?';
  37445. } else {
  37446. url = url + '&';
  37447. }
  37448. url = url + name + '=' + value;
  37449. } else {
  37450. let newValue = name + '=' + value;
  37451. url = url.replace(results[2], newValue);
  37452. }
  37453. window.history.replaceState({}, '', url);
  37454. }
  37455. static createChildAABB(aabb, index){
  37456. let min = aabb.min.clone();
  37457. let max = aabb.max.clone();
  37458. let size = new Vector3().subVectors(max, min);
  37459. if ((index & 0b0001) > 0) {
  37460. min.z += size.z / 2;
  37461. } else {
  37462. max.z -= size.z / 2;
  37463. }
  37464. if ((index & 0b0010) > 0) {
  37465. min.y += size.y / 2;
  37466. } else {
  37467. max.y -= size.y / 2;
  37468. }
  37469. if ((index & 0b0100) > 0) {
  37470. min.x += size.x / 2;
  37471. } else {
  37472. max.x -= size.x / 2;
  37473. }
  37474. return new Box3(min, max);
  37475. }
  37476. // see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
  37477. static clipboardCopy(text){
  37478. let textArea = document.createElement("textarea");
  37479. textArea.style.position = 'fixed';
  37480. textArea.style.top = 0;
  37481. textArea.style.left = 0;
  37482. textArea.style.width = '2em';
  37483. textArea.style.height = '2em';
  37484. textArea.style.padding = 0;
  37485. textArea.style.border = 'none';
  37486. textArea.style.outline = 'none';
  37487. textArea.style.boxShadow = 'none';
  37488. textArea.style.background = 'transparent';
  37489. textArea.value = text;
  37490. document.body.appendChild(textArea);
  37491. textArea.select();
  37492. try {
  37493. let success = document.execCommand('copy');
  37494. if(success){
  37495. console.log("copied text to clipboard");
  37496. }else {
  37497. console.log("copy to clipboard failed");
  37498. }
  37499. } catch (err) {
  37500. console.log("error while trying to copy to clipboard");
  37501. }
  37502. document.body.removeChild(textArea);
  37503. }
  37504. static getMeasurementIcon(measurement){
  37505. if (measurement instanceof Measure) {
  37506. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  37507. return `${Potree.resourcePath}/icons/distance.svg`;
  37508. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  37509. return `${Potree.resourcePath}/icons/area.svg`;
  37510. } else if (measurement.maxMarkers === 1) {
  37511. return `${Potree.resourcePath}/icons/point.svg`;
  37512. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  37513. return `${Potree.resourcePath}/icons/angle.png`;
  37514. } else if (measurement.showHeight) {
  37515. return `${Potree.resourcePath}/icons/height.svg`;
  37516. } else {
  37517. return `${Potree.resourcePath}/icons/distance.svg`;
  37518. }
  37519. } else if (measurement instanceof Profile) {
  37520. return `${Potree.resourcePath}/icons/profile.svg`;
  37521. } else if (measurement instanceof Volume) {
  37522. return `${Potree.resourcePath}/icons/volume.svg`;
  37523. } else if (measurement instanceof PolygonClipVolume) {
  37524. return `${Potree.resourcePath}/icons/clip-polygon.svg`;
  37525. }
  37526. }
  37527. static lineToLineIntersection(P0, P1, P2, P3){
  37528. const P = [P0, P1, P2, P3];
  37529. const d = (m, n, o, p) => {
  37530. let result =
  37531. (P[m].x - P[n].x) * (P[o].x - P[p].x)
  37532. + (P[m].y - P[n].y) * (P[o].y - P[p].y)
  37533. + (P[m].z - P[n].z) * (P[o].z - P[p].z);
  37534. return result;
  37535. };
  37536. const mua = (d(0, 2, 3, 2) * d(3, 2, 1, 0) - d(0, 2, 1, 0) * d(3, 2, 3, 2))
  37537. /**-----------------------------------------------------------------**/ /
  37538. (d(1, 0, 1, 0) * d(3, 2, 3, 2) - d(3, 2, 1, 0) * d(3, 2, 1, 0));
  37539. const mub = (d(0, 2, 3, 2) + mua * d(3, 2, 1, 0))
  37540. /**--------------------------------------**/ /
  37541. d(3, 2, 3, 2);
  37542. const P01 = P1.clone().sub(P0);
  37543. const P23 = P3.clone().sub(P2);
  37544. const Pa = P0.clone().add(P01.multiplyScalar(mua));
  37545. const Pb = P2.clone().add(P23.multiplyScalar(mub));
  37546. const center = Pa.clone().add(Pb).multiplyScalar(0.5);
  37547. return center;
  37548. }
  37549. static computeCircleCenter(A, B, C){
  37550. const AB = B.clone().sub(A);
  37551. const AC = C.clone().sub(A);
  37552. const N = AC.clone().cross(AB).normalize();
  37553. const ab_dir = AB.clone().cross(N).normalize();
  37554. const ac_dir = AC.clone().cross(N).normalize();
  37555. const ab_origin = A.clone().add(B).multiplyScalar(0.5);
  37556. const ac_origin = A.clone().add(C).multiplyScalar(0.5);
  37557. const P0 = ab_origin;
  37558. const P1 = ab_origin.clone().add(ab_dir);
  37559. const P2 = ac_origin;
  37560. const P3 = ac_origin.clone().add(ac_dir);
  37561. const center = Utils.lineToLineIntersection(P0, P1, P2, P3);
  37562. return center;
  37563. // Potree.Utils.debugLine(viewer.scene.scene, P0, P1, 0x00ff00);
  37564. // Potree.Utils.debugLine(viewer.scene.scene, P2, P3, 0x0000ff);
  37565. // Potree.Utils.debugSphere(viewer.scene.scene, center, 0.03, 0xff00ff);
  37566. // const radius = center.distanceTo(A);
  37567. // Potree.Utils.debugCircle(viewer.scene.scene, center, radius, new THREE.Vector3(0, 0, 1), 0xff00ff);
  37568. }
  37569. static getNorthVec(p1, distance, projection){
  37570. if(projection){
  37571. // if there is a projection, transform coordinates to WGS84
  37572. // and compute angle to north there
  37573. proj4.defs("pointcloud", projection);
  37574. const transform = proj4("pointcloud", "WGS84");
  37575. const llP1 = transform.forward(p1.toArray());
  37576. let llP2 = transform.forward([p1.x, p1.y + distance]);
  37577. const polarRadius = Math.sqrt((llP2[0] - llP1[0]) ** 2 + (llP2[1] - llP1[1]) ** 2);
  37578. llP2 = [llP1[0], llP1[1] + polarRadius];
  37579. const northVec = transform.inverse(llP2);
  37580. return new Vector3(...northVec, p1.z).sub(p1);
  37581. }else {
  37582. // if there is no projection, assume [0, 1, 0] as north direction
  37583. const vec = new Vector3(0, 1, 0).multiplyScalar(distance);
  37584. return vec;
  37585. }
  37586. }
  37587. static computeAzimuth(p1, p2, projection){
  37588. let azimuth = 0;
  37589. if(projection){
  37590. // if there is a projection, transform coordinates to WGS84
  37591. // and compute angle to north there
  37592. let transform;
  37593. if (projection.includes('EPSG')) {
  37594. transform = proj4(projection, "WGS84");
  37595. } else {
  37596. proj4.defs("pointcloud", projection);
  37597. transform = proj4("pointcloud", "WGS84");
  37598. }
  37599. const llP1 = transform.forward(p1.toArray());
  37600. const llP2 = transform.forward(p2.toArray());
  37601. const dir = [
  37602. llP2[0] - llP1[0],
  37603. llP2[1] - llP1[1],
  37604. ];
  37605. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  37606. }else {
  37607. // if there is no projection, assume [0, 1, 0] as north direction
  37608. const dir = [p2.x - p1.x, p2.y - p1.y];
  37609. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  37610. }
  37611. // make clockwise
  37612. azimuth = -azimuth;
  37613. return azimuth;
  37614. }
  37615. static async loadScript(url){
  37616. return new Promise( resolve => {
  37617. const element = document.getElementById(url);
  37618. if(element){
  37619. resolve();
  37620. }else {
  37621. const script = document.createElement("script");
  37622. script.id = url;
  37623. script.onload = () => {
  37624. resolve();
  37625. };
  37626. script.src = url;
  37627. document.body.appendChild(script);
  37628. }
  37629. });
  37630. }
  37631. static createSvgGradient(scheme){
  37632. // this is what we are creating:
  37633. //
  37634. //<svg width="1em" height="3em" xmlns="http://www.w3.org/2000/svg">
  37635. // <defs>
  37636. // <linearGradient id="gradientID" gradientTransform="rotate(90)">
  37637. // <stop offset="0%" stop-color="rgb(93, 78, 162)" />
  37638. // ...
  37639. // <stop offset="100%" stop-color="rgb(157, 0, 65)" />
  37640. // </linearGradient>
  37641. // </defs>
  37642. //
  37643. // <rect width="100%" height="100%" fill="url('#myGradient')" stroke="black" stroke-width="0.1em"/>
  37644. //</svg>
  37645. const gradientId = `${Math.random()}_${Date.now()}`;
  37646. const svgn = "http://www.w3.org/2000/svg";
  37647. const svg = document.createElementNS(svgn, "svg");
  37648. svg.setAttributeNS(null, "width", "2em");
  37649. svg.setAttributeNS(null, "height", "3em");
  37650. { // <defs>
  37651. const defs = document.createElementNS(svgn, "defs");
  37652. const linearGradient = document.createElementNS(svgn, "linearGradient");
  37653. linearGradient.setAttributeNS(null, "id", gradientId);
  37654. linearGradient.setAttributeNS(null, "gradientTransform", "rotate(90)");
  37655. for(let i = scheme.length - 1; i >= 0; i--){
  37656. const stopVal = scheme[i];
  37657. const percent = parseInt(100 - stopVal[0] * 100);
  37658. const [r, g, b] = stopVal[1].toArray().map(v => parseInt(v * 255));
  37659. const stop = document.createElementNS(svgn, "stop");
  37660. stop.setAttributeNS(null, "offset", `${percent}%`);
  37661. stop.setAttributeNS(null, "stop-color", `rgb(${r}, ${g}, ${b})`);
  37662. linearGradient.appendChild(stop);
  37663. }
  37664. defs.appendChild(linearGradient);
  37665. svg.appendChild(defs);
  37666. }
  37667. const rect = document.createElementNS(svgn, "rect");
  37668. rect.setAttributeNS(null, "width", `100%`);
  37669. rect.setAttributeNS(null, "height", `100%`);
  37670. rect.setAttributeNS(null, "fill", `url("#${gradientId}")`);
  37671. rect.setAttributeNS(null, "stroke", `black`);
  37672. rect.setAttributeNS(null, "stroke-width", `0.1em`);
  37673. svg.appendChild(rect);
  37674. return svg;
  37675. }
  37676. static async waitAny(promises){
  37677. return new Promise( (resolve) => {
  37678. promises.map( promise => {
  37679. promise.then( () => {
  37680. resolve();
  37681. });
  37682. });
  37683. });
  37684. }
  37685. }
  37686. Utils.screenPass = new function () {
  37687. this.screenScene = new Scene();
  37688. this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1));
  37689. this.screenQuad.material.depthTest = true;
  37690. this.screenQuad.material.depthWrite = true;
  37691. this.screenQuad.material.transparent = true;
  37692. this.screenScene.add(this.screenQuad);
  37693. this.camera = new Camera();
  37694. this.render = function (renderer, material, target) {
  37695. this.screenQuad.material = material;
  37696. if (typeof target === 'undefined') {
  37697. renderer.render(this.screenScene, this.camera);
  37698. } else {
  37699. renderer.render(this.screenScene, this.camera, target);
  37700. }
  37701. };
  37702. }();
  37703. class Version{
  37704. constructor(version){
  37705. this.version = version;
  37706. let vmLength = (version.indexOf('.') === -1) ? version.length : version.indexOf('.');
  37707. this.versionMajor = parseInt(version.substr(0, vmLength));
  37708. this.versionMinor = parseInt(version.substr(vmLength + 1));
  37709. if (this.versionMinor.length === 0) {
  37710. this.versionMinor = 0;
  37711. }
  37712. }
  37713. newerThan(version){
  37714. let v = new Version(version);
  37715. if (this.versionMajor > v.versionMajor) {
  37716. return true;
  37717. } else if (this.versionMajor === v.versionMajor && this.versionMinor > v.versionMinor) {
  37718. return true;
  37719. } else {
  37720. return false;
  37721. }
  37722. }
  37723. equalOrHigher(version){
  37724. let v = new Version(version);
  37725. if (this.versionMajor > v.versionMajor) {
  37726. return true;
  37727. } else if (this.versionMajor === v.versionMajor && this.versionMinor >= v.versionMinor) {
  37728. return true;
  37729. } else {
  37730. return false;
  37731. }
  37732. }
  37733. upTo(version){
  37734. return !this.newerThan(version);
  37735. }
  37736. }
  37737. //加载 解析点云
  37738. class BinaryLoader{
  37739. constructor(version, boundingBox, scale){
  37740. if (typeof (version) === 'string') {
  37741. this.version = new Version(version);
  37742. } else {
  37743. this.version = version;
  37744. }
  37745. this.boundingBox = boundingBox;
  37746. this.scale = scale;
  37747. }
  37748. load(node){
  37749. if (node.loaded) {
  37750. return;
  37751. }
  37752. let url = node.getURL();
  37753. if (this.version.equalOrHigher('1.4')) {
  37754. url += '.bin';
  37755. }
  37756. let xhr = XHRFactory.createXMLHttpRequest();
  37757. xhr.open('GET', url, true);
  37758. xhr.responseType = 'arraybuffer';
  37759. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  37760. xhr.onreadystatechange = () => {
  37761. if (xhr.readyState === 4) {
  37762. if((xhr.status === 200 || xhr.status === 0) && xhr.response !== null){
  37763. let buffer = xhr.response;
  37764. this.parse(node, buffer);
  37765. } else {
  37766. //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  37767. throw new Error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  37768. }
  37769. }
  37770. };
  37771. try {
  37772. xhr.send(null);
  37773. } catch (e) {
  37774. console.log('fehler beim laden der punktwolke: ' + e);
  37775. }
  37776. };
  37777. parse(node, buffer, callback){
  37778. let pointAttributes = node.pcoGeometry.pointAttributes;
  37779. let numPoints = buffer.byteLength / node.pcoGeometry.pointAttributes.byteSize;
  37780. if (this.version.upTo('1.5')) {
  37781. node.numPoints = numPoints;
  37782. }
  37783. let workerPath = Potree.scriptPath + '/workers/BinaryDecoderWorker.js';
  37784. let worker = Potree.workerPool.getWorker(workerPath);
  37785. worker.onmessage = function (e) {
  37786. let data = e.data;
  37787. let buffers = data.attributeBuffers;
  37788. let tightBoundingBox = new Box3(
  37789. new Vector3().fromArray(data.tightBoundingBox.min),
  37790. new Vector3().fromArray(data.tightBoundingBox.max)
  37791. );
  37792. Potree.workerPool.returnWorker(workerPath, worker);
  37793. let geometry = new BufferGeometry();
  37794. for(let property in buffers){
  37795. let buffer = buffers[property].buffer;
  37796. let batchAttribute = buffers[property].attribute;
  37797. if (property === "POSITION_CARTESIAN") {
  37798. geometry.setAttribute('position', new BufferAttribute(new Float32Array(buffer), 3));
  37799. } else if (property === "rgba") {
  37800. geometry.setAttribute("rgba", new BufferAttribute(new Uint8Array(buffer), 4, true));
  37801. } else if (property === "NORMAL_SPHEREMAPPED") {
  37802. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  37803. } else if (property === "NORMAL_OCT16") {
  37804. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  37805. } else if (property === "NORMAL") {
  37806. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  37807. } else if (property === "INDICES") {
  37808. let bufferAttribute = new BufferAttribute(new Uint8Array(buffer), 4);
  37809. bufferAttribute.normalized = true;
  37810. geometry.setAttribute('indices', bufferAttribute);
  37811. } else if (property === "SPACING") {
  37812. let bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  37813. geometry.setAttribute('spacing', bufferAttribute);
  37814. } else {
  37815. const bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  37816. bufferAttribute.potree = {
  37817. offset: buffers[property].offset,
  37818. scale: buffers[property].scale,
  37819. preciseBuffer: buffers[property].preciseBuffer,
  37820. range: batchAttribute.range,
  37821. };
  37822. geometry.setAttribute(property, bufferAttribute);
  37823. const attribute = pointAttributes.attributes.find(a => a.name === batchAttribute.name);
  37824. attribute.range[0] = Math.min(attribute.range[0], batchAttribute.range[0]);
  37825. attribute.range[1] = Math.max(attribute.range[1], batchAttribute.range[1]);
  37826. if(node.getLevel() === 0){
  37827. attribute.initialRange = batchAttribute.range;
  37828. }
  37829. }
  37830. }
  37831. tightBoundingBox.max.sub(tightBoundingBox.min);
  37832. tightBoundingBox.min.set(0, 0, 0);
  37833. let numPoints = e.data.buffer.byteLength / pointAttributes.byteSize;
  37834. node.numPoints = numPoints;
  37835. node.geometry = geometry;
  37836. node.mean = new Vector3(...data.mean);
  37837. node.tightBoundingBox = tightBoundingBox;
  37838. node.loaded = true;
  37839. node.loading = false;
  37840. node.estimatedSpacing = data.estimatedSpacing;
  37841. Potree.numNodesLoading--;
  37842. callback();//add
  37843. };
  37844. let message = {
  37845. buffer: buffer,
  37846. pointAttributes: pointAttributes,
  37847. version: this.version.version,
  37848. min: [ node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z ],
  37849. offset: [node.pcoGeometry.offset.x, node.pcoGeometry.offset.y, node.pcoGeometry.offset.z],
  37850. scale: this.scale,
  37851. spacing: node.spacing,
  37852. hasChildren: node.hasChildren,
  37853. name: node.name
  37854. };
  37855. worker.postMessage(message, [message.buffer]);
  37856. };
  37857. }
  37858. let ftCanvas = document.createElement('canvas');
  37859. const Features = (function () {
  37860. let gl = ftCanvas.getContext('webgl') || ftCanvas.getContext('experimental-webgl');
  37861. if (gl === null){
  37862. return {};
  37863. }
  37864. // -- code taken from THREE.WebGLRenderer --
  37865. let _vertexShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT);
  37866. let _vertexShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT);
  37867. // Unused: let _vertexShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT);
  37868. let _fragmentShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
  37869. let _fragmentShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT);
  37870. // Unused: let _fragmentShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT);
  37871. let highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  37872. let mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  37873. // -----------------------------------------
  37874. let precision;
  37875. if (highpAvailable) {
  37876. precision = 'highp';
  37877. } else if (mediumpAvailable) {
  37878. precision = 'mediump';
  37879. } else {
  37880. precision = 'lowp';
  37881. }
  37882. return {
  37883. SHADER_INTERPOLATION: {
  37884. isSupported: function () {
  37885. let supported = true;
  37886. supported = supported && gl.getExtension('EXT_frag_depth');
  37887. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  37888. return supported;
  37889. }
  37890. },
  37891. SHADER_SPLATS: {
  37892. isSupported: function () {
  37893. let supported = true;
  37894. supported = supported && gl.getExtension('EXT_frag_depth');
  37895. supported = supported && gl.getExtension('OES_texture_float');
  37896. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  37897. return supported;
  37898. }
  37899. },
  37900. SHADER_EDL: {
  37901. isSupported: function () {
  37902. let supported = true;
  37903. supported = supported && gl.getExtension('EXT_frag_depth');
  37904. supported = supported && gl.getExtension('OES_texture_float');
  37905. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  37906. //supported = supported || (gl instanceof WebGL2RenderingContext);
  37907. return supported;
  37908. }
  37909. },
  37910. //WEBGL2: {
  37911. // isSupported: function(){
  37912. // return typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext;
  37913. // }
  37914. //},
  37915. precision: precision
  37916. };
  37917. }());
  37918. /**
  37919. * Some types of possible point attribute data formats
  37920. *
  37921. * @class
  37922. */
  37923. const PointAttributeTypes = {
  37924. DATA_TYPE_DOUBLE: {ordinal: 0, name: "double", size: 8},
  37925. DATA_TYPE_FLOAT: {ordinal: 1, name: "float", size: 4},
  37926. DATA_TYPE_INT8: {ordinal: 2, name: "int8", size: 1},
  37927. DATA_TYPE_UINT8: {ordinal: 3, name: "uint8", size: 1},
  37928. DATA_TYPE_INT16: {ordinal: 4, name: "int16", size: 2},
  37929. DATA_TYPE_UINT16: {ordinal: 5, name: "uint16", size: 2},
  37930. DATA_TYPE_INT32: {ordinal: 6, name: "int32", size: 4},
  37931. DATA_TYPE_UINT32: {ordinal: 7, name: "uint32", size: 4},
  37932. DATA_TYPE_INT64: {ordinal: 8, name: "int64", size: 8},
  37933. DATA_TYPE_UINT64: {ordinal: 9, name: "uint64", size: 8}
  37934. };
  37935. let i = 0;
  37936. for (let obj in PointAttributeTypes) {
  37937. PointAttributeTypes[i] = PointAttributeTypes[obj];
  37938. i++;
  37939. }
  37940. class PointAttribute{
  37941. constructor(name, type, numElements){
  37942. this.name = name;
  37943. this.type = type;
  37944. this.numElements = numElements;
  37945. this.byteSize = this.numElements * this.type.size;
  37946. this.description = "";
  37947. this.range = [Infinity, -Infinity];
  37948. }
  37949. };
  37950. PointAttribute.POSITION_CARTESIAN = new PointAttribute(
  37951. "POSITION_CARTESIAN", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  37952. PointAttribute.RGBA_PACKED = new PointAttribute(
  37953. "COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 4);
  37954. PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED;
  37955. PointAttribute.RGB_PACKED = new PointAttribute(
  37956. "COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 3);
  37957. PointAttribute.NORMAL_FLOATS = new PointAttribute(
  37958. "NORMAL_FLOATS", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  37959. PointAttribute.INTENSITY = new PointAttribute(
  37960. "INTENSITY", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  37961. PointAttribute.CLASSIFICATION = new PointAttribute(
  37962. "CLASSIFICATION", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  37963. PointAttribute.NORMAL_SPHEREMAPPED = new PointAttribute(
  37964. "NORMAL_SPHEREMAPPED", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  37965. PointAttribute.NORMAL_OCT16 = new PointAttribute(
  37966. "NORMAL_OCT16", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  37967. PointAttribute.NORMAL = new PointAttribute(
  37968. "NORMAL", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  37969. PointAttribute.RETURN_NUMBER = new PointAttribute(
  37970. "RETURN_NUMBER", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  37971. PointAttribute.NUMBER_OF_RETURNS = new PointAttribute(
  37972. "NUMBER_OF_RETURNS", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  37973. PointAttribute.SOURCE_ID = new PointAttribute(
  37974. "SOURCE_ID", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  37975. PointAttribute.INDICES = new PointAttribute(
  37976. "INDICES", PointAttributeTypes.DATA_TYPE_UINT32, 1);
  37977. PointAttribute.SPACING = new PointAttribute(
  37978. "SPACING", PointAttributeTypes.DATA_TYPE_FLOAT, 1);
  37979. PointAttribute.GPS_TIME = new PointAttribute(
  37980. "GPS_TIME", PointAttributeTypes.DATA_TYPE_DOUBLE, 1);
  37981. class PointAttributes{
  37982. constructor(pointAttributes){
  37983. this.attributes = [];
  37984. this.byteSize = 0;
  37985. this.size = 0;
  37986. this.vectors = [];
  37987. if (pointAttributes != null) {
  37988. for (let i = 0; i < pointAttributes.length; i++) {
  37989. let pointAttributeName = pointAttributes[i];
  37990. let pointAttribute = PointAttribute[pointAttributeName];
  37991. this.attributes.push(pointAttribute);
  37992. this.byteSize += pointAttribute.byteSize;
  37993. this.size++;
  37994. }
  37995. }
  37996. }
  37997. add(pointAttribute){
  37998. this.attributes.push(pointAttribute);
  37999. this.byteSize += pointAttribute.byteSize;
  38000. this.size++;
  38001. };
  38002. addVector(vector){
  38003. this.vectors.push(vector);
  38004. }
  38005. hasNormals(){
  38006. for (let name in this.attributes) {
  38007. let pointAttribute = this.attributes[name];
  38008. if (
  38009. pointAttribute === PointAttribute.NORMAL_SPHEREMAPPED ||
  38010. pointAttribute === PointAttribute.NORMAL_FLOATS ||
  38011. pointAttribute === PointAttribute.NORMAL ||
  38012. pointAttribute === PointAttribute.NORMAL_OCT16) {
  38013. return true;
  38014. }
  38015. }
  38016. return false;
  38017. };
  38018. }
  38019. class Points$1 {
  38020. constructor () {
  38021. this.boundingBox = new Box3();
  38022. this.numPoints = 0;
  38023. this.data = {};
  38024. }
  38025. add (points) {
  38026. let currentSize = this.numPoints;
  38027. let additionalSize = points.numPoints;
  38028. let newSize = currentSize + additionalSize;
  38029. let thisAttributes = Object.keys(this.data);
  38030. let otherAttributes = Object.keys(points.data);
  38031. let attributes = new Set([...thisAttributes, ...otherAttributes]);
  38032. for (let attribute of attributes) {
  38033. if (thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  38034. // attribute in both, merge
  38035. let Type = this.data[attribute].constructor;
  38036. let merged = new Type(this.data[attribute].length + points.data[attribute].length);
  38037. merged.set(this.data[attribute], 0);
  38038. merged.set(points.data[attribute], this.data[attribute].length);
  38039. this.data[attribute] = merged;
  38040. } else if (thisAttributes.includes(attribute) && !otherAttributes.includes(attribute)) {
  38041. // attribute only in this; take over this and expand to new size
  38042. let elementsPerPoint = this.data[attribute].length / this.numPoints;
  38043. let Type = this.data[attribute].constructor;
  38044. let expanded = new Type(elementsPerPoint * newSize);
  38045. expanded.set(this.data[attribute], 0);
  38046. this.data[attribute] = expanded;
  38047. } else if (!thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  38048. // attribute only in points to be added; take over new points and expand to new size
  38049. let elementsPerPoint = points.data[attribute].length / points.numPoints;
  38050. let Type = points.data[attribute].constructor;
  38051. let expanded = new Type(elementsPerPoint * newSize);
  38052. expanded.set(points.data[attribute], elementsPerPoint * currentSize);
  38053. this.data[attribute] = expanded;
  38054. }
  38055. }
  38056. this.numPoints = newSize;
  38057. this.boundingBox.union(points.boundingBox);
  38058. }
  38059. }
  38060. class CSVExporter {
  38061. static toString (points) {
  38062. let string = '';
  38063. let attributes = Object.keys(points.data)
  38064. .filter(a => a !== 'normal')
  38065. .sort((a, b) => {
  38066. if (a === 'position') return -1;
  38067. if (b === 'position') return 1;
  38068. if (a === 'rgba') return -1;
  38069. if (b === 'rgba') return 1;
  38070. });
  38071. let headerValues = [];
  38072. for (let attribute of attributes) {
  38073. let itemSize = points.data[attribute].length / points.numPoints;
  38074. if (attribute === 'position') {
  38075. headerValues = headerValues.concat(['x', 'y', 'z']);
  38076. } else if (attribute === 'rgba') {
  38077. headerValues = headerValues.concat(['r', 'g', 'b', 'a']);
  38078. } else if (itemSize > 1) {
  38079. for (let i = 0; i < itemSize; i++) {
  38080. headerValues.push(`${attribute}_${i}`);
  38081. }
  38082. } else {
  38083. headerValues.push(attribute);
  38084. }
  38085. }
  38086. string = headerValues.join(', ') + '\n';
  38087. for (let i = 0; i < points.numPoints; i++) {
  38088. let values = [];
  38089. for (let attribute of attributes) {
  38090. let itemSize = points.data[attribute].length / points.numPoints;
  38091. let value = points.data[attribute]
  38092. .subarray(itemSize * i, itemSize * i + itemSize)
  38093. .join(', ');
  38094. values.push(value);
  38095. }
  38096. string += values.join(', ') + '\n';
  38097. }
  38098. return string;
  38099. }
  38100. };
  38101. class LASExporter {
  38102. static toLAS (points) {
  38103. // TODO Unused: let string = '';
  38104. let boundingBox = points.boundingBox;
  38105. let offset = boundingBox.min.clone();
  38106. let diagonal = boundingBox.min.distanceTo(boundingBox.max);
  38107. let scale = new Vector3(0.001, 0.001, 0.001);
  38108. if (diagonal > 1000 * 1000) {
  38109. scale = new Vector3(0.01, 0.01, 0.01);
  38110. } else {
  38111. scale = new Vector3(0.001, 0.001, 0.001);
  38112. }
  38113. let setString = function (string, offset, buffer) {
  38114. let view = new Uint8Array(buffer);
  38115. for (let i = 0; i < string.length; i++) {
  38116. let charCode = string.charCodeAt(i);
  38117. view[offset + i] = charCode;
  38118. }
  38119. };
  38120. let buffer = new ArrayBuffer(227 + 28 * points.numPoints);
  38121. let view = new DataView(buffer);
  38122. let u8View = new Uint8Array(buffer);
  38123. // let u16View = new Uint16Array(buffer);
  38124. setString('LASF', 0, buffer);
  38125. u8View[24] = 1;
  38126. u8View[25] = 2;
  38127. // system identifier o:26 l:32
  38128. // generating software o:58 l:32
  38129. setString('Potree 1.7', 58, buffer);
  38130. // file creation day of year o:90 l:2
  38131. // file creation year o:92 l:2
  38132. // header size o:94 l:2
  38133. view.setUint16(94, 227, true);
  38134. // offset to point data o:96 l:4
  38135. view.setUint32(96, 227, true);
  38136. // number of letiable length records o:100 l:4
  38137. // point data record format 104 1
  38138. u8View[104] = 2;
  38139. // point data record length 105 2
  38140. view.setUint16(105, 28, true);
  38141. // number of point records 107 4
  38142. view.setUint32(107, points.numPoints, true);
  38143. // number of points by return 111 20
  38144. // x scale factor 131 8
  38145. view.setFloat64(131, scale.x, true);
  38146. // y scale factor 139 8
  38147. view.setFloat64(139, scale.y, true);
  38148. // z scale factor 147 8
  38149. view.setFloat64(147, scale.z, true);
  38150. // x offset 155 8
  38151. view.setFloat64(155, offset.x, true);
  38152. // y offset 163 8
  38153. view.setFloat64(163, offset.y, true);
  38154. // z offset 171 8
  38155. view.setFloat64(171, offset.z, true);
  38156. // max x 179 8
  38157. view.setFloat64(179, boundingBox.max.x, true);
  38158. // min x 187 8
  38159. view.setFloat64(187, boundingBox.min.x, true);
  38160. // max y 195 8
  38161. view.setFloat64(195, boundingBox.max.y, true);
  38162. // min y 203 8
  38163. view.setFloat64(203, boundingBox.min.y, true);
  38164. // max z 211 8
  38165. view.setFloat64(211, boundingBox.max.z, true);
  38166. // min z 219 8
  38167. view.setFloat64(219, boundingBox.min.z, true);
  38168. let boffset = 227;
  38169. for (let i = 0; i < points.numPoints; i++) {
  38170. let px = points.data.position[3 * i + 0];
  38171. let py = points.data.position[3 * i + 1];
  38172. let pz = points.data.position[3 * i + 2];
  38173. let ux = parseInt((px - offset.x) / scale.x);
  38174. let uy = parseInt((py - offset.y) / scale.y);
  38175. let uz = parseInt((pz - offset.z) / scale.z);
  38176. view.setUint32(boffset + 0, ux, true);
  38177. view.setUint32(boffset + 4, uy, true);
  38178. view.setUint32(boffset + 8, uz, true);
  38179. if (points.data.intensity) {
  38180. view.setUint16(boffset + 12, (points.data.intensity[i]), true);
  38181. }
  38182. let rt = 0;
  38183. if (points.data.returnNumber) {
  38184. rt += points.data.returnNumber[i];
  38185. }
  38186. if (points.data.numberOfReturns) {
  38187. rt += (points.data.numberOfReturns[i] << 3);
  38188. }
  38189. view.setUint8(boffset + 14, rt);
  38190. if (points.data.classification) {
  38191. view.setUint8(boffset + 15, points.data.classification[i]);
  38192. }
  38193. // scan angle rank
  38194. // user data
  38195. // point source id
  38196. if (points.data.pointSourceID) {
  38197. view.setUint16(boffset + 18, points.data.pointSourceID[i]);
  38198. }
  38199. if (points.data.rgba) {
  38200. let rgba = points.data.rgba;
  38201. view.setUint16(boffset + 20, (rgba[4 * i + 0] * 255), true);
  38202. view.setUint16(boffset + 22, (rgba[4 * i + 1] * 255), true);
  38203. view.setUint16(boffset + 24, (rgba[4 * i + 2] * 255), true);
  38204. }
  38205. boffset += 28;
  38206. }
  38207. return buffer;
  38208. }
  38209. }
  38210. /**
  38211. * @author mrdoob / http://mrdoob.com/ https://github.com/mrdoob/eventdispatcher.js
  38212. *
  38213. * with slight modifications by mschuetz, http://potree.org
  38214. *
  38215. */
  38216. // The MIT License
  38217. //
  38218. // Copyright (c) 2011 Mr.doob
  38219. //
  38220. // Permission is hereby granted, free of charge, to any person obtaining a copy
  38221. // of this software and associated documentation files (the "Software"), to deal
  38222. // in the Software without restriction, including without limitation the rights
  38223. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  38224. // copies of the Software, and to permit persons to whom the Software is
  38225. // furnished to do so, subject to the following conditions:
  38226. //
  38227. // The above copyright notice and this permission notice shall be included in
  38228. // all copies or substantial portions of the Software.
  38229. //
  38230. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38231. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38232. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  38233. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38234. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  38235. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38236. // THE SOFTWARE.
  38237. class EventDispatcher$1{
  38238. constructor(){
  38239. this._listeners = {};
  38240. }
  38241. addEventListener(type, listener){
  38242. const listeners = this._listeners;
  38243. if(listeners[type] === undefined){
  38244. listeners[type] = [];
  38245. }
  38246. if(listeners[type].indexOf(listener) === - 1){
  38247. listeners[type].push( listener );
  38248. }
  38249. }
  38250. hasEventListener(type, listener){
  38251. const listeners = this._listeners;
  38252. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== - 1;
  38253. }
  38254. removeEventListener(type, listener){
  38255. let listeners = this._listeners;
  38256. let listenerArray = listeners[type];
  38257. if (listenerArray !== undefined){
  38258. let index = listenerArray.indexOf(listener);
  38259. if(index !== - 1){
  38260. listenerArray.splice(index, 1);
  38261. }
  38262. }
  38263. }
  38264. removeEventListeners(type){
  38265. if(this._listeners[type] !== undefined){
  38266. delete this._listeners[type];
  38267. }
  38268. };
  38269. dispatchEvent(event){
  38270. let listeners = this._listeners;
  38271. let listenerArray = listeners[event.type];
  38272. if ( listenerArray !== undefined ) {
  38273. event.target = this;
  38274. for(let listener of listenerArray.slice(0)){
  38275. listener.call(this, event);
  38276. }
  38277. }
  38278. }
  38279. }
  38280. class PointCloudTreeNode extends EventDispatcher$1{
  38281. constructor(){
  38282. super();
  38283. this.needsTransformUpdate = true;
  38284. }
  38285. getChildren () {
  38286. throw new Error('override function');
  38287. }
  38288. getBoundingBox () {
  38289. throw new Error('override function');
  38290. }
  38291. isLoaded () {
  38292. throw new Error('override function');
  38293. }
  38294. isGeometryNode () {
  38295. throw new Error('override function');
  38296. }
  38297. isTreeNode () {
  38298. throw new Error('override function');
  38299. }
  38300. getLevel () {
  38301. throw new Error('override function');
  38302. }
  38303. getBoundingSphere () {
  38304. throw new Error('override function');
  38305. }
  38306. };
  38307. class PointCloudTree extends Object3D {
  38308. constructor () {
  38309. super();
  38310. //this.spriteGroup = new THREE.Object3D //add
  38311. }
  38312. initialized () {
  38313. return this.root !== null;
  38314. }
  38315. };
  38316. class PointCloudOctreeGeometry{
  38317. constructor(){
  38318. this.url = null;
  38319. this.octreeDir = null;
  38320. this.spacing = 0;
  38321. this.boundingBox = null;
  38322. this.root = null;
  38323. this.nodes = null;
  38324. this.pointAttributes = null;
  38325. this.hierarchyStepSize = -1;
  38326. this.loader = null;
  38327. }
  38328. }
  38329. class PointCloudOctreeGeometryNode extends PointCloudTreeNode{
  38330. constructor(name, pcoGeometry, boundingBox){
  38331. super();
  38332. this.id = PointCloudOctreeGeometryNode.IDCount++;
  38333. this.name = name;
  38334. this.index = parseInt(name.charAt(name.length - 1));
  38335. this.pcoGeometry = pcoGeometry;
  38336. this.geometry = null;
  38337. this.boundingBox = boundingBox;
  38338. this.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  38339. this.children = {};
  38340. this.numPoints = 0;
  38341. this.level = null;
  38342. this.loaded = false;
  38343. this.oneTimeDisposeHandlers = [];
  38344. }
  38345. isGeometryNode(){
  38346. return true;
  38347. }
  38348. getLevel(){
  38349. return this.level;
  38350. }
  38351. isTreeNode(){
  38352. return false;
  38353. }
  38354. isLoaded(){
  38355. return this.loaded;
  38356. }
  38357. getBoundingSphere(){
  38358. return this.boundingSphere;
  38359. }
  38360. getBoundingBox(){
  38361. return this.boundingBox;
  38362. }
  38363. getChildren(){
  38364. let children = [];
  38365. for (let i = 0; i < 8; i++) {
  38366. if (this.children[i]) {
  38367. children.push(this.children[i]);
  38368. }
  38369. }
  38370. return children;
  38371. }
  38372. getBoundingBox(){
  38373. return this.boundingBox;
  38374. }
  38375. getURL(){
  38376. let url = '';
  38377. let version = this.pcoGeometry.loader.version;
  38378. if (version.equalOrHigher('1.5')) {
  38379. url = this.pcoGeometry.octreeDir + '/' + this.getHierarchyPath() + '/' + this.name;
  38380. } else if (version.equalOrHigher('1.4')) {
  38381. url = this.pcoGeometry.octreeDir + '/' + this.name;
  38382. } else if (version.upTo('1.3')) {
  38383. url = this.pcoGeometry.octreeDir + '/' + this.name;
  38384. }
  38385. return url;
  38386. }
  38387. getHierarchyPath(){
  38388. let path = 'r/';
  38389. let hierarchyStepSize = this.pcoGeometry.hierarchyStepSize;
  38390. let indices = this.name.substr(1);
  38391. let numParts = Math.floor(indices.length / hierarchyStepSize);
  38392. for (let i = 0; i < numParts; i++) {
  38393. path += indices.substr(i * hierarchyStepSize, hierarchyStepSize) + '/';
  38394. }
  38395. path = path.slice(0, -1);
  38396. return path;
  38397. }
  38398. addChild(child) {
  38399. this.children[child.index] = child;
  38400. child.parent = this;
  38401. }
  38402. load(){
  38403. if (this.loading === true || this.loaded === true || Potree.numNodesLoading >= Potree.maxNodesLoading) {
  38404. return;
  38405. }
  38406. this.loading = true;
  38407. Potree.numNodesLoading++;
  38408. if (this.pcoGeometry.loader.version.equalOrHigher('1.5')) {
  38409. if ((this.level % this.pcoGeometry.hierarchyStepSize) === 0 && this.hasChildren) {
  38410. this.loadHierachyThenPoints();
  38411. } else {
  38412. this.loadPoints();
  38413. }
  38414. } else {
  38415. this.loadPoints();
  38416. }
  38417. }
  38418. loadPoints(){
  38419. this.pcoGeometry.loader.load(this);
  38420. }
  38421. loadHierachyThenPoints(){
  38422. let node = this;
  38423. // load hierarchy
  38424. let callback = function (node, hbuffer) {
  38425. let tStart = performance.now();
  38426. let view = new DataView(hbuffer);
  38427. let stack = [];
  38428. let children = view.getUint8(0);
  38429. let numPoints = view.getUint32(1, true);
  38430. node.numPoints = numPoints;
  38431. stack.push({children: children, numPoints: numPoints, name: node.name});
  38432. let decoded = [];
  38433. let offset = 5;
  38434. while (stack.length > 0) {
  38435. let snode = stack.shift();
  38436. let mask = 1;
  38437. for (let i = 0; i < 8; i++) {
  38438. if ((snode.children & mask) !== 0) {
  38439. let childName = snode.name + i;
  38440. let childChildren = view.getUint8(offset);
  38441. let childNumPoints = view.getUint32(offset + 1, true);
  38442. stack.push({children: childChildren, numPoints: childNumPoints, name: childName});
  38443. decoded.push({children: childChildren, numPoints: childNumPoints, name: childName});
  38444. offset += 5;
  38445. }
  38446. mask = mask * 2;
  38447. }
  38448. if (offset === hbuffer.byteLength) {
  38449. break;
  38450. }
  38451. }
  38452. // console.log(decoded);
  38453. let nodes = {};
  38454. nodes[node.name] = node;
  38455. let pco = node.pcoGeometry;
  38456. for (let i = 0; i < decoded.length; i++) {
  38457. let name = decoded[i].name;
  38458. let decodedNumPoints = decoded[i].numPoints;
  38459. let index = parseInt(name.charAt(name.length - 1));
  38460. let parentName = name.substring(0, name.length - 1);
  38461. let parentNode = nodes[parentName];
  38462. let level = name.length - 1;
  38463. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  38464. let currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  38465. currentNode.level = level;
  38466. currentNode.numPoints = decodedNumPoints;
  38467. currentNode.hasChildren = decoded[i].children > 0;
  38468. currentNode.spacing = pco.spacing / Math.pow(2, level);
  38469. parentNode.addChild(currentNode);
  38470. nodes[name] = currentNode;
  38471. }
  38472. let duration = performance.now() - tStart;
  38473. if(duration > 5){
  38474. let msg = `duration: ${duration}ms, numNodes: ${decoded.length}`;
  38475. console.log(msg);
  38476. }
  38477. node.loadPoints();
  38478. };
  38479. if ((node.level % node.pcoGeometry.hierarchyStepSize) === 0) {
  38480. // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc";
  38481. let hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc';
  38482. let xhr = XHRFactory.createXMLHttpRequest();
  38483. xhr.open('GET', hurl, true);
  38484. xhr.responseType = 'arraybuffer';
  38485. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  38486. xhr.onreadystatechange = () => {
  38487. if (xhr.readyState === 4) {
  38488. if (xhr.status === 200 || xhr.status === 0) {
  38489. let hbuffer = xhr.response;
  38490. callback(node, hbuffer);
  38491. } else {
  38492. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl);
  38493. Potree.numNodesLoading--;
  38494. }
  38495. }
  38496. };
  38497. try {
  38498. xhr.send(null);
  38499. } catch (e) {
  38500. console.log('fehler beim laden der punktwolke: ' + e);
  38501. }
  38502. }
  38503. }
  38504. getNumPoints(){
  38505. return this.numPoints;
  38506. }
  38507. dispose(){
  38508. if (this.geometry && this.parent != null) {
  38509. this.geometry.dispose();
  38510. this.geometry = null;
  38511. this.loaded = false;
  38512. this.dispatchEvent( { type: 'dispose' } );
  38513. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  38514. let handler = this.oneTimeDisposeHandlers[i];
  38515. handler();
  38516. }
  38517. this.oneTimeDisposeHandlers = [];
  38518. }
  38519. }
  38520. }
  38521. PointCloudOctreeGeometryNode.IDCount = 0;
  38522. // -------------------------------------------
  38523. // to get a ready to use gradient array from a chroma.js gradient:
  38524. // http://gka.github.io/chroma.js/
  38525. // -------------------------------------------
  38526. //
  38527. // let stops = [];
  38528. // for(let i = 0; i <= 10; i++){
  38529. // let range = chroma.scale(['yellow', 'navy']).mode('lch').domain([10,0])(i)._rgb
  38530. // .slice(0, 3)
  38531. // .map(v => (v / 255).toFixed(4))
  38532. // .join(", ");
  38533. //
  38534. // let line = `[${i / 10}, new THREE.Color(${range})],`;
  38535. //
  38536. // stops.push(line);
  38537. // }
  38538. // stops.join("\n");
  38539. //
  38540. //
  38541. //
  38542. // -------------------------------------------
  38543. // to get a ready to use gradient array from matplotlib:
  38544. // -------------------------------------------
  38545. // import matplotlib.pyplot as plt
  38546. // import matplotlib.colors as colors
  38547. //
  38548. // norm = colors.Normalize(vmin=0,vmax=1)
  38549. // cmap = plt.cm.viridis
  38550. //
  38551. // for i in range(0,11):
  38552. // u = i / 10
  38553. // rgb = cmap(norm(u))[0:3]
  38554. // rgb = ["{0:.3f}".format(v) for v in rgb]
  38555. // rgb = "[" + str(u) + ", new THREE.Color(" + ", ".join(rgb) + ")],"
  38556. // print(rgb)
  38557. let Gradients = {
  38558. // From chroma spectral http://gka.github.io/chroma.js/
  38559. SPECTRAL: [
  38560. [0, new Color(0.3686, 0.3098, 0.6353)],
  38561. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  38562. [0.2, new Color(0.4000, 0.7608, 0.6471)],
  38563. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  38564. [0.4, new Color(0.9020, 0.9608, 0.5961)],
  38565. [0.5, new Color(1.0000, 1.0000, 0.7490)],
  38566. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  38567. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  38568. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  38569. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  38570. [1, new Color(0.6196, 0.0039, 0.2588)]
  38571. ],
  38572. PLASMA: [
  38573. [0.0, new Color(0.241, 0.015, 0.610)],
  38574. [0.1, new Color(0.387, 0.001, 0.654)],
  38575. [0.2, new Color(0.524, 0.025, 0.653)],
  38576. [0.3, new Color(0.651, 0.125, 0.596)],
  38577. [0.4, new Color(0.752, 0.227, 0.513)],
  38578. [0.5, new Color(0.837, 0.329, 0.431)],
  38579. [0.6, new Color(0.907, 0.435, 0.353)],
  38580. [0.7, new Color(0.963, 0.554, 0.272)],
  38581. [0.8, new Color(0.992, 0.681, 0.195)],
  38582. [0.9, new Color(0.987, 0.822, 0.144)],
  38583. [1.0, new Color(0.940, 0.975, 0.131)]
  38584. ],
  38585. YELLOW_GREEN: [
  38586. [0, new Color(0.1647, 0.2824, 0.3451)],
  38587. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  38588. [0.2, new Color(0.0610, 0.4319, 0.4864)],
  38589. [0.3, new Color(0.0000, 0.5099, 0.5319)],
  38590. [0.4, new Color(0.0000, 0.5881, 0.5569)],
  38591. [0.5, new Color(0.1370, 0.6650, 0.5614)],
  38592. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  38593. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  38594. [0.8, new Color(0.6102, 0.8748, 0.4850)],
  38595. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  38596. [1, new Color(0.9804, 0.9804, 0.4314)]
  38597. ],
  38598. VIRIDIS: [
  38599. [0.0, new Color(0.267, 0.005, 0.329)],
  38600. [0.1, new Color(0.283, 0.141, 0.458)],
  38601. [0.2, new Color(0.254, 0.265, 0.530)],
  38602. [0.3, new Color(0.207, 0.372, 0.553)],
  38603. [0.4, new Color(0.164, 0.471, 0.558)],
  38604. [0.5, new Color(0.128, 0.567, 0.551)],
  38605. [0.6, new Color(0.135, 0.659, 0.518)],
  38606. [0.7, new Color(0.267, 0.749, 0.441)],
  38607. [0.8, new Color(0.478, 0.821, 0.318)],
  38608. [0.9, new Color(0.741, 0.873, 0.150)],
  38609. [1.0, new Color(0.993, 0.906, 0.144)]
  38610. ],
  38611. INFERNO: [
  38612. [0.0, new Color(0.077, 0.042, 0.206)],
  38613. [0.1, new Color(0.225, 0.036, 0.388)],
  38614. [0.2, new Color(0.373, 0.074, 0.432)],
  38615. [0.3, new Color(0.522, 0.128, 0.420)],
  38616. [0.4, new Color(0.665, 0.182, 0.370)],
  38617. [0.5, new Color(0.797, 0.255, 0.287)],
  38618. [0.6, new Color(0.902, 0.364, 0.184)],
  38619. [0.7, new Color(0.969, 0.516, 0.063)],
  38620. [0.8, new Color(0.988, 0.683, 0.072)],
  38621. [0.9, new Color(0.961, 0.859, 0.298)],
  38622. [1.0, new Color(0.988, 0.998, 0.645)]
  38623. ],
  38624. GRAYSCALE: [
  38625. [0, new Color(0, 0, 0)],
  38626. [1, new Color(1, 1, 1)]
  38627. ],
  38628. // 16 samples of the TURBU color scheme
  38629. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  38630. // original file licensed under Apache-2.0
  38631. TURBO: [
  38632. [0.00, new Color(0.18995, 0.07176, 0.23217)],
  38633. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  38634. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  38635. [0.20, new Color(0.25862, 0.57958, 0.99876)],
  38636. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  38637. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  38638. [0.40, new Color(0.19659, 0.94901, 0.59466)],
  38639. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  38640. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  38641. [0.60, new Color(0.80473, 0.92452, 0.20459)],
  38642. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  38643. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  38644. [0.80, new Color(0.9836, 0.49291, 0.12849)],
  38645. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  38646. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  38647. [1.00, new Color(0.66449, 0.08436, 0.00424)],
  38648. ],
  38649. RAINBOW: [
  38650. [0, new Color(0.278, 0, 0.714)],
  38651. [1 / 6, new Color(0, 0, 1)],
  38652. [2 / 6, new Color(0, 1, 1)],
  38653. [3 / 6, new Color(0, 1, 0)],
  38654. [4 / 6, new Color(1, 1, 0)],
  38655. [5 / 6, new Color(1, 0.64, 0)],
  38656. [1, new Color(1, 0, 0)]
  38657. ],
  38658. CONTOUR: [
  38659. [0.00, new Color(0, 0, 0)],
  38660. [0.03, new Color(0, 0, 0)],
  38661. [0.04, new Color(1, 1, 1)],
  38662. [1.00, new Color(1, 1, 1)]
  38663. ],
  38664. };
  38665. let Shaders = {};
  38666. Shaders["pointcloud_new.vs"] = `
  38667. precision highp float;
  38668. precision highp int;
  38669. #define max_clip_polygons 8
  38670. #define PI 3.141592653589793
  38671. #if defined(usePanoMap)
  38672. uniform samplerCube pano0Map; //随便设置一个samplerCube去使用都会让点云消失
  38673. uniform samplerCube pano1Map;
  38674. uniform float progress;
  38675. uniform float easeInOutRatio;
  38676. uniform vec3 pano0Position;
  38677. uniform mat4 pano0Matrix;
  38678. uniform vec3 pano1Position;
  38679. uniform mat4 pano1Matrix;
  38680. /*
  38681. varying vec3 vWorldPosition0;
  38682. varying vec3 vWorldPosition1;
  38683. */
  38684. #endif
  38685. //--------------
  38686. attribute vec3 position;
  38687. attribute vec3 color;
  38688. attribute float intensity;
  38689. attribute float classification;
  38690. attribute float returnNumber;
  38691. attribute float numberOfReturns;
  38692. attribute float pointSourceID;
  38693. attribute vec4 indices; //每个点的index
  38694. attribute float spacing;
  38695. attribute float gpsTime;
  38696. attribute vec3 normal;
  38697. attribute float aExtra;
  38698. uniform mat4 modelMatrix;
  38699. uniform mat4 modelViewMatrix;
  38700. uniform mat4 projectionMatrix;
  38701. uniform mat4 viewMatrix;
  38702. uniform mat4 uViewInv;
  38703. //uniform float uScreenWidth;
  38704. //uniform float uScreenHeight;
  38705. uniform vec2 resolution;
  38706. uniform float fov;
  38707. uniform float near;
  38708. uniform float far;
  38709. uniform bool uDebug;
  38710. uniform bool uUseOrthographicCamera;
  38711. uniform float uOrthoWidth;
  38712. uniform float uOrthoHeight;
  38713. #define CLIPTASK_NONE 0
  38714. #define CLIPTASK_HIGHLIGHT 1
  38715. #define CLIPTASK_SHOW_INSIDE 2
  38716. #define CLIPTASK_SHOW_OUTSIDE 3
  38717. #define CLIPMETHOD_INSIDE_ANY 0
  38718. #define CLIPMETHOD_INSIDE_ALL 1
  38719. //最外层裁剪(下载)
  38720. #if defined(bigClipInBox)
  38721. uniform mat4 clipBoxBig_in;
  38722. #endif
  38723. //内层裁剪
  38724. #if defined(num_in_clipboxes) && num_in_clipboxes > 0
  38725. uniform mat4 clipBoxes_in[num_in_clipboxes];
  38726. #endif
  38727. #if defined(num_out_clipboxes) && num_out_clipboxes > 0
  38728. uniform mat4 clipBoxes_out[num_out_clipboxes];
  38729. #endif
  38730. #if defined(num_clipspheres) && num_clipspheres > 0
  38731. uniform mat4 uClipSpheres[num_clipspheres];
  38732. #endif
  38733. #if defined(num_highlightBox) && num_highlightBox > 0
  38734. uniform mat4 boxes_highlight[num_highlightBox];
  38735. #endif
  38736. uniform float size;
  38737. uniform float minSize;
  38738. uniform float maxSize;
  38739. uniform float uPCIndex;
  38740. uniform float uOctreeSpacing;
  38741. uniform float uNodeSpacing;
  38742. uniform float uOctreeSize;
  38743. uniform vec3 uBBSize;
  38744. uniform float uLevel;
  38745. uniform float levelPercent;//add
  38746. uniform float uVNStart;
  38747. uniform bool uIsLeafNode;
  38748. uniform vec3 uColor;
  38749. uniform float uOpacity;
  38750. varying float vOpacity; //add
  38751. uniform vec2 elevationRange;
  38752. uniform vec2 intensityRange;
  38753. uniform vec2 uFilterReturnNumberRange;
  38754. uniform vec2 uFilterNumberOfReturnsRange;
  38755. uniform vec2 uFilterPointSourceIDClipRange;
  38756. uniform vec2 uFilterGPSTimeClipRange;
  38757. //uniform float ufilterByNormalThreshold;
  38758. uniform float uGpsScale;
  38759. uniform float uGpsOffset;
  38760. uniform vec2 uNormalizedGpsBufferRange;
  38761. uniform vec3 uIntensity_gbc;
  38762. uniform vec3 uRGB_gbc;
  38763. uniform vec3 uExtra_gbc;
  38764. uniform float uTransition;
  38765. uniform float wRGB;
  38766. uniform float wIntensity;
  38767. uniform float wElevation;
  38768. uniform float wClassification;
  38769. uniform float wReturnNumber;
  38770. uniform float wSourceID;
  38771. uniform vec2 uExtraNormalizedRange;
  38772. uniform vec2 uExtraRange;
  38773. uniform float uExtraScale;
  38774. uniform float uExtraOffset;
  38775. uniform vec3 uShadowColor;
  38776. uniform sampler2D visibleNodes;
  38777. uniform sampler2D gradient;
  38778. uniform sampler2D classificationLUT;
  38779. #if defined(color_type_matcap)
  38780. uniform sampler2D matcapTextureUniform;
  38781. #endif
  38782. uniform bool backfaceCulling;
  38783. #if defined(num_shadowmaps) && num_shadowmaps > 0
  38784. uniform sampler2D uShadowMap[num_shadowmaps];
  38785. uniform mat4 uShadowWorldView[num_shadowmaps];
  38786. uniform mat4 uShadowProj[num_shadowmaps];
  38787. #endif
  38788. varying vec3 vColor;
  38789. varying float vLogDepth;
  38790. varying vec3 vViewPosition;
  38791. varying float vRadius;
  38792. varying float vPointSize;
  38793. float round(float number){
  38794. return floor(number + 0.5);
  38795. }
  38796. //
  38797. // ### ######## ### ######## ######## #### ## ## ######## ###### #### ######## ######## ######
  38798. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  38799. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  38800. // ## ## ## ## ## ## ######## ## ## ## ## ###### ###### ## ## ###### ######
  38801. // ######### ## ## ######### ## ## ## ## ## ## ## ## ## ## ##
  38802. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  38803. // ## ## ######## ## ## ## ## #### ### ######## ###### #### ######## ######## ######
  38804. //
  38805. // ---------------------
  38806. // OCTREE
  38807. // ---------------------
  38808. #if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_octree)
  38809. /**
  38810. * number of 1-bits up to inclusive index position
  38811. * number is treated as if it were an integer in the range 0-255
  38812. *
  38813. */
  38814. int numberOfOnes(int number, int index){
  38815. int numOnes = 0;
  38816. int tmp = 128;
  38817. for(int i = 7; i >= 0; i--){
  38818. if(number >= tmp){
  38819. number = number - tmp;
  38820. if(i <= index){
  38821. numOnes++;
  38822. }
  38823. }
  38824. tmp = tmp / 2;
  38825. }
  38826. return numOnes;
  38827. }
  38828. /**
  38829. * checks whether the bit at index is 1
  38830. * number is treated as if it were an integer in the range 0-255
  38831. *
  38832. */
  38833. bool isBitSet(int number, int index){
  38834. // weird multi else if due to lack of proper array, int and bitwise support in WebGL 1.0
  38835. int powi = 1;
  38836. if(index == 0){
  38837. powi = 1;
  38838. }else if(index == 1){
  38839. powi = 2;
  38840. }else if(index == 2){
  38841. powi = 4;
  38842. }else if(index == 3){
  38843. powi = 8;
  38844. }else if(index == 4){
  38845. powi = 16;
  38846. }else if(index == 5){
  38847. powi = 32;
  38848. }else if(index == 6){
  38849. powi = 64;
  38850. }else if(index == 7){
  38851. powi = 128;
  38852. }else{
  38853. return false;
  38854. }
  38855. int ndp = number / powi;
  38856. return mod(float(ndp), 2.0) != 0.0;
  38857. }
  38858. /**
  38859. * find the LOD at the point position
  38860. */
  38861. float getLOD(){//////
  38862. vec3 offset = vec3(0.0, 0.0, 0.0);
  38863. int iOffset = int(uVNStart);
  38864. float depth = uLevel;
  38865. for(float i = 0.0; i <= 30.0; i++){
  38866. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  38867. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  38868. index3d = floor(index3d + 0.5);
  38869. int index = int(round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));
  38870. vec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));
  38871. int mask = int(round(value.r * 255.0));
  38872. if(isBitSet(mask, index)){
  38873. // there are more visible child nodes at this position
  38874. int advanceG = int(round(value.g * 255.0)) * 256;
  38875. int advanceB = int(round(value.b * 255.0));
  38876. int advanceChild = numberOfOnes(mask, index - 1);
  38877. int advance = advanceG + advanceB + advanceChild;
  38878. iOffset = iOffset + advance;
  38879. depth++;
  38880. }else{
  38881. // no more visible child nodes at this position
  38882. //return value.a * 255.0;
  38883. float lodOffset = (255.0 * value.a) / 10.0 - 10.0;
  38884. return depth + lodOffset;
  38885. }
  38886. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  38887. }
  38888. return depth;
  38889. }
  38890. float getSpacing(){
  38891. vec3 offset = vec3(0.0, 0.0, 0.0);
  38892. int iOffset = int(uVNStart);
  38893. float depth = uLevel;
  38894. float spacing = uNodeSpacing;
  38895. for(float i = 0.0; i <= 30.0; i++){
  38896. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  38897. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  38898. index3d = floor(index3d + 0.5);
  38899. int index = int(round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));
  38900. vec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));
  38901. int mask = int(round(value.r * 255.0));
  38902. float spacingFactor = value.a;
  38903. if(i > 0.0){
  38904. spacing = spacing / (255.0 * spacingFactor);
  38905. }
  38906. if(isBitSet(mask, index)){
  38907. // there are more visible child nodes at this position
  38908. int advanceG = int(round(value.g * 255.0)) * 256;
  38909. int advanceB = int(round(value.b * 255.0));
  38910. int advanceChild = numberOfOnes(mask, index - 1);
  38911. int advance = advanceG + advanceB + advanceChild;
  38912. iOffset = iOffset + advance;
  38913. //spacing = spacing / (255.0 * spacingFactor);
  38914. //spacing = spacing / 3.0;
  38915. depth++;
  38916. }else{
  38917. // no more visible child nodes at this position
  38918. return spacing;
  38919. }
  38920. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  38921. }
  38922. return spacing;
  38923. }
  38924. float getPointSizeAttenuation(){
  38925. return pow(2.0, getLOD());
  38926. }
  38927. #endif
  38928. // ---------------------
  38929. // KD-TREE
  38930. // ---------------------
  38931. #if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_kdtree)
  38932. float getLOD(){
  38933. vec3 offset = vec3(0.0, 0.0, 0.0);
  38934. float iOffset = 0.0;
  38935. float depth = 0.0;
  38936. vec3 size = uBBSize;
  38937. vec3 pos = position;
  38938. for(float i = 0.0; i <= 1000.0; i++){
  38939. vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));
  38940. int children = int(value.r * 255.0);
  38941. float next = value.g * 255.0;
  38942. int split = int(value.b * 255.0);
  38943. if(next == 0.0){
  38944. return depth;
  38945. }
  38946. vec3 splitv = vec3(0.0, 0.0, 0.0);
  38947. if(split == 1){
  38948. splitv.x = 1.0;
  38949. }else if(split == 2){
  38950. splitv.y = 1.0;
  38951. }else if(split == 4){
  38952. splitv.z = 1.0;
  38953. }
  38954. iOffset = iOffset + next;
  38955. float factor = length(pos * splitv / size);
  38956. if(factor < 0.5){
  38957. // left
  38958. if(children == 0 || children == 2){
  38959. return depth;
  38960. }
  38961. }else{
  38962. // right
  38963. pos = pos - size * splitv * 0.5;
  38964. if(children == 0 || children == 1){
  38965. return depth;
  38966. }
  38967. if(children == 3){
  38968. iOffset = iOffset + 1.0;
  38969. }
  38970. }
  38971. size = size * ((1.0 - (splitv + 1.0) / 2.0) + 0.5);
  38972. depth++;
  38973. }
  38974. return depth;
  38975. }
  38976. float getPointSizeAttenuation(){
  38977. return 0.5 * pow(1.3, getLOD());
  38978. }
  38979. #endif
  38980. //
  38981. // ### ######## ######## ######## #### ######## ## ## ######## ######## ######
  38982. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  38983. // ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  38984. // ## ## ## ## ######## ## ######## ## ## ## ###### ######
  38985. // ######### ## ## ## ## ## ## ## ## ## ## ## ##
  38986. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  38987. // ## ## ## ## ## ## #### ######## ####### ## ######## ######
  38988. //
  38989. // formula adapted from: http://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-5-contrast-adjustment/
  38990. float getContrastFactor(float contrast){
  38991. return (1.0158730158730156 * (contrast + 1.0)) / (1.0158730158730156 - contrast);
  38992. }
  38993. vec3 getRGB(){
  38994. vec3 rgb = color;
  38995. rgb = pow(rgb, vec3(uRGB_gbc.x));
  38996. rgb = rgb + uRGB_gbc.y;
  38997. rgb = (rgb - 0.5) * getContrastFactor(uRGB_gbc.z) + 0.5;
  38998. rgb = clamp(rgb, 0.0, 1.0);
  38999. return rgb;
  39000. }
  39001. float getIntensity(){
  39002. float w = (intensity - intensityRange.x) / (intensityRange.y - intensityRange.x);
  39003. w = pow(w, uIntensity_gbc.x);
  39004. w = w + uIntensity_gbc.y;
  39005. w = (w - 0.5) * getContrastFactor(uIntensity_gbc.z) + 0.5;
  39006. w = clamp(w, 0.0, 1.0);
  39007. return w;
  39008. }
  39009. vec3 getGpsTime(){
  39010. float w = (gpsTime + uGpsOffset) * uGpsScale;
  39011. vec3 c = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  39012. // vec2 r = uNormalizedGpsBufferRange;
  39013. // float w = gpsTime * (r.y - r.x) + r.x;
  39014. // w = clamp(w, 0.0, 1.0);
  39015. // vec3 c = texture2D(gradient, vec2(w,1.0-w)).rgb;
  39016. return c;
  39017. }
  39018. vec3 getElevation(){
  39019. vec4 world = modelMatrix * vec4( position, 1.0 );
  39020. float w = (world.z - elevationRange.x) / (elevationRange.y - elevationRange.x);
  39021. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  39022. return cElevation;
  39023. }
  39024. vec4 getClassification(){
  39025. vec2 uv = vec2(classification / 255.0, 0.5);
  39026. vec4 classColor = texture2D(classificationLUT, uv);
  39027. return classColor;
  39028. }
  39029. vec3 getReturns(){
  39030. // 0b 00_000_111
  39031. float rn = mod(returnNumber, 8.0);
  39032. // 0b 00_111_000
  39033. float nr = mod(returnNumber / 8.0, 8.0);
  39034. if(nr <= 1.0){
  39035. return vec3(1.0, 0.0, 0.0);
  39036. }else{
  39037. return vec3(0.0, 1.0, 0.0);
  39038. }
  39039. // return vec3(nr / 4.0, 0.0, 0.0);
  39040. // if(nr == 1.0){
  39041. // return vec3(1.0, 1.0, 0.0);
  39042. // }else{
  39043. // if(rn == 1.0){
  39044. // return vec3(1.0, 0.0, 0.0);
  39045. // }else if(rn == nr){
  39046. // return vec3(0.0, 0.0, 1.0);
  39047. // }else{
  39048. // return vec3(0.0, 1.0, 0.0);
  39049. // }
  39050. // }
  39051. // if(numberOfReturns == 1.0){
  39052. // return vec3(1.0, 1.0, 0.0);
  39053. // }else{
  39054. // if(returnNumber == 1.0){
  39055. // return vec3(1.0, 0.0, 0.0);
  39056. // }else if(returnNumber == numberOfReturns){
  39057. // return vec3(0.0, 0.0, 1.0);
  39058. // }else{
  39059. // return vec3(0.0, 1.0, 0.0);
  39060. // }
  39061. // }
  39062. }
  39063. vec3 getReturnNumber(){
  39064. if(numberOfReturns == 1.0){
  39065. return vec3(1.0, 1.0, 0.0);
  39066. }else{
  39067. if(returnNumber == 1.0){
  39068. return vec3(1.0, 0.0, 0.0);
  39069. }else if(returnNumber == numberOfReturns){
  39070. return vec3(0.0, 0.0, 1.0);
  39071. }else{
  39072. return vec3(0.0, 1.0, 0.0);
  39073. }
  39074. }
  39075. }
  39076. vec3 getNumberOfReturns(){
  39077. float value = numberOfReturns;
  39078. float w = value / 6.0;
  39079. vec3 color = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  39080. return color;
  39081. }
  39082. vec3 getSourceID(){
  39083. float w = mod(pointSourceID, 10.0) / 10.0;
  39084. return texture2D(gradient, vec2(w,1.0 - w)).rgb;
  39085. }
  39086. vec3 getCompositeColor(){
  39087. vec3 c;
  39088. float w;
  39089. c += wRGB * getRGB();
  39090. w += wRGB;
  39091. c += wIntensity * getIntensity() * vec3(1.0, 1.0, 1.0);
  39092. w += wIntensity;
  39093. c += wElevation * getElevation();
  39094. w += wElevation;
  39095. c += wReturnNumber * getReturnNumber();
  39096. w += wReturnNumber;
  39097. c += wSourceID * getSourceID();
  39098. w += wSourceID;
  39099. vec4 cl = wClassification * getClassification();
  39100. c += cl.a * cl.rgb;
  39101. w += wClassification * cl.a;
  39102. c = c / w;
  39103. if(w == 0.0){
  39104. //c = color;
  39105. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  39106. }
  39107. return c;
  39108. }
  39109. vec3 getNormal(){
  39110. //vec3 n_hsv = vec3( modelMatrix * vec4( normal, 0.0 )) * 0.5 + 0.5; // (n_world.xyz + vec3(1.,1.,1.)) / 2.;
  39111. vec3 n_view = normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );
  39112. return n_view;
  39113. }
  39114. bool applyBackfaceCulling() {
  39115. // Black not facing vertices / Backface culling
  39116. vec3 e = normalize(vec3(modelViewMatrix * vec4( position, 1. )));
  39117. vec3 n = getNormal(); // normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );
  39118. if((uUseOrthographicCamera && n.z <= 0.) || (!uUseOrthographicCamera && dot( n, e ) >= 0.)) {
  39119. return true;
  39120. } else {
  39121. return false;
  39122. }
  39123. }
  39124. #if defined(color_type_matcap)
  39125. // Matcap Material
  39126. vec3 getMatcap(){
  39127. vec3 eye = normalize( vec3( modelViewMatrix * vec4( position, 1. ) ) );
  39128. if(uUseOrthographicCamera) {
  39129. eye = vec3(0., 0., -1.);
  39130. }
  39131. vec3 r_en = reflect( eye, getNormal() ); // or r_en = e - 2. * dot( n, e ) * n;
  39132. float m = 2. * sqrt(pow( r_en.x, 2. ) + pow( r_en.y, 2. ) + pow( r_en.z + 1., 2. ));
  39133. vec2 vN = r_en.xy / m + .5;
  39134. return texture2D(matcapTextureUniform, vN).rgb;
  39135. }
  39136. #endif
  39137. vec3 getExtra(){
  39138. float w = (aExtra + uExtraOffset) * uExtraScale;
  39139. w = clamp(w, 0.0, 1.0);
  39140. vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  39141. // vec2 r = uExtraNormalizedRange;
  39142. // float w = aExtra * (r.y - r.x) + r.x;
  39143. // w = (w - uExtraRange.x) / (uExtraRange.y - uExtraRange.x);
  39144. // w = clamp(w, 0.0, 1.0);
  39145. // vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  39146. return color;
  39147. }
  39148. vec3 getColor(){
  39149. vec3 color;
  39150. #ifdef color_type_rgba
  39151. color = getRGB();
  39152. #elif defined color_type_height || defined color_type_elevation
  39153. color = getElevation();
  39154. #elif defined color_type_rgb_height
  39155. vec3 cHeight = getElevation();
  39156. color = (1.0 - uTransition) * getRGB() + uTransition * cHeight;
  39157. #elif defined color_type_depth
  39158. float linearDepth = gl_Position.w;
  39159. float expDepth = (gl_Position.z / gl_Position.w) * 0.5 + 0.5;
  39160. color = vec3(linearDepth, expDepth, 0.0);
  39161. //color = vec3(1.0, 0.5, 0.3);
  39162. #elif defined color_type_intensity
  39163. float w = getIntensity();
  39164. color = vec3(w, w, w);
  39165. #elif defined color_type_gps_time
  39166. color = getGpsTime();
  39167. #elif defined color_type_intensity_gradient
  39168. float w = getIntensity();
  39169. color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  39170. #elif defined color_type_color
  39171. color = uColor;
  39172. #elif defined color_type_level_of_detail
  39173. float depth = getLOD();
  39174. float w = depth / 10.0;
  39175. color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  39176. #elif defined color_type_indices
  39177. color = indices.rgb;
  39178. #elif defined color_type_classification
  39179. vec4 cl = getClassification();
  39180. color = cl.rgb;
  39181. #elif defined color_type_return_number
  39182. color = getReturnNumber();
  39183. #elif defined color_type_returns
  39184. color = getReturns();
  39185. #elif defined color_type_number_of_returns
  39186. color = getNumberOfReturns();
  39187. #elif defined color_type_source_id
  39188. color = getSourceID();
  39189. #elif defined color_type_point_source_id
  39190. color = getSourceID();
  39191. #elif defined color_type_normal
  39192. color = (modelMatrix * vec4(normal, 0.0)).xyz;
  39193. #elif defined color_type_phong
  39194. color = color;
  39195. #elif defined color_type_composite
  39196. color = getCompositeColor();
  39197. #elif defined color_type_matcap
  39198. color = getMatcap();
  39199. #else
  39200. color = getExtra();
  39201. #endif
  39202. if (backfaceCulling && applyBackfaceCulling()){
  39203. //color = vec3(0.);
  39204. }
  39205. //applyBackfaceCulling直接返回false或者注释color = vec3(0.);都没问题
  39206. return color;
  39207. }
  39208. float getPointSize(){
  39209. float pointSize = 1.0;
  39210. float maxSize_ = maxSize;
  39211. float slope = tan(fov / 2.0);
  39212. float projFactor = -0.5 * resolution.y / (slope * vViewPosition.z);
  39213. /*
  39214. float scale = length(
  39215. modelViewMatrix * vec4(0, 0, 0, 1) -
  39216. modelViewMatrix * vec4(uOctreeSpacing, 0, 0, 1)
  39217. ) / uOctreeSpacing;
  39218. projFactor = projFactor * scale;
  39219. */
  39220. float r = uOctreeSpacing * 1.7;
  39221. //vRadius = r;
  39222. #if defined fixed_point_size
  39223. pointSize = size;
  39224. #elif defined attenuated_point_size
  39225. if(uUseOrthographicCamera){
  39226. //pointSize = size * 100.0; //加个乘数
  39227. pointSize = size / uOrthoWidth * resolution.x; //改成近似adaptive_point_size根据窗口缩放
  39228. maxSize_ = 3.0; //for panoEditor, when zoom in, need more details, rather than always same size
  39229. }else{ //近大远小,模拟真实mesh,边缘放大
  39230. //pointSize = size * spacing * projFactor; //spacing是attribute 为空 如果有这个值就能更自适应填补
  39231. //pointSize = size * uOctreeSpacing * projFactor / 18.0; //直接用cloud的spacing里,不过因为都一样所以可能没有什么意义
  39232. //pointSize = pointSize * projFactor;
  39233. pointSize = size * projFactor ;
  39234. }
  39235. #elif defined adaptive_point_size
  39236. if(uUseOrthographicCamera) {
  39237. float worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();
  39238. pointSize = (worldSpaceSize / uOrthoWidth) * resolution.x; //uScreenWidth;
  39239. maxSize_ = 3.0;
  39240. } else {
  39241. float worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();
  39242. pointSize = worldSpaceSize * projFactor;
  39243. }
  39244. #endif
  39245. pointSize = max(minSize, pointSize);
  39246. pointSize = min(maxSize_, pointSize);
  39247. vRadius = pointSize / projFactor;
  39248. return pointSize;
  39249. }
  39250. bool insideBox(mat4 clipBox){//add
  39251. vec4 clipPosition = clipBox * modelMatrix * vec4( position, 1.0 );
  39252. bool inside = -0.5 <= clipPosition.x && clipPosition.x <= 0.5;
  39253. inside = inside && -0.5 <= clipPosition.y && clipPosition.y <= 0.5;
  39254. inside = inside && -0.5 <= clipPosition.z && clipPosition.z <= 0.5;
  39255. return inside;
  39256. }
  39257. void doClipping(){
  39258. {
  39259. vec4 cl = getClassification();
  39260. if(cl.a == 0.0){
  39261. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  39262. return;
  39263. }
  39264. }
  39265. #if defined(clip_return_number_enabled)
  39266. { // return number filter
  39267. vec2 range = uFilterReturnNumberRange;
  39268. if(returnNumber < range.x || returnNumber > range.y){
  39269. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  39270. return;
  39271. }
  39272. }
  39273. #endif
  39274. #if defined(clip_number_of_returns_enabled)
  39275. { // number of return filter
  39276. vec2 range = uFilterNumberOfReturnsRange;
  39277. if(numberOfReturns < range.x || numberOfReturns > range.y){
  39278. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  39279. return;
  39280. }
  39281. }
  39282. #endif
  39283. #if defined(clip_gps_enabled)
  39284. { // GPS time filter
  39285. float time = (gpsTime + uGpsOffset) * uGpsScale;
  39286. vec2 range = uFilterGPSTimeClipRange;
  39287. if(time < range.x || time > range.y){
  39288. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  39289. return;
  39290. }
  39291. }
  39292. #endif
  39293. #if defined(clip_point_source_id_enabled)
  39294. { // point source id filter
  39295. vec2 range = uFilterPointSourceIDClipRange;
  39296. if(pointSourceID < range.x || pointSourceID > range.y){
  39297. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  39298. return;
  39299. }
  39300. }
  39301. #endif
  39302. //总共三种box : 最外层可见、内层可见和不可见(外层可见和内层可见是交集,内层可见和内层不可见是并集)
  39303. #if defined(bigClipInBox)
  39304. if(!insideBox(clipBoxBig_in)){
  39305. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  39306. return;;
  39307. }
  39308. #endif
  39309. #if defined(num_in_clipboxes) && num_in_clipboxes > 0
  39310. //当有可见box时,需要在任一可见box内才可见
  39311. bool visi1 = false;
  39312. for(int i = 0; i < num_in_clipboxes; i++){
  39313. if(insideBox(clipBoxes_in[i])){
  39314. visi1 = true;
  39315. break;
  39316. }
  39317. }
  39318. if(!visi1){
  39319. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  39320. return;
  39321. }
  39322. #endif
  39323. #if defined(num_out_clipboxes) && num_out_clipboxes > 0
  39324. //当有不可见box时,不在所有不可见box内才可见
  39325. bool visi2 = true;
  39326. for(int i = 0; i < num_out_clipboxes; i++){
  39327. if(insideBox(clipBoxes_out[i])){
  39328. visi2 = false;
  39329. break;
  39330. }
  39331. }
  39332. if(!visi2){
  39333. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  39334. return;
  39335. }
  39336. #endif
  39337. #if defined(num_highlightBox) && num_highlightBox > 0
  39338. //当有高亮box时,需要在任一可见高亮内都高宽
  39339. bool highlight = false;
  39340. for(int i = 0; i < num_highlightBox; i++){
  39341. if(insideBox(boxes_highlight[i])){
  39342. highlight = true;
  39343. break;
  39344. }
  39345. }
  39346. if(highlight){
  39347. vColor.r += 0.5;
  39348. }
  39349. #endif
  39350. }
  39351. //
  39352. // ## ## ### #### ## ##
  39353. // ### ### ## ## ## ### ##
  39354. // #### #### ## ## ## #### ##
  39355. // ## ### ## ## ## ## ## ## ##
  39356. // ## ## ######### ## ## ####
  39357. // ## ## ## ## ## ## ###
  39358. // ## ## ## ## #### ## ##
  39359. //
  39360. vec2 getSamplerCoord( vec3 direction )
  39361. {
  39362. direction = normalize(direction);
  39363. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  39364. float ty=acos(direction.z)/PI;
  39365. return vec2(tx,ty);
  39366. }
  39367. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  39368. {
  39369. float y = direction.y;
  39370. direction.y = direction.z;
  39371. direction.z = -y;
  39372. return direction;
  39373. }
  39374. void main() {
  39375. //bool filtered_by_normal = false;
  39376. float normalZ = 0.0;
  39377. #ifdef use_filter_by_normal
  39378. /*if(abs(getNormal().z) > 0.4) { //ufilterByNormalThreshold 暂定 3
  39379. // Move point outside clip space space to discard it.
  39380. //gl_Position = vec4(0.0, 0.0, 2.0, 1.0); //gl_Position的可视区域是 x,y,z都是[-1,1]
  39381. //return;
  39382. //filtered_by_normal = true; //标记一下。不直接不绘制,因为有的法线都是垂直向上
  39383. }*/
  39384. normalZ = abs(getNormal().z);
  39385. #endif
  39386. vec4 mvPosition = modelViewMatrix * vec4(position, 1.0 );
  39387. vViewPosition = mvPosition.xyz;
  39388. gl_Position = projectionMatrix * mvPosition;
  39389. vLogDepth = log2(-mvPosition.z);
  39390. // COLOR
  39391. //加-------------------
  39392. #if defined(usePanoMap)
  39393. vec4 worldPosition = modelMatrix * vec4(position, 1.0);
  39394. vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;
  39395. vec3 vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;
  39396. vWorldPosition0.x *= -1.0;
  39397. vWorldPosition0 = transformAxis(vWorldPosition0);
  39398. vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;
  39399. vec3 vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;
  39400. vWorldPosition1.x *= -1.0;
  39401. vWorldPosition1 = transformAxis(vWorldPosition1);
  39402. /*
  39403. vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);
  39404. vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz);
  39405. vec4 colorFromPano0 = texture2D(pano0Map,samplerCoord0);
  39406. vec4 colorFromPano1 = texture2D(pano1Map,samplerCoord1);
  39407. */
  39408. vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  39409. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  39410. vColor = mix(colorFromPano0,colorFromPano1,progress).xyz;
  39411. //float easeInOutRatio = 0.0; //缓冲,渐变点云到贴图的颜色
  39412. if(progress < easeInOutRatio){
  39413. float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;
  39414. vec3 vColor1 = getColor();
  39415. vColor = mix(vColor,vColor1,easeProgress);
  39416. }else if(progress > 1.0 - easeInOutRatio){
  39417. float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;
  39418. vec3 vColor1 = getColor();
  39419. vColor = mix(vColor,vColor1,easeProgress);
  39420. }
  39421. #else
  39422. vColor = getColor();
  39423. #endif
  39424. //-------------------
  39425. if(uOpacity>=1.0 || uUseOrthographicCamera){
  39426. vOpacity = uOpacity;
  39427. if(uOpacity<1.0){ //uUseOrthographicCamera
  39428. //防止缩小后点云几乎看不见
  39429. vOpacity *= 4.0-3.0 * levelPercent;
  39430. }
  39431. }else{ //#ifdef attenuated_opacity zoom不会改变z 所以这并不是用在分屏时候的
  39432. float v = -gl_Position.z-1.0 ; // 范围从-2到0, e的-2到0次方的范围是0.818到1
  39433. //vOpacity = uOpacity * exp(v/ (levelPercent * 20.0 ) );
  39434. //近处加深,远处变淡 gl_Position.z似乎朝向屏幕里为正
  39435. float r = clamp( pow(1.1, v/10.0 ), 0.1, 1.0 ); //除以的数字越大,近高远低的程度越小,范围越长。 程度太高远处单薄的区域看不见 pow的底数越大改变率越大
  39436. vOpacity = uOpacity * r ;
  39437. }
  39438. vOpacity *= max(0.3, pow((1.0 - normalZ),5.0));//垂直朝相机时降低透明度
  39439. //vOpacity = clamp(vOpacity, 0.0, 1.0);
  39440. // POINT SIZE
  39441. float pointSize = getPointSize();
  39442. gl_PointSize = pointSize;
  39443. vPointSize = pointSize;
  39444. // only for "replacing" approaches
  39445. // if(getLOD() != uLevel){
  39446. // gl_Position = vec4(10.0, 10.0, 10.0, 1.0);
  39447. // }
  39448. #if defined hq_depth_pass
  39449. float originalDepth = gl_Position.w;
  39450. float adjustedDepth = originalDepth + 2.0 * vRadius;
  39451. float adjust = adjustedDepth / originalDepth;
  39452. mvPosition.xyz = mvPosition.xyz * adjust;
  39453. gl_Position = projectionMatrix * mvPosition;
  39454. #endif
  39455. // CLIPPING
  39456. doClipping();
  39457. #if defined(num_clipspheres) && num_clipspheres > 0
  39458. for(int i = 0; i < num_clipspheres; i++){
  39459. vec4 sphereLocal = uClipSpheres[i] * mvPosition;
  39460. float distance = length(sphereLocal.xyz);
  39461. if(distance < 1.0){
  39462. float w = distance;
  39463. vec3 cGradient = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  39464. vColor = cGradient;
  39465. //vColor = cGradient * 0.7 + vColor * 0.3;
  39466. }
  39467. }
  39468. #endif
  39469. #if defined(num_shadowmaps) && num_shadowmaps > 0
  39470. const float sm_near = 0.1;
  39471. const float sm_far = 10000.0;
  39472. for(int i = 0; i < num_shadowmaps; i++){
  39473. vec3 viewPos = (uShadowWorldView[i] * vec4(position, 1.0)).xyz;
  39474. float distanceToLight = abs(viewPos.z);
  39475. vec4 projPos = uShadowProj[i] * uShadowWorldView[i] * vec4(position, 1);
  39476. vec3 nc = projPos.xyz / projPos.w;
  39477. float u = nc.x * 0.5 + 0.5;
  39478. float v = nc.y * 0.5 + 0.5;
  39479. vec2 sampleStep = vec2(1.0 / (2.0*1024.0), 1.0 / (2.0*1024.0)) * 1.5;
  39480. vec2 sampleLocations[9];
  39481. sampleLocations[0] = vec2(0.0, 0.0);
  39482. sampleLocations[1] = sampleStep;
  39483. sampleLocations[2] = -sampleStep;
  39484. sampleLocations[3] = vec2(sampleStep.x, -sampleStep.y);
  39485. sampleLocations[4] = vec2(-sampleStep.x, sampleStep.y);
  39486. sampleLocations[5] = vec2(0.0, sampleStep.y);
  39487. sampleLocations[6] = vec2(0.0, -sampleStep.y);
  39488. sampleLocations[7] = vec2(sampleStep.x, 0.0);
  39489. sampleLocations[8] = vec2(-sampleStep.x, 0.0);
  39490. float visibleSamples = 0.0;
  39491. float numSamples = 0.0;
  39492. float bias = vRadius * 2.0;
  39493. for(int j = 0; j < 9; j++){
  39494. vec4 depthMapValue = texture2D(uShadowMap[i], vec2(u, v) + sampleLocations[j]);
  39495. float linearDepthFromSM = depthMapValue.x + bias;
  39496. float linearDepthFromViewer = distanceToLight;
  39497. if(linearDepthFromSM > linearDepthFromViewer){
  39498. visibleSamples += 1.0;
  39499. }
  39500. numSamples += 1.0;
  39501. }
  39502. float visibility = visibleSamples / numSamples;
  39503. 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){
  39504. //vColor = vec3(0.0, 0.0, 0.2);
  39505. }else{
  39506. //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);
  39507. vColor = vColor * visibility + vColor * uShadowColor * (1.0 - visibility);
  39508. }
  39509. }
  39510. #endif
  39511. }
  39512. `;
  39513. Shaders["pointcloud_new.fs"] = `
  39514. #if defined paraboloid_point_shape
  39515. #extension GL_EXT_frag_depth : enable
  39516. #endif
  39517. #define PI 3.141592653589793
  39518. precision highp float;
  39519. precision highp int;
  39520. /*
  39521. #if defined(usePanoMap)
  39522. uniform samplerCube pano0Map; //随便设置一个samplerCube去使用都会让点云消失
  39523. uniform samplerCube pano1Map;
  39524. uniform float progress;
  39525. uniform float easeInOutRatio;
  39526. uniform vec3 pano0Position;
  39527. uniform mat4 pano0Matrix;
  39528. uniform vec3 pano1Position;
  39529. uniform mat4 pano1Matrix;
  39530. varying vec3 vWorldPosition0;
  39531. varying vec3 vWorldPosition1;
  39532. #endif
  39533. */
  39534. //------------
  39535. uniform mat4 viewMatrix;
  39536. uniform mat4 uViewInv;
  39537. uniform mat4 uProjInv;
  39538. uniform vec3 cameraPosition;
  39539. uniform mat4 projectionMatrix;
  39540. //uniform float uOpacity;
  39541. varying float vOpacity; //add
  39542. uniform float blendHardness;
  39543. uniform float blendDepthSupplement;
  39544. uniform float fov;
  39545. uniform float uSpacing;
  39546. uniform float near;
  39547. uniform float far;
  39548. uniform float uPCIndex;
  39549. uniform float uScreenWidth;
  39550. uniform float uScreenHeight;
  39551. varying vec3 vColor;
  39552. varying float vLogDepth;
  39553. varying vec3 vViewPosition;
  39554. varying float vRadius;
  39555. varying float vPointSize;
  39556. varying vec3 vPosition;
  39557. float specularStrength = 1.0;
  39558. vec2 getSamplerCoord( vec3 direction )
  39559. {
  39560. direction = normalize(direction);
  39561. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  39562. float ty=acos(direction.z)/PI;
  39563. return vec2(tx,ty);
  39564. }
  39565. void main() {
  39566. vec3 color = vColor;
  39567. /*#if defined(usePanoMap) //加 经测试,即使全部写在fragment里也是无论pointsize多大都是一个点一个颜色,所以干脆写在vectex里
  39568. vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  39569. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  39570. color = mix(colorFromPano0,colorFromPano1,progress).xyz;
  39571. //float easeInOutRatio = 0.0; //缓冲,渐变点云到贴图的颜色
  39572. if(progress < easeInOutRatio){
  39573. float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;
  39574. color = mix(color,vColor,easeProgress);
  39575. }else if(progress > 1.0 - easeInOutRatio){
  39576. float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;
  39577. color = mix(color,vColor,easeProgress);
  39578. }
  39579. #else
  39580. color = vColor;
  39581. #endif*/
  39582. float depth = gl_FragCoord.z;
  39583. #if defined(circle_point_shape) || defined(paraboloid_point_shape)
  39584. float u = 2.0 * gl_PointCoord.x - 1.0;
  39585. float v = 2.0 * gl_PointCoord.y - 1.0;
  39586. #endif
  39587. #if defined(circle_point_shape)
  39588. float cc = u*u + v*v;
  39589. if(cc > 1.0){
  39590. discard;
  39591. }
  39592. #endif
  39593. #if defined color_type_indices //pick point recognize
  39594. gl_FragColor = vec4(color, uPCIndex / 255.0); //uPCIndex : node Index
  39595. #else
  39596. gl_FragColor = vec4(color, vOpacity);
  39597. #endif
  39598. #if defined paraboloid_point_shape
  39599. float wi = 0.0 - ( u*u + v*v);
  39600. vec4 pos = vec4(vViewPosition, 1.0);
  39601. pos.z += wi * vRadius;
  39602. float linearDepth = -pos.z;
  39603. pos = projectionMatrix * pos;
  39604. pos = pos / pos.w;
  39605. float expDepth = pos.z;
  39606. depth = (pos.z + 1.0) / 2.0;
  39607. gl_FragDepthEXT = depth;
  39608. gl_FragDepthEXT = clamp(gl_FragDepthEXT, 0.0, 1.0); //add
  39609. #if defined(color_type_depth)
  39610. color.r = linearDepth;
  39611. color.g = expDepth;
  39612. #endif
  39613. #if defined(use_edl)
  39614. gl_FragColor.a = log2(linearDepth);
  39615. #endif
  39616. #else
  39617. #if defined(use_edl)
  39618. gl_FragColor.a = vLogDepth;
  39619. #endif
  39620. #endif
  39621. #if defined(weighted_splats)
  39622. float distance = 2.0 * length(gl_PointCoord.xy - 0.5);
  39623. float weight = max(0.0, 1.0 - distance);
  39624. weight = pow(weight, 1.5);
  39625. gl_FragColor.a = weight;
  39626. gl_FragColor.xyz = gl_FragColor.xyz * weight;
  39627. #endif
  39628. //gl_FragColor = vec4(0.0, 0.7, 0.0, 1.0);
  39629. }
  39630. `;
  39631. Shaders["pointcloud_sm.vs"] = `
  39632. precision mediump float;
  39633. precision mediump int;
  39634. attribute vec3 position;
  39635. attribute vec3 color;
  39636. uniform mat4 modelMatrix;
  39637. uniform mat4 modelViewMatrix;
  39638. uniform mat4 projectionMatrix;
  39639. uniform mat4 viewMatrix;
  39640. uniform float uScreenWidth;
  39641. uniform float uScreenHeight;
  39642. uniform float near;
  39643. uniform float far;
  39644. uniform float uSpacing;
  39645. uniform float uOctreeSize;
  39646. uniform float uLevel;
  39647. uniform float uVNStart;
  39648. uniform sampler2D visibleNodes;
  39649. varying float vLinearDepth;
  39650. varying vec3 vColor;
  39651. #define PI 3.141592653589793
  39652. // ---------------------
  39653. // OCTREE
  39654. // ---------------------
  39655. #if defined(adaptive_point_size)
  39656. /**
  39657. * number of 1-bits up to inclusive index position
  39658. * number is treated as if it were an integer in the range 0-255
  39659. *
  39660. */
  39661. float numberOfOnes(float number, float index){
  39662. float tmp = mod(number, pow(2.0, index + 1.0));
  39663. float numOnes = 0.0;
  39664. for(float i = 0.0; i < 8.0; i++){
  39665. if(mod(tmp, 2.0) != 0.0){
  39666. numOnes++;
  39667. }
  39668. tmp = floor(tmp / 2.0);
  39669. }
  39670. return numOnes;
  39671. }
  39672. /**
  39673. * checks whether the bit at index is 1
  39674. * number is treated as if it were an integer in the range 0-255
  39675. *
  39676. */
  39677. bool isBitSet(float number, float index){
  39678. return mod(floor(number / pow(2.0, index)), 2.0) != 0.0;
  39679. }
  39680. /**
  39681. * find the LOD at the point position
  39682. */
  39683. float getLOD(){
  39684. vec3 offset = vec3(0.0, 0.0, 0.0);
  39685. float iOffset = uVNStart;
  39686. float depth = uLevel;
  39687. for(float i = 0.0; i <= 30.0; i++){
  39688. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  39689. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  39690. index3d = floor(index3d + 0.5);
  39691. float index = 4.0 * index3d.x + 2.0 * index3d.y + index3d.z;
  39692. vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));
  39693. float mask = value.r * 255.0;
  39694. if(isBitSet(mask, index)){
  39695. // there are more visible child nodes at this position
  39696. iOffset = iOffset + value.g * 255.0 * 256.0 + value.b * 255.0 + numberOfOnes(mask, index - 1.0);
  39697. depth++;
  39698. }else{
  39699. // no more visible child nodes at this position
  39700. return depth;
  39701. }
  39702. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  39703. }
  39704. return depth;
  39705. }
  39706. #endif
  39707. float getPointSize(){
  39708. float pointSize = 1.0;
  39709. float slope = tan(fov / 2.0);
  39710. float projFactor = -0.5 * uScreenHeight / (slope * vViewPosition.z);
  39711. float r = uOctreeSpacing * 1.5;
  39712. vRadius = r;
  39713. #if defined fixed_point_size
  39714. pointSize = size;
  39715. #elif defined attenuated_point_size
  39716. if(uUseOrthographicCamera){
  39717. pointSize = size;
  39718. }else{
  39719. pointSize = pointSize * projFactor;
  39720. }
  39721. #elif defined adaptive_point_size
  39722. if(uUseOrthographicCamera) {
  39723. float worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();
  39724. pointSize = (worldSpaceSize / uOrthoWidth) * uScreenWidth;
  39725. } else {
  39726. float worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();
  39727. pointSize = worldSpaceSize * projFactor;
  39728. }
  39729. #endif
  39730. pointSize = max(minSize, pointSize);
  39731. pointSize = min(maxSize, pointSize);
  39732. vRadius = pointSize / projFactor;
  39733. return pointSize;
  39734. }
  39735. void main() {
  39736. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  39737. vLinearDepth = gl_Position.w;
  39738. float pointSize = getPointSize();
  39739. gl_PointSize = pointSize;
  39740. }
  39741. `;
  39742. Shaders["pointcloud_sm.fs"] = `
  39743. precision mediump float;
  39744. precision mediump int;
  39745. varying vec3 vColor;
  39746. varying float vLinearDepth;
  39747. void main() {
  39748. //gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  39749. //gl_FragColor = vec4(vColor, 1.0);
  39750. //gl_FragColor = vec4(vLinearDepth, pow(vLinearDepth, 2.0), 0.0, 1.0);
  39751. gl_FragColor = vec4(vLinearDepth, vLinearDepth / 30.0, vLinearDepth / 30.0, 1.0);
  39752. }
  39753. `;
  39754. Shaders["normalize.vs"] = `
  39755. precision mediump float;
  39756. precision mediump int;
  39757. attribute vec3 position;
  39758. attribute vec2 uv;
  39759. uniform mat4 projectionMatrix;
  39760. uniform mat4 modelViewMatrix;
  39761. varying vec2 vUv;
  39762. void main() {
  39763. vUv = uv;
  39764. gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  39765. }`;
  39766. Shaders["normalize.fs"] = `
  39767. #extension GL_EXT_frag_depth : enable
  39768. precision mediump float;
  39769. precision mediump int;
  39770. uniform sampler2D uWeightMap;
  39771. uniform sampler2D uDepthMap;
  39772. varying vec2 vUv;
  39773. void main() {
  39774. float depth = texture2D(uDepthMap, vUv).r;
  39775. if(depth >= 1.0){
  39776. discard;
  39777. }
  39778. gl_FragColor = vec4(depth, 1.0, 0.0, 1.0);
  39779. vec4 color = texture2D(uWeightMap, vUv);
  39780. color = color / color.w;
  39781. gl_FragColor = vec4(color.xyz, 1.0);
  39782. gl_FragDepthEXT = depth;
  39783. }`;
  39784. Shaders["normalize_and_edl.fs"] = `
  39785. #extension GL_EXT_frag_depth : enable
  39786. //
  39787. // adapted from the EDL shader code from Christian Boucheny in cloud compare:
  39788. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  39789. //
  39790. precision mediump float;
  39791. precision mediump int;
  39792. uniform sampler2D uWeightMap;
  39793. uniform sampler2D uEDLMap;
  39794. uniform sampler2D uDepthMap;
  39795. uniform float screenWidth;
  39796. uniform float screenHeight;
  39797. uniform vec2 neighbours[NEIGHBOUR_COUNT];
  39798. uniform float edlStrength;
  39799. uniform float radius;
  39800. varying vec2 vUv;
  39801. float response(float depth){
  39802. vec2 uvRadius = radius / vec2(screenWidth, screenHeight);
  39803. float sum = 0.0;
  39804. for(int i = 0; i < NEIGHBOUR_COUNT; i++){
  39805. vec2 uvNeighbor = vUv + uvRadius * neighbours[i];
  39806. float neighbourDepth = texture2D(uEDLMap, uvNeighbor).a;
  39807. if(neighbourDepth != 0.0){
  39808. if(depth == 0.0){
  39809. sum += 100.0;
  39810. }else{
  39811. sum += max(0.0, depth - neighbourDepth);
  39812. }
  39813. }
  39814. }
  39815. return sum / float(NEIGHBOUR_COUNT);
  39816. }
  39817. void main() {
  39818. float edlDepth = texture2D(uEDLMap, vUv).a;
  39819. float res = response(edlDepth);
  39820. float shade = exp(-res * 300.0 * edlStrength);
  39821. float depth = texture2D(uDepthMap, vUv).r;
  39822. if(depth >= 1.0 && res == 0.0){
  39823. discard;
  39824. }
  39825. vec4 color = texture2D(uWeightMap, vUv);
  39826. color = color / color.w;
  39827. color = color * shade;
  39828. gl_FragColor = vec4(color.xyz, 1.0);
  39829. gl_FragDepthEXT = depth;
  39830. }`;
  39831. Shaders["edl_new.vs"] = `
  39832. precision mediump float;
  39833. precision mediump int;
  39834. attribute vec3 position;
  39835. attribute vec2 uv;
  39836. uniform mat4 projectionMatrix;
  39837. uniform mat4 modelViewMatrix;
  39838. varying vec2 vUv;
  39839. void main() {
  39840. vUv = uv;
  39841. vec4 mvPosition = modelViewMatrix * vec4(position,1.0);
  39842. gl_Position = projectionMatrix * mvPosition;
  39843. }`;
  39844. Shaders["edl_new.fs"] = `
  39845. #extension GL_EXT_frag_depth : enable
  39846. //
  39847. // adapted from the EDL shader code from Christian Boucheny in cloud compare:
  39848. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  39849. //
  39850. precision mediump float;
  39851. precision mediump int;
  39852. //uniform float screenWidth;
  39853. //uniform float screenHeight;
  39854. uniform vec2 resolution;
  39855. uniform vec2 neighbours[NEIGHBOUR_COUNT];
  39856. uniform float edlStrength;
  39857. uniform float radius;
  39858. uniform float opacity;
  39859. //uniform float uNear;
  39860. //uniform float uFar;
  39861. uniform mat4 uProj;
  39862. uniform sampler2D uEDLColor;
  39863. uniform sampler2D uEDLDepth;
  39864. varying vec2 vUv;
  39865. uniform int useEDL;
  39866. float response(float depth){
  39867. vec2 uvRadius = radius / resolution; //vec2(screenWidth, screenHeight);
  39868. float sum = 0.0;
  39869. for(int i = 0; i < NEIGHBOUR_COUNT; i++){
  39870. vec2 uvNeighbor = vUv + uvRadius * neighbours[i];
  39871. //获取周围八个格子的值
  39872. float neighbourDepth = texture2D(uEDLColor, uvNeighbor).a;
  39873. neighbourDepth = (neighbourDepth == 1.0) ? 0.0 : neighbourDepth;
  39874. if(neighbourDepth != 0.0){
  39875. //if(depth == 0.0){
  39876. // sum += 100.0;
  39877. //}else{
  39878. sum += max(0.0, depth - neighbourDepth); //获取差值
  39879. //}
  39880. }
  39881. }
  39882. return sum / float(NEIGHBOUR_COUNT);
  39883. }
  39884. void main(){
  39885. vec4 cEDL = texture2D(uEDLColor, vUv);
  39886. float depth = cEDL.a;
  39887. depth = (depth == 1.0) ? 0.0 : depth;
  39888. if(depth == 0.0){ //去掉这句就能在无点云像素的地方渲染outline,但会遮住其他mesh
  39889. discard;
  39890. }
  39891. if(useEDL == 1){
  39892. float res = response(depth);
  39893. float shade = exp(-res * 300.0 * edlStrength); //自然常数e为底的指数函数
  39894. const float min = 0.2; //add 使边缘色变浅 范围从0-1 变为min-1
  39895. shade = shade * (1.0-min) + min;
  39896. gl_FragColor = vec4(cEDL.rgb * shade, opacity);
  39897. }else{//加 不改颜色的情况
  39898. gl_FragColor = vec4(cEDL.rgb, opacity);
  39899. }
  39900. //注意,edlStrength越强,在相同depth的叠放的点云间的轮廓线颜色越深
  39901. //作用:勾勒边缘,强化深度差异,模拟阴影,加强结构立体感
  39902. { // write regular hyperbolic depth values to depth buffer 修改深度
  39903. float dl = pow(2.0, depth);
  39904. vec4 dp = uProj * vec4(0.0, 0.0, -dl, 1.0);
  39905. float pz = dp.z / dp.w;
  39906. float fragDepth = (pz + 1.0) / 2.0;
  39907. gl_FragDepthEXT = fragDepth;
  39908. }
  39909. }
  39910. `;
  39911. Shaders["blur.vs"] = `
  39912. varying vec2 vUv;
  39913. void main() {
  39914. vUv = uv;
  39915. gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  39916. }`;
  39917. Shaders["blur.fs"] = `
  39918. uniform mat4 projectionMatrix;
  39919. uniform float screenWidth;
  39920. uniform float screenHeight;
  39921. uniform float near;
  39922. uniform float far;
  39923. uniform sampler2D map;
  39924. varying vec2 vUv;
  39925. void main() {
  39926. float dx = 1.0 / screenWidth;
  39927. float dy = 1.0 / screenHeight;
  39928. vec3 color = vec3(0.0, 0.0, 0.0);
  39929. color += texture2D(map, vUv + vec2(-dx, -dy)).rgb;
  39930. color += texture2D(map, vUv + vec2( 0, -dy)).rgb;
  39931. color += texture2D(map, vUv + vec2(+dx, -dy)).rgb;
  39932. color += texture2D(map, vUv + vec2(-dx, 0)).rgb;
  39933. color += texture2D(map, vUv + vec2( 0, 0)).rgb;
  39934. color += texture2D(map, vUv + vec2(+dx, 0)).rgb;
  39935. color += texture2D(map, vUv + vec2(-dx, dy)).rgb;
  39936. color += texture2D(map, vUv + vec2( 0, dy)).rgb;
  39937. color += texture2D(map, vUv + vec2(+dx, dy)).rgb;
  39938. color = color / 9.0;
  39939. gl_FragColor = vec4(color, 1.0);
  39940. }`;
  39941. Shaders["depthBasic.vs"] = `
  39942. varying vec2 vUv;
  39943. void main() {
  39944. vUv = uv;
  39945. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  39946. }
  39947. `;
  39948. Shaders["depthBasic.fs"] = `varying vec2 vUv;
  39949. uniform float opacity;
  39950. uniform float mapScale;
  39951. uniform vec3 baseColor;
  39952. #if defined use_map
  39953. uniform sampler2D map;
  39954. vec4 getMapColor(vec4 color){
  39955. vec2 uv = (vUv - 0.5) / mapScale + 0.5;
  39956. if(uv.x > 1.0 || uv.y > 1.0 || uv.x < 0.0 || uv.y < 0.0){
  39957. //color = vec4(0.0,0.0,0.0,0.0);
  39958. discard;
  39959. }else{
  39960. color = texture2D(map, uv) * color;
  39961. }
  39962. return color;
  39963. }
  39964. #endif
  39965. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  39966. //似乎通过gl.getExtension('EXT_frag_depth')得到的GL_EXT_frag_depth
  39967. uniform sampler2D depthTexture;
  39968. uniform float nearPlane;
  39969. uniform float farPlane;
  39970. uniform vec2 resolution;
  39971. uniform vec2 viewportOffset; // viewportOffset 范围从0-整个画布的像素
  39972. uniform vec3 backColor;
  39973. uniform float occlusionDistance;
  39974. uniform float clipDistance;
  39975. uniform float maxClipFactor;
  39976. uniform float maxOcclusionFactor;
  39977. //uniform bool uUseOrthographicCamera;
  39978. float convertToLinear(float zValue)
  39979. {
  39980. //if(uUseOrthographicCamera){
  39981. // return zValue*(farPlane-nearPlane)+nearPlane;
  39982. //}else{
  39983. float z = zValue * 2.0 - 1.0;
  39984. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  39985. //}
  39986. }
  39987. #endif
  39988. void main() {
  39989. vec4 color = vec4(baseColor, opacity);
  39990. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  39991. // mixFactor and clipFactor define the color mixing proportion between the states of
  39992. // full visibility and occluded visibility
  39993. // and
  39994. // full visibility and total invisibility
  39995. float mixFactor = 0.0;
  39996. float clipFactor = 0.0;
  39997. // The linear depth value of the current fragment
  39998. float fragDepth = convertToLinear(gl_FragCoord.z);
  39999. // The coordinates of the current fragment in the depth texture
  40000. vec2 depthTxtCoords = vec2(gl_FragCoord.x-viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  40001. //gl_FragCoord大小为 viewport client大小
  40002. // The linear depth value of the pixel occupied by this fragment in the depth buffer
  40003. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  40004. // The difference between the two depths
  40005. float delta = fragDepth - textureDepth;
  40006. if (delta > 0.0)//差距
  40007. {
  40008. // occlusionDistance and clipDistance define the width of the respective zones and
  40009. // mixFactor and clipFactor express the interpolation between the two colors depending on the position
  40010. // of the current fragment withing those zones.
  40011. mixFactor = clamp(delta / occlusionDistance, 0.0, maxOcclusionFactor);
  40012. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  40013. }
  40014. // If the fragment is totally transparent, don't bother drawing it
  40015. if (clipFactor == 1.0)
  40016. {
  40017. discard;
  40018. }else{
  40019. #if defined use_map
  40020. color = getMapColor(color);
  40021. #endif
  40022. color = vec4(mix(color.rgb, backColor, mixFactor), color.a * (1.0 - clipFactor));
  40023. }
  40024. #else
  40025. #if defined use_map
  40026. color = getMapColor(color);
  40027. #endif
  40028. #endif
  40029. gl_FragColor = color;
  40030. }
  40031. `;
  40032. Shaders["copyCubeMap.vs"] = `varying vec3 vWorldPos;
  40033. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  40034. {
  40035. float y = direction.y;
  40036. direction.y = direction.z;
  40037. direction.z = -y;
  40038. return direction;
  40039. }
  40040. void main() {
  40041. vWorldPos = vec3(-position.x, -position.y, position.z);
  40042. //vWorldPos = transformAxis(vWorldPos);
  40043. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  40044. }
  40045. `;
  40046. Shaders["copyCubeMap.fs"] = `varying vec3 vWorldPos;
  40047. uniform float alpha;
  40048. uniform samplerCube tDiffuse;
  40049. void main() {
  40050. vec4 texColor = textureCube(tDiffuse, vWorldPos);
  40051. gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);
  40052. }
  40053. `;
  40054. Shaders["basicTextured.vs"] = `varying vec2 vUv;
  40055. void main() {
  40056. vUv = uv;
  40057. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  40058. }
  40059. `;
  40060. Shaders["basicTextured.fs"] = `varying vec2 vUv;
  40061. uniform float opacity;
  40062. #ifdef HasMap
  40063. uniform sampler2D map;
  40064. #endif
  40065. #ifdef HasColor
  40066. uniform vec3 color;
  40067. #endif
  40068. void main() {
  40069. vec4 color_;
  40070. #ifdef HasColor
  40071. color_ = vec4(color, opacity);
  40072. #else
  40073. color_ = vec4(1.0,1.0,1.0, opacity);
  40074. #endif
  40075. #ifdef HasMap
  40076. vec4 texColor = texture2D(map, vUv);
  40077. gl_FragColor = texColor * color_;
  40078. #else
  40079. gl_FragColor = color_;
  40080. #endif
  40081. }
  40082. `;
  40083. Shaders["skybox.vs"] = `uniform mat4 matrix;
  40084. varying vec3 vWorldPosition;
  40085. void main()
  40086. {
  40087. vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz ; // - cameraPosition;
  40088. vWorldPosition = (vec4(vWorldPosition, 1.0) * matrix).xyz;
  40089. vWorldPosition.x *= -1.0;
  40090. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  40091. }`;
  40092. Shaders["skybox.fs"] = `varying vec3 vWorldPosition;
  40093. uniform sampler2D tDiffuse;
  40094. #define PI 3.141592653
  40095. /*vec2 getSamplerCoord( vec3 direction )
  40096. {
  40097. direction = normalize(direction);
  40098. float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;
  40099. float ty=acos(direction.y)/PI;
  40100. return vec2(tx,ty);
  40101. }*/
  40102. vec2 getSamplerCoord( vec3 direction )
  40103. {
  40104. direction = normalize(direction);
  40105. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  40106. float ty=acos(direction.z)/PI;
  40107. return vec2(tx,ty);
  40108. }
  40109. void main()
  40110. {
  40111. vec2 samplerCoord = getSamplerCoord(vWorldPosition);
  40112. vec4 color = texture2D(tDiffuse, samplerCoord);
  40113. //gl_FragColor = RGBEToLinear( color ); //对于hdr必须加这一句,否则效果很奇怪。copy自meshBasicMaterial里的mat_fragment的mapTexelToLinear函数,只要有map就会使用该函数
  40114. gl_FragColor = color;
  40115. //#include <tonemapping_fragment>
  40116. //////#include <encodings_fragment>
  40117. }
  40118. `;
  40119. const ClassificationScheme = {
  40120. DEFAULT: {
  40121. 0: { visible: true, name: 'never classified' , color: [0.5, 0.5, 0.5, 1.0] },
  40122. 1: { visible: true, name: 'unclassified' , color: [0.5, 0.5, 0.5, 1.0] },
  40123. 2: { visible: true, name: 'ground' , color: [0.63, 0.32, 0.18, 1.0] },
  40124. 3: { visible: true, name: 'low vegetation' , color: [0.0, 1.0, 0.0, 1.0] },
  40125. 4: { visible: true, name: 'medium vegetation' , color: [0.0, 0.8, 0.0, 1.0] },
  40126. 5: { visible: true, name: 'high vegetation' , color: [0.0, 0.6, 0.0, 1.0] },
  40127. 6: { visible: true, name: 'building' , color: [1.0, 0.66, 0.0, 1.0] },
  40128. 7: { visible: true, name: 'low point(noise)' , color: [1.0, 0.0, 1.0, 1.0] },
  40129. 8: { visible: true, name: 'key-point' , color: [1.0, 0.0, 0.0, 1.0] },
  40130. 9: { visible: true, name: 'water' , color: [0.0, 0.0, 1.0, 1.0] },
  40131. 12: { visible: true, name: 'overlap' , color: [1.0, 1.0, 0.0, 1.0] },
  40132. DEFAULT: { visible: true, name: 'default' , color: [0.3, 0.6, 0.6, 0.5] },
  40133. }
  40134. };
  40135. Object.defineProperty(ClassificationScheme, 'RANDOM', {
  40136. get: function() {
  40137. let scheme = {};
  40138. for(let i = 0; i <= 255; i++){
  40139. scheme[i] = new Vector4(Math.random(), Math.random(), Math.random());
  40140. }
  40141. scheme["DEFAULT"] = new Vector4(Math.random(), Math.random(), Math.random());
  40142. return scheme;
  40143. }
  40144. });
  40145. class EnumItem{
  40146. constructor(object){
  40147. for(let key of Object.keys(object)){
  40148. this[key] = object[key];
  40149. }
  40150. }
  40151. inspect(){
  40152. return `Enum(${this.name}: ${this.value})`;
  40153. }
  40154. };
  40155. class Enum{
  40156. constructor(object){
  40157. this.object = object;
  40158. for(let key of Object.keys(object)){
  40159. let value = object[key];
  40160. if(typeof value === "object"){
  40161. value.name = key;
  40162. }else {
  40163. value = {name: key, value: value};
  40164. }
  40165. this[key] = new EnumItem(value);
  40166. }
  40167. }
  40168. fromValue(value){
  40169. for(let key of Object.keys(this.object)){
  40170. if(this[key].value === value){
  40171. return this[key];
  40172. }
  40173. }
  40174. throw new Error(`No enum for value: ${value}`);
  40175. }
  40176. };
  40177. const CameraMode = {
  40178. ORTHOGRAPHIC: 0,
  40179. PERSPECTIVE: 1,
  40180. VR: 2,
  40181. };
  40182. const ClipTask = {
  40183. NONE: 0,
  40184. HIGHLIGHT: 1,
  40185. SHOW_INSIDE: 2,
  40186. SHOW_OUTSIDE: 3
  40187. };
  40188. const ClipMethod = {
  40189. INSIDE_ANY: 0,
  40190. INSIDE_ALL: 1
  40191. };
  40192. const ElevationGradientRepeat = {
  40193. CLAMP: 0,
  40194. REPEAT: 1,
  40195. MIRRORED_REPEAT: 2,
  40196. };
  40197. const MOUSE$1 = {
  40198. LEFT: 0b0001,
  40199. RIGHT: 0b0010,
  40200. MIDDLE: 0b0100
  40201. };
  40202. const PointSizeType = {
  40203. FIXED: 0,
  40204. ATTENUATED: 1,
  40205. ADAPTIVE: 2
  40206. };
  40207. const PointShape$1 = {
  40208. SQUARE: 0,
  40209. CIRCLE: 1,
  40210. PARABOLOID: 2
  40211. };
  40212. const TreeType = {
  40213. OCTREE: 0,
  40214. KDTREE: 1
  40215. };
  40216. const LengthUnits = {
  40217. METER: {code: 'm', unitspermeter: 1.0},
  40218. FEET: {code: 'ft', unitspermeter: 3.28084},
  40219. INCH: {code: '\u2033', unitspermeter: 39.3701}
  40220. };
  40221. //
  40222. // how to calculate the radius of a projected sphere in screen space
  40223. // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
  40224. // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere
  40225. //
  40226. class PointCloudMaterial$1 extends RawShaderMaterial {//base
  40227. constructor (parameters = {}) {
  40228. super();
  40229. this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new Color(0xffffff));
  40230. this.visibleNodesTexture.minFilter = NearestFilter;
  40231. this.visibleNodesTexture.magFilter = NearestFilter;
  40232. let getValid = (a, b) => {
  40233. if(a !== undefined){
  40234. return a;
  40235. }else {
  40236. return b;
  40237. }
  40238. };
  40239. let pointSize = getValid(parameters.size, 1.0);
  40240. let minSize = getValid(parameters.minSize, 2.0);
  40241. let maxSize = getValid(parameters.maxSize, 50.0);
  40242. let treeType = getValid(parameters.treeType, TreeType.OCTREE);
  40243. this._pointSizeType = PointSizeType.FIXED;
  40244. this._shape = PointShape$1.SQUARE;
  40245. this._useClipBox = false;
  40246. this.clipBoxes = [];
  40247. this.clipPolygons = [];
  40248. this._weighted = false;
  40249. this._gradient = Gradients.SPECTRAL;
  40250. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  40251. //this._matcap = "matcap.jpg";
  40252. //this.matcapTexture = PointCloudMaterial.generateMatcapTexture(this._matcap);
  40253. this.lights = false;
  40254. this.fog = false;
  40255. this._treeType = treeType;
  40256. this._useEDL = false;
  40257. this.defines = new Map();
  40258. this.ranges = new Map();
  40259. this._activeAttributeName = null;
  40260. this._defaultIntensityRangeChanged = false;
  40261. this._defaultElevationRangeChanged = false;
  40262. {
  40263. const [width, height] = [256, 1];
  40264. let data = new Uint8Array(width * 4);
  40265. let texture = new DataTexture(data, width, height, RGBAFormat);
  40266. texture.magFilter = NearestFilter;
  40267. texture.needsUpdate = true;
  40268. this.classificationTexture = texture;
  40269. }
  40270. this.attributes = {
  40271. position: { type: 'fv', value: [] },
  40272. color: { type: 'fv', value: [] },
  40273. normal: { type: 'fv', value: [] },
  40274. intensity: { type: 'f', value: [] },
  40275. classification: { type: 'f', value: [] },
  40276. returnNumber: { type: 'f', value: [] },
  40277. numberOfReturns: { type: 'f', value: [] },
  40278. pointSourceID: { type: 'f', value: [] },
  40279. indices: { type: 'fv', value: [] }
  40280. };
  40281. this.uniforms = {
  40282. level: { type: "f", value: 0.0 },
  40283. vnStart: { type: "f", value: 0.0 },
  40284. spacing: { type: "f", value: 1.0 },
  40285. blendHardness: { type: "f", value: 2.0 },
  40286. blendDepthSupplement: { type: "f", value: 0.0 },
  40287. fov: { type: "f", value: 1.0 },
  40288. screenWidth: { type: "f", value: 1.0 },
  40289. screenHeight: { type: "f", value: 1.0 },
  40290. near: { type: "f", value: 0.1 },
  40291. far: { type: "f", value: 1.0 },
  40292. uColor: { type: "c", value: new Color( 0xffffff ) },
  40293. uOpacity: { type: "f", value: 1.0 },
  40294. size: { type: "f", value: pointSize },
  40295. minSize: { type: "f", value: minSize },
  40296. maxSize: { type: "f", value: maxSize },
  40297. octreeSize: { type: "f", value: 0 },
  40298. bbSize: { type: "fv", value: [0, 0, 0] },
  40299. elevationRange: { type: "2fv", value: [0, 0] },
  40300. clipBoxCount: { type: "f", value: 0 },
  40301. //clipSphereCount: { type: "f", value: 0 },
  40302. clipPolygonCount: { type: "i", value: 0 },
  40303. clipBoxes: { type: "Matrix4fv", value: [] },
  40304. //clipSpheres: { type: "Matrix4fv", value: [] },
  40305. clipPolygons: { type: "3fv", value: [] },
  40306. clipPolygonVCount: { type: "iv", value: [] },
  40307. clipPolygonVP: { type: "Matrix4fv", value: [] },
  40308. visibleNodes: { type: "t", value: this.visibleNodesTexture },
  40309. pcIndex: { type: "f", value: 0 },
  40310. gradient: { type: "t", value: this.gradientTexture },
  40311. classificationLUT: { type: "t", value: this.classificationTexture },
  40312. uHQDepthMap: { type: "t", value: null },
  40313. toModel: { type: "Matrix4f", value: [] },
  40314. diffuse: { type: "fv", value: [1, 1, 1] },
  40315. transition: { type: "f", value: 0.5 },
  40316. intensityRange: { type: "fv", value: [Infinity, -Infinity] },
  40317. intensity_gbc: { type: "fv", value: [1, 0, 0]},
  40318. uRGB_gbc: { type: "fv", value: [1, 0, 0]},
  40319. // intensityGamma: { type: "f", value: 1 },
  40320. // intensityContrast: { type: "f", value: 0 },
  40321. // intensityBrightness:{ type: "f", value: 0 },
  40322. // rgbGamma: { type: "f", value: 1 },
  40323. // rgbContrast: { type: "f", value: 0 },
  40324. // rgbBrightness: { type: "f", value: 0 },
  40325. wRGB: { type: "f", value: 1 },
  40326. wIntensity: { type: "f", value: 0 },
  40327. wElevation: { type: "f", value: 0 },
  40328. wClassification: { type: "f", value: 0 },
  40329. wReturnNumber: { type: "f", value: 0 },
  40330. wSourceID: { type: "f", value: 0 },
  40331. useOrthographicCamera: { type: "b", value: false },
  40332. elevationGradientRepat: { type: "i", value: ElevationGradientRepeat.CLAMP },
  40333. clipTask: { type: "i", value: 1 },
  40334. clipMethod: { type: "i", value: 1 },
  40335. uShadowColor: { type: "3fv", value: [0, 0, 0] },
  40336. uExtraScale: { type: "f", value: 1},
  40337. uExtraOffset: { type: "f", value: 0},
  40338. uExtraRange: { type: "2fv", value: [0, 1] },
  40339. uExtraGammaBrightContr: { type: "3fv", value: [1, 0, 0] },
  40340. uFilterReturnNumberRange: { type: "fv", value: [0, 7]},
  40341. uFilterNumberOfReturnsRange: { type: "fv", value: [0, 7]},
  40342. uFilterGPSTimeClipRange: { type: "fv", value: [0, 7]},
  40343. uFilterPointSourceIDClipRange: { type: "fv", value: [0, 65535]},
  40344. //matcapTextureUniform: { type: "t", value: this.matcapTexture },
  40345. backfaceCulling: { type: "b", value: false },
  40346. };
  40347. this.classification = ClassificationScheme.DEFAULT;
  40348. this.defaultAttributeValues.normal = [0, 0, 0];
  40349. this.defaultAttributeValues.classification = [0, 0, 0];
  40350. this.defaultAttributeValues.indices = [0, 0, 0, 0];
  40351. this.vertexShader = Shaders['pointcloud.vs'];
  40352. this.fragmentShader = Shaders['pointcloud.fs'];
  40353. this.vertexColors = VertexColors;
  40354. this.updateShaderSource();
  40355. }
  40356. setDefine(key, value){
  40357. if(value !== undefined && value !== null){
  40358. if(this.defines.get(key) !== value){
  40359. this.defines.set(key, value);
  40360. this.updateShaderSource();
  40361. }
  40362. }else {
  40363. this.removeDefine(key);
  40364. }
  40365. }
  40366. removeDefine(key){
  40367. this.defines.delete(key);
  40368. }
  40369. updateShaderSource () {
  40370. let vs = Shaders['pointcloud.vs'];
  40371. let fs = Shaders['pointcloud.fs'];
  40372. let definesString = this.getDefines();
  40373. let vsVersionIndex = vs.indexOf("#version ");
  40374. let fsVersionIndex = fs.indexOf("#version ");
  40375. if(vsVersionIndex >= 0){
  40376. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  40377. }else {
  40378. vs = `${definesString}\n${vs}`;
  40379. }
  40380. if(fsVersionIndex >= 0){
  40381. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  40382. }else {
  40383. fs = `${definesString}\n${fs}`;
  40384. }
  40385. this.vertexShader = vs;
  40386. this.fragmentShader = fs;
  40387. if (this.opacity === 1.0) {
  40388. this.blending = NoBlending;
  40389. this.transparent = false;
  40390. this.depthTest = true;
  40391. this.depthWrite = true;
  40392. this.depthFunc = LessEqualDepth;
  40393. } else if (this.opacity < 1.0 && !this.useEDL) {
  40394. this.blending = AdditiveBlending;
  40395. this.transparent = true;
  40396. this.depthTest = false;
  40397. this.depthWrite = true;
  40398. this.depthFunc = AlwaysDepth;
  40399. }
  40400. if (this.weighted) {
  40401. this.blending = AdditiveBlending;
  40402. this.transparent = true;
  40403. this.depthTest = true;
  40404. this.depthWrite = false;
  40405. }
  40406. this.needsUpdate = true;
  40407. }
  40408. getDefines () {
  40409. let defines = [];
  40410. if (this.pointSizeType === PointSizeType.FIXED) {
  40411. defines.push('#define fixed_point_size');
  40412. } else if (this.pointSizeType === PointSizeType.ATTENUATED) {
  40413. defines.push('#define attenuated_point_size');
  40414. } else if (this.pointSizeType === PointSizeType.ADAPTIVE) {
  40415. defines.push('#define adaptive_point_size');
  40416. }
  40417. if (this.shape === PointShape$1.SQUARE) {
  40418. defines.push('#define square_point_shape');
  40419. } else if (this.shape === PointShape$1.CIRCLE) {
  40420. defines.push('#define circle_point_shape');
  40421. } else if (this.shape === PointShape$1.PARABOLOID) {
  40422. defines.push('#define paraboloid_point_shape');
  40423. }
  40424. if (this._useEDL) {
  40425. defines.push('#define use_edl');
  40426. }
  40427. if(this.activeAttributeName){
  40428. let attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_');
  40429. defines.push(`#define color_type_${attributeName}`);
  40430. }
  40431. if(this._treeType === TreeType.OCTREE){
  40432. defines.push('#define tree_type_octree');
  40433. }else if(this._treeType === TreeType.KDTREE){
  40434. defines.push('#define tree_type_kdtree');
  40435. }
  40436. if (this.weighted) {
  40437. defines.push('#define weighted_splats');
  40438. }
  40439. for(let [key, value] of this.defines){
  40440. defines.push(value);
  40441. }
  40442. return defines.join("\n");
  40443. }
  40444. setClipBoxes (clipBoxes) {
  40445. if (!clipBoxes) {
  40446. return;
  40447. }
  40448. let doUpdate = (this.clipBoxes.length !== clipBoxes.length) && (clipBoxes.length === 0 || this.clipBoxes.length === 0);
  40449. this.uniforms.clipBoxCount.value = this.clipBoxes.length;
  40450. this.clipBoxes = clipBoxes;
  40451. if (doUpdate) {
  40452. this.updateShaderSource();
  40453. }
  40454. this.uniforms.clipBoxes.value = new Float32Array(this.clipBoxes.length * 16);
  40455. for (let i = 0; i < this.clipBoxes.length; i++) {
  40456. let box = clipBoxes[i];
  40457. this.uniforms.clipBoxes.value.set(box.inverse.elements, 16 * i);
  40458. }
  40459. for (let i = 0; i < this.uniforms.clipBoxes.value.length; i++) {
  40460. if (Number.isNaN(this.uniforms.clipBoxes.value[i])) {
  40461. this.uniforms.clipBoxes.value[i] = Infinity;
  40462. }
  40463. }
  40464. }
  40465. setClipPolygons(clipPolygons, maxPolygonVertices) {
  40466. if(!clipPolygons){
  40467. return;
  40468. }
  40469. this.clipPolygons = clipPolygons;
  40470. let doUpdate = (this.clipPolygons.length !== clipPolygons.length);
  40471. if(doUpdate){
  40472. this.updateShaderSource();
  40473. }
  40474. }
  40475. get gradient(){
  40476. return this._gradient;
  40477. }
  40478. set gradient (value) {//海拔贴图
  40479. if (this._gradient !== value) {
  40480. this._gradient = value;
  40481. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  40482. this.uniforms.gradient.value = this.gradientTexture;
  40483. }
  40484. }
  40485. /* get matcap(){
  40486. return this._matcap;
  40487. }
  40488. set matcap (value) {
  40489. if (this._matcap !== value) {
  40490. this._matcap = value;
  40491. this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap);
  40492. this.uniforms.matcapTextureUniform.value = this.matcapTexture;
  40493. }
  40494. } */
  40495. get useOrthographicCamera() {
  40496. return this.uniforms.useOrthographicCamera.value;
  40497. }
  40498. set useOrthographicCamera(value) {
  40499. if(this.uniforms.useOrthographicCamera.value !== value){
  40500. this.uniforms.useOrthographicCamera.value = value;
  40501. }
  40502. }
  40503. get backfaceCulling() {
  40504. return this.uniforms.backfaceCulling.value;
  40505. }
  40506. set backfaceCulling(value) {
  40507. if(this.uniforms.backfaceCulling.value !== value){
  40508. this.uniforms.backfaceCulling.value = value;
  40509. this.dispatchEvent({type: 'backface_changed', target: this});
  40510. }
  40511. }
  40512. recomputeClassification () {
  40513. const classification = this.classification;
  40514. const data = this.classificationTexture.image.data;
  40515. let width = 256;
  40516. const black = [1, 1, 1, 1];
  40517. let valuesChanged = false;
  40518. for (let i = 0; i < width; i++) {
  40519. let color;
  40520. let visible = true;
  40521. if (classification[i]) {
  40522. color = classification[i].color;
  40523. visible = classification[i].visible;
  40524. } else if (classification[i % 32]) {
  40525. color = classification[i % 32].color;
  40526. visible = classification[i % 32].visible;
  40527. } else if(classification.DEFAULT) {
  40528. color = classification.DEFAULT.color;
  40529. visible = classification.DEFAULT.visible;
  40530. }else {
  40531. color = black;
  40532. }
  40533. const r = parseInt(255 * color[0]);
  40534. const g = parseInt(255 * color[1]);
  40535. const b = parseInt(255 * color[2]);
  40536. const a = visible ? parseInt(255 * color[3]) : 0;
  40537. if(data[4 * i + 0] !== r){
  40538. data[4 * i + 0] = r;
  40539. valuesChanged = true;
  40540. }
  40541. if(data[4 * i + 1] !== g){
  40542. data[4 * i + 1] = g;
  40543. valuesChanged = true;
  40544. }
  40545. if(data[4 * i + 2] !== b){
  40546. data[4 * i + 2] = b;
  40547. valuesChanged = true;
  40548. }
  40549. if(data[4 * i + 3] !== a){
  40550. data[4 * i + 3] = a;
  40551. valuesChanged = true;
  40552. }
  40553. }
  40554. if(valuesChanged){
  40555. this.classificationTexture.needsUpdate = true;
  40556. this.dispatchEvent({
  40557. type: 'material_property_changed',
  40558. target: this
  40559. });
  40560. }
  40561. }
  40562. get spacing () {
  40563. return this.uniforms.spacing.value;
  40564. }
  40565. set spacing (value) {
  40566. if (this.uniforms.spacing.value !== value) { // 即 uOctreeSpacing 来自cloud.js里
  40567. this.uniforms.spacing.value = value;
  40568. }
  40569. }
  40570. get useClipBox () {
  40571. return this._useClipBox;
  40572. }
  40573. set useClipBox (value) {
  40574. if (this._useClipBox !== value) {
  40575. this._useClipBox = value;
  40576. this.updateShaderSource();
  40577. }
  40578. }
  40579. get clipTask(){
  40580. return this.uniforms.clipTask.value;
  40581. }
  40582. set clipTask(mode){
  40583. this.uniforms.clipTask.value = mode;
  40584. }
  40585. get elevationGradientRepat(){
  40586. return this.uniforms.elevationGradientRepat.value;
  40587. }
  40588. set elevationGradientRepat(mode){
  40589. this.uniforms.elevationGradientRepat.value = mode;
  40590. }
  40591. get clipMethod(){
  40592. return this.uniforms.clipMethod.value;
  40593. }
  40594. set clipMethod(mode){
  40595. this.uniforms.clipMethod.value = mode;
  40596. }
  40597. get weighted(){
  40598. return this._weighted;
  40599. }
  40600. set weighted (value) {
  40601. if (this._weighted !== value) {
  40602. this._weighted = value;
  40603. this.updateShaderSource();
  40604. }
  40605. }
  40606. get fov () {
  40607. return this.uniforms.fov.value;
  40608. }
  40609. set fov (value) {
  40610. if (this.uniforms.fov.value !== value) {
  40611. this.uniforms.fov.value = value;
  40612. // this.updateShaderSource();
  40613. }
  40614. }
  40615. get screenWidth () {
  40616. return this.uniforms.screenWidth.value;
  40617. }
  40618. set screenWidth (value) {
  40619. if (this.uniforms.screenWidth.value !== value) {
  40620. this.uniforms.screenWidth.value = value;
  40621. // this.updateShaderSource();
  40622. }
  40623. }
  40624. get screenHeight () {
  40625. return this.uniforms.screenHeight.value;
  40626. }
  40627. set screenHeight (value) {
  40628. if (this.uniforms.screenHeight.value !== value) {
  40629. this.uniforms.screenHeight.value = value;
  40630. // this.updateShaderSource();
  40631. }
  40632. }
  40633. get near () {
  40634. return this.uniforms.near.value;
  40635. }
  40636. set near (value) {
  40637. if (this.uniforms.near.value !== value) {
  40638. this.uniforms.near.value = value;
  40639. }
  40640. }
  40641. get far () {
  40642. return this.uniforms.far.value;
  40643. }
  40644. set far (value) {
  40645. if (this.uniforms.far.value !== value) {
  40646. this.uniforms.far.value = value;
  40647. }
  40648. }
  40649. get opacity(){
  40650. return this.uniforms.uOpacity.value;
  40651. }
  40652. set opacity (value) {
  40653. if (this.uniforms && this.uniforms.uOpacity) {
  40654. if (this.uniforms.uOpacity.value !== value) {
  40655. this.uniforms.uOpacity.value = value;
  40656. this.updateShaderSource();
  40657. this.dispatchEvent({
  40658. type: 'opacity_changed',
  40659. target: this
  40660. });
  40661. this.dispatchEvent({
  40662. type: 'material_property_changed',
  40663. target: this
  40664. });
  40665. }
  40666. }
  40667. }
  40668. get activeAttributeName(){
  40669. return this._activeAttributeName;
  40670. }
  40671. set activeAttributeName(value){
  40672. if (this._activeAttributeName !== value) {
  40673. this._activeAttributeName = value;
  40674. this.updateShaderSource();
  40675. this.dispatchEvent({
  40676. type: 'active_attribute_changed',
  40677. target: this
  40678. });
  40679. this.dispatchEvent({
  40680. type: 'material_property_changed',
  40681. target: this
  40682. });
  40683. }
  40684. }
  40685. get pointSizeType () {
  40686. return this._pointSizeType;
  40687. }
  40688. set pointSizeType (value) {
  40689. if (this._pointSizeType !== value) {
  40690. this._pointSizeType = value;
  40691. this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿
  40692. this.dispatchEvent({
  40693. type: 'point_size_type_changed',
  40694. target: this
  40695. });
  40696. this.dispatchEvent({
  40697. type: 'material_property_changed',
  40698. target: this
  40699. });
  40700. }
  40701. }
  40702. get useEDL(){
  40703. return this._useEDL;
  40704. }
  40705. set useEDL (value) {
  40706. if (this._useEDL !== value) {
  40707. this._useEDL = value;
  40708. this.updateShaderSource();
  40709. }
  40710. }
  40711. get color () {
  40712. return this.uniforms.uColor.value;
  40713. }
  40714. set color (value) {
  40715. if (!this.uniforms.uColor.value.equals(value)) {
  40716. this.uniforms.uColor.value.copy(value);
  40717. this.dispatchEvent({
  40718. type: 'color_changed',
  40719. target: this
  40720. });
  40721. this.dispatchEvent({
  40722. type: 'material_property_changed',
  40723. target: this
  40724. });
  40725. }
  40726. }
  40727. get shape () {
  40728. return this._shape;
  40729. }
  40730. set shape (value) {
  40731. if (this._shape !== value) {
  40732. this._shape = value;
  40733. this.updateShaderSource();
  40734. this.dispatchEvent({type: 'point_shape_changed', target: this});
  40735. this.dispatchEvent({
  40736. type: 'material_property_changed',
  40737. target: this
  40738. });
  40739. }
  40740. }
  40741. get treeType () {
  40742. return this._treeType;
  40743. }
  40744. set treeType (value) {
  40745. if (this._treeType !== value) {
  40746. this._treeType = value;
  40747. this.updateShaderSource();
  40748. }
  40749. }
  40750. get bbSize () {
  40751. return this.uniforms.bbSize.value;
  40752. }
  40753. set bbSize (value) {
  40754. this.uniforms.bbSize.value = value;
  40755. }
  40756. get size () {
  40757. return this.uniforms.size.value;
  40758. }
  40759. set size (value) {
  40760. if (this.uniforms.size.value !== value) {
  40761. this.uniforms.size.value = value;
  40762. this.dispatchEvent({
  40763. type: 'point_size_changed',
  40764. target: this
  40765. });
  40766. this.dispatchEvent({
  40767. type: 'material_property_changed',
  40768. target: this
  40769. });
  40770. }
  40771. }
  40772. get minSize(){
  40773. return this.uniforms.minSize.value;
  40774. }
  40775. set minSize(value){
  40776. if (this.uniforms.minSize.value !== value) {
  40777. this.uniforms.minSize.value = value;
  40778. this.dispatchEvent({
  40779. type: 'point_size_changed',
  40780. target: this
  40781. });
  40782. this.dispatchEvent({
  40783. type: 'material_property_changed',
  40784. target: this
  40785. });
  40786. }
  40787. }
  40788. get elevationRange () {
  40789. return this.uniforms.elevationRange.value;
  40790. }
  40791. set elevationRange (value) {
  40792. let changed = this.uniforms.elevationRange.value[0] !== value[0]
  40793. || this.uniforms.elevationRange.value[1] !== value[1];
  40794. if(changed){
  40795. this.uniforms.elevationRange.value = value;
  40796. this._defaultElevationRangeChanged = true;
  40797. this.dispatchEvent({
  40798. type: 'material_property_changed',
  40799. target: this
  40800. });
  40801. }
  40802. }
  40803. get heightMin () {
  40804. return this.uniforms.elevationRange.value[0];
  40805. }
  40806. set heightMin (value) {
  40807. this.elevationRange = [value, this.elevationRange[1]];
  40808. }
  40809. get heightMax () {
  40810. return this.uniforms.elevationRange.value[1];
  40811. }
  40812. set heightMax (value) {
  40813. this.elevationRange = [this.elevationRange[0], value];
  40814. }
  40815. get transition () {
  40816. return this.uniforms.transition.value;
  40817. }
  40818. set transition (value) {
  40819. this.uniforms.transition.value = value;
  40820. }
  40821. get intensityRange () {
  40822. return this.uniforms.intensityRange.value;
  40823. }
  40824. set intensityRange (value) {
  40825. if (!(value instanceof Array && value.length === 2)) {
  40826. return;
  40827. }
  40828. if (value[0] === this.uniforms.intensityRange.value[0] &&
  40829. value[1] === this.uniforms.intensityRange.value[1]) {
  40830. return;
  40831. }
  40832. this.uniforms.intensityRange.value = value;
  40833. this._defaultIntensityRangeChanged = true;
  40834. this.dispatchEvent({
  40835. type: 'material_property_changed',
  40836. target: this
  40837. });
  40838. }
  40839. get intensityGamma () {
  40840. return this.uniforms.intensity_gbc.value[0];
  40841. }
  40842. set intensityGamma (value) {
  40843. if (this.uniforms.intensity_gbc.value[0] !== value) {
  40844. this.uniforms.intensity_gbc.value[0] = value;
  40845. this.dispatchEvent({
  40846. type: 'material_property_changed',
  40847. target: this
  40848. });
  40849. }
  40850. }
  40851. get intensityContrast () {
  40852. return this.uniforms.intensity_gbc.value[2];
  40853. }
  40854. set intensityContrast (value) {
  40855. if (this.uniforms.intensity_gbc.value[2] !== value) {
  40856. this.uniforms.intensity_gbc.value[2] = value;
  40857. this.dispatchEvent({
  40858. type: 'material_property_changed',
  40859. target: this
  40860. });
  40861. }
  40862. }
  40863. get intensityBrightness () {
  40864. return this.uniforms.intensity_gbc.value[1];
  40865. }
  40866. set intensityBrightness (value) {
  40867. if (this.uniforms.intensity_gbc.value[1] !== value) {
  40868. this.uniforms.intensity_gbc.value[1] = value;
  40869. this.dispatchEvent({
  40870. type: 'material_property_changed',
  40871. target: this
  40872. });
  40873. }
  40874. }
  40875. get rgbGamma () {
  40876. return this.uniforms.uRGB_gbc.value[0];
  40877. }
  40878. set rgbGamma (value) {
  40879. if (this.uniforms.uRGB_gbc.value[0] !== value) {
  40880. this.uniforms.uRGB_gbc.value[0] = value;
  40881. this.dispatchEvent({
  40882. type: 'material_property_changed',
  40883. target: this
  40884. });
  40885. }
  40886. }
  40887. get rgbContrast () {
  40888. return this.uniforms.uRGB_gbc.value[2];
  40889. }
  40890. set rgbContrast (value) {
  40891. if (this.uniforms.uRGB_gbc.value[2] !== value) {
  40892. this.uniforms.uRGB_gbc.value[2] = value;
  40893. this.dispatchEvent({
  40894. type: 'material_property_changed',
  40895. target: this
  40896. });
  40897. }
  40898. }
  40899. get rgbBrightness () {
  40900. return this.uniforms.uRGB_gbc.value[1];
  40901. }
  40902. set rgbBrightness (value) {
  40903. if (this.uniforms.uRGB_gbc.value[1] !== value) {
  40904. this.uniforms.uRGB_gbc.value[1] = value;
  40905. this.dispatchEvent({
  40906. type: 'material_property_changed',
  40907. target: this
  40908. });
  40909. }
  40910. }
  40911. get extraGamma () {
  40912. return this.uniforms.uExtraGammaBrightContr.value[0];
  40913. }
  40914. set extraGamma (value) {
  40915. if (this.uniforms.uExtraGammaBrightContr.value[0] !== value) {
  40916. this.uniforms.uExtraGammaBrightContr.value[0] = value;
  40917. this.dispatchEvent({
  40918. type: 'material_property_changed',
  40919. target: this
  40920. });
  40921. }
  40922. }
  40923. get extraBrightness () {
  40924. return this.uniforms.uExtraGammaBrightContr.value[1];
  40925. }
  40926. set extraBrightness (value) {
  40927. if (this.uniforms.uExtraGammaBrightContr.value[1] !== value) {
  40928. this.uniforms.uExtraGammaBrightContr.value[1] = value;
  40929. this.dispatchEvent({
  40930. type: 'material_property_changed',
  40931. target: this
  40932. });
  40933. }
  40934. }
  40935. get extraContrast () {
  40936. return this.uniforms.uExtraGammaBrightContr.value[2];
  40937. }
  40938. set extraContrast (value) {
  40939. if (this.uniforms.uExtraGammaBrightContr.value[2] !== value) {
  40940. this.uniforms.uExtraGammaBrightContr.value[2] = value;
  40941. this.dispatchEvent({
  40942. type: 'material_property_changed',
  40943. target: this
  40944. });
  40945. }
  40946. }
  40947. getRange(attributeName){
  40948. return this.ranges.get(attributeName);
  40949. }
  40950. setRange(attributeName, newRange){
  40951. let rangeChanged = false;
  40952. let oldRange = this.ranges.get(attributeName);
  40953. if(oldRange != null && newRange != null){
  40954. rangeChanged = oldRange[0] !== newRange[0] || oldRange[1] !== newRange[1];
  40955. }else {
  40956. rangeChanged = true;
  40957. }
  40958. this.ranges.set(attributeName, newRange);
  40959. if(rangeChanged){
  40960. this.dispatchEvent({
  40961. type: 'material_property_changed',
  40962. target: this
  40963. });
  40964. }
  40965. }
  40966. get extraRange () {
  40967. return this.uniforms.uExtraRange.value;
  40968. }
  40969. set extraRange (value) {
  40970. if (!(value instanceof Array && value.length === 2)) {
  40971. return;
  40972. }
  40973. if (value[0] === this.uniforms.uExtraRange.value[0] &&
  40974. value[1] === this.uniforms.uExtraRange.value[1]) {
  40975. return;
  40976. }
  40977. this.uniforms.uExtraRange.value = value;
  40978. this._defaultExtraRangeChanged = true;
  40979. this.dispatchEvent({
  40980. type: 'material_property_changed',
  40981. target: this
  40982. });
  40983. }
  40984. get weightRGB () {
  40985. return this.uniforms.wRGB.value;
  40986. }
  40987. set weightRGB (value) {
  40988. if(this.uniforms.wRGB.value !== value){
  40989. this.uniforms.wRGB.value = value;
  40990. this.dispatchEvent({
  40991. type: 'material_property_changed',
  40992. target: this
  40993. });
  40994. }
  40995. }
  40996. get weightIntensity () {
  40997. return this.uniforms.wIntensity.value;
  40998. }
  40999. set weightIntensity (value) {
  41000. if(this.uniforms.wIntensity.value !== value){
  41001. this.uniforms.wIntensity.value = value;
  41002. this.dispatchEvent({
  41003. type: 'material_property_changed',
  41004. target: this
  41005. });
  41006. }
  41007. }
  41008. get weightElevation () {
  41009. return this.uniforms.wElevation.value;
  41010. }
  41011. set weightElevation (value) {
  41012. if(this.uniforms.wElevation.value !== value){
  41013. this.uniforms.wElevation.value = value;
  41014. this.dispatchEvent({
  41015. type: 'material_property_changed',
  41016. target: this
  41017. });
  41018. }
  41019. }
  41020. get weightClassification () {
  41021. return this.uniforms.wClassification.value;
  41022. }
  41023. set weightClassification (value) {
  41024. if(this.uniforms.wClassification.value !== value){
  41025. this.uniforms.wClassification.value = value;
  41026. this.dispatchEvent({
  41027. type: 'material_property_changed',
  41028. target: this
  41029. });
  41030. }
  41031. }
  41032. get weightReturnNumber () {
  41033. return this.uniforms.wReturnNumber.value;
  41034. }
  41035. set weightReturnNumber (value) {
  41036. if(this.uniforms.wReturnNumber.value !== value){
  41037. this.uniforms.wReturnNumber.value = value;
  41038. this.dispatchEvent({
  41039. type: 'material_property_changed',
  41040. target: this
  41041. });
  41042. }
  41043. }
  41044. get weightSourceID () {
  41045. return this.uniforms.wSourceID.value;
  41046. }
  41047. set weightSourceID (value) {
  41048. if(this.uniforms.wSourceID.value !== value){
  41049. this.uniforms.wSourceID.value = value;
  41050. this.dispatchEvent({
  41051. type: 'material_property_changed',
  41052. target: this
  41053. });
  41054. }
  41055. }
  41056. static generateGradientTexture (gradient) {
  41057. let size = 64;
  41058. // create canvas
  41059. let canvas = document.createElement('canvas');
  41060. canvas.width = size;
  41061. canvas.height = size;
  41062. // get context
  41063. let context = canvas.getContext('2d');
  41064. // draw gradient
  41065. context.rect(0, 0, size, size);
  41066. let ctxGradient = context.createLinearGradient(0, 0, size, size);
  41067. for (let i = 0; i < gradient.length; i++) {
  41068. let step = gradient[i];
  41069. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  41070. }
  41071. context.fillStyle = ctxGradient;
  41072. context.fill();
  41073. //let texture = new THREE.Texture(canvas);
  41074. let texture = new CanvasTexture(canvas);
  41075. texture.needsUpdate = true;
  41076. texture.minFilter = LinearFilter;
  41077. texture.wrap = RepeatWrapping;
  41078. texture.repeat = 2;
  41079. // textureImage = texture.image;
  41080. return texture;
  41081. }
  41082. static generateMatcapTexture (matcap) {
  41083. var url = new URL(Potree.resourcePath + "/textures/matcap/" + matcap).href;
  41084. let texture = new TextureLoader().load( url );
  41085. texture.magFilter = texture.minFilter = LinearFilter;
  41086. texture.needsUpdate = true;
  41087. // 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
  41088. // Switch matcap texture on the fly : viewer.scene.pointclouds[0].material.matcap = 'matcap1.jpg';
  41089. // 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
  41090. return texture;
  41091. }
  41092. disableEvents(){
  41093. if(this._hiddenListeners === undefined){
  41094. this._hiddenListeners = this._listeners;
  41095. this._listeners = {};
  41096. }
  41097. };
  41098. enableEvents(){
  41099. this._listeners = this._hiddenListeners;
  41100. this._hiddenListeners = undefined;
  41101. };
  41102. // copyFrom(from){
  41103. // var a = 10;
  41104. // for(let name of Object.keys(this.uniforms)){
  41105. // this.uniforms[name].value = from.uniforms[name].value;
  41106. // }
  41107. // }
  41108. // copy(from){
  41109. // this.copyFrom(from);
  41110. // }
  41111. }
  41112. //见ExtendPointCloudOctree
  41113. class PointCloudOctreeNode extends PointCloudTreeNode {
  41114. constructor () {
  41115. super();
  41116. //this.children = {};
  41117. this.children = [];
  41118. this.sceneNode = null;
  41119. this.octree = null;
  41120. }
  41121. getNumPoints () {
  41122. return this.geometryNode.numPoints;
  41123. }
  41124. isLoaded () {
  41125. return true;
  41126. }
  41127. isTreeNode () {
  41128. return true;
  41129. }
  41130. isGeometryNode () {
  41131. return false;
  41132. }
  41133. getLevel () {
  41134. return this.geometryNode.level;
  41135. }
  41136. getBoundingSphere () {
  41137. return this.geometryNode.boundingSphere;
  41138. }
  41139. getBoundingBox () {
  41140. return this.geometryNode.boundingBox;
  41141. }
  41142. getChildren () {
  41143. let children = [];
  41144. for (let i = 0; i < 8; i++) {
  41145. if (this.children[i]) {
  41146. children.push(this.children[i]);
  41147. }
  41148. }
  41149. return children;
  41150. }
  41151. getPointsInBox(boxNode){
  41152. if(!this.sceneNode){
  41153. return null;
  41154. }
  41155. let buffer = this.geometryNode.buffer;
  41156. let posOffset = buffer.offset("position");
  41157. let stride = buffer.stride;
  41158. let view = new DataView(buffer.data);
  41159. let worldToBox = boxNode.matrixWorld.clone().invert();
  41160. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, this.sceneNode.matrixWorld);
  41161. let inBox = [];
  41162. let pos = new Vector4();
  41163. for(let i = 0; i < buffer.numElements; i++){
  41164. let x = view.getFloat32(i * stride + posOffset + 0, true);
  41165. let y = view.getFloat32(i * stride + posOffset + 4, true);
  41166. let z = view.getFloat32(i * stride + posOffset + 8, true);
  41167. pos.set(x, y, z, 1);
  41168. pos.applyMatrix4(objectToBox);
  41169. if(-0.5 < pos.x && pos.x < 0.5){
  41170. if(-0.5 < pos.y && pos.y < 0.5){
  41171. if(-0.5 < pos.z && pos.z < 0.5){
  41172. pos.set(x, y, z, 1).applyMatrix4(this.sceneNode.matrixWorld);
  41173. inBox.push(new Vector3(pos.x, pos.y, pos.z));
  41174. }
  41175. }
  41176. }
  41177. }
  41178. return inBox;
  41179. }
  41180. get name () {
  41181. return this.geometryNode.name;
  41182. }
  41183. };
  41184. class PointCloudOctree extends PointCloudTree {//base
  41185. constructor (geometry, material) {
  41186. super();
  41187. this.pointBudget = Infinity; //一直是这个值
  41188. this.pcoGeometry = geometry;
  41189. this.boundingBox = this.pcoGeometry.boundingBox;
  41190. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  41191. this.material = material || new PointCloudMaterial$1();
  41192. this.visiblePointsTarget = 2 * 1000 * 1000;
  41193. this.minimumNodePixelSize = 150;
  41194. this.level = 0;
  41195. this.position.copy(geometry.offset);
  41196. this.updateMatrix();
  41197. {
  41198. let priorityQueue = ["rgba", "rgb", "intensity", "classification"];
  41199. let selected = "rgba";
  41200. for(let attributeName of priorityQueue){
  41201. let attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === attributeName);
  41202. if(!attribute){
  41203. continue;
  41204. }
  41205. let min = attribute.range[0].constructor.name === "Array" ? attribute.range[0] : [attribute.range[0]];
  41206. let max = attribute.range[1].constructor.name === "Array" ? attribute.range[1] : [attribute.range[1]];
  41207. let range_min = new Vector3(...min);
  41208. let range_max = new Vector3(...max);
  41209. let range = range_min.distanceTo(range_max);
  41210. if(range === 0){
  41211. continue;
  41212. }
  41213. selected = attributeName;
  41214. break;
  41215. }
  41216. this.material.activeAttributeName = selected;
  41217. }
  41218. this.showBoundingBox = false;
  41219. this.boundingBoxNodes = [];
  41220. this.loadQueue = [];
  41221. this.visibleBounds = new Box3();
  41222. this.visibleNodes = [];
  41223. this.visibleGeometry = [];
  41224. this.generateDEM = false;
  41225. this.profileRequests = [];
  41226. this.name = '';
  41227. this._visible = true;
  41228. {
  41229. let box = [this.pcoGeometry.tightBoundingBox, this.getBoundingBoxWorld()]
  41230. .find(v => v !== undefined);
  41231. this.updateMatrixWorld(true);
  41232. box = Utils.computeTransformedBoundingBox(box, this.matrixWorld);
  41233. let bMin = box.min.z;
  41234. let bMax = box.max.z;
  41235. this.material.heightMin = bMin;
  41236. this.material.heightMax = bMax;
  41237. }
  41238. // TODO read projection from file instead
  41239. this.projection = geometry.projection;
  41240. this.fallbackProjection = geometry.fallbackProjection;
  41241. this.root = this.pcoGeometry.root;
  41242. }
  41243. setName (name) {
  41244. if (this.name !== name) {
  41245. this.name = name;
  41246. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  41247. }
  41248. }
  41249. getName () {
  41250. return this.name;
  41251. }
  41252. getAttribute(name){
  41253. const attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === name);
  41254. if(attribute){
  41255. return attribute;
  41256. }else {
  41257. return null;
  41258. }
  41259. }
  41260. getAttributes(){
  41261. return this.pcoGeometry.pointAttributes;
  41262. }
  41263. toTreeNode (geometryNode, parent) {
  41264. let node = new PointCloudOctreeNode();
  41265. // if(geometryNode.name === "r40206"){
  41266. // console.log("creating node for r40206");
  41267. // }
  41268. let sceneNode = new Points(geometryNode.geometry, this.material);
  41269. sceneNode.name = geometryNode.name;
  41270. sceneNode.position.copy(geometryNode.boundingBox.min);
  41271. sceneNode.frustumCulled = false;
  41272. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  41273. if (material.program) {
  41274. _this.getContext().useProgram(material.program.program);
  41275. if (material.program.getUniforms().map.level) {
  41276. let level = geometryNode.getLevel();
  41277. material.uniforms.level.value = level;
  41278. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  41279. }
  41280. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  41281. let vnStart = this.visibleNodeTextureOffsets.get(node);
  41282. material.uniforms.vnStart.value = vnStart;
  41283. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  41284. }
  41285. if (material.program.getUniforms().map.pcIndex) {
  41286. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  41287. material.uniforms.pcIndex.value = i;
  41288. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  41289. }
  41290. }
  41291. };
  41292. // { // DEBUG
  41293. // let sg = new THREE.SphereGeometry(1, 16, 16);
  41294. // let sm = new THREE.MeshNormalMaterial();
  41295. // let s = new THREE.Mesh(sg, sm);
  41296. // s.scale.set(5, 5, 5);
  41297. // s.position.copy(geometryNode.mean)
  41298. // .add(this.position)
  41299. // .add(geometryNode.boundingBox.min);
  41300. //
  41301. // viewer.scene.scene.add(s);
  41302. // }
  41303. node.geometryNode = geometryNode;
  41304. node.sceneNode = sceneNode;
  41305. node.pointcloud = this;
  41306. node.children = [];
  41307. //for (let key in geometryNode.children) {
  41308. // node.children[key] = geometryNode.children[key];
  41309. //}
  41310. for(let i = 0; i < 8; i++){
  41311. node.children[i] = geometryNode.children[i];
  41312. }
  41313. if (!parent) {
  41314. this.root = node;
  41315. this.add(sceneNode);
  41316. } else {
  41317. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  41318. parent.sceneNode.add(sceneNode);
  41319. parent.children[childIndex] = node;
  41320. }
  41321. let disposeListener = function () {
  41322. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  41323. parent.sceneNode.remove(node.sceneNode);
  41324. parent.children[childIndex] = geometryNode;
  41325. };
  41326. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  41327. return node;
  41328. }
  41329. updateVisibleBounds () {
  41330. let leafNodes = [];
  41331. for (let i = 0; i < this.visibleNodes.length; i++) {
  41332. let node = this.visibleNodes[i];
  41333. let isLeaf = true;
  41334. for (let j = 0; j < node.children.length; j++) {
  41335. let child = node.children[j];
  41336. if (child instanceof PointCloudOctreeNode) {
  41337. isLeaf = isLeaf && !child.sceneNode.visible;
  41338. } else if (child instanceof PointCloudOctreeGeometryNode) {
  41339. isLeaf = true;
  41340. }
  41341. }
  41342. if (isLeaf) {
  41343. leafNodes.push(node);
  41344. }
  41345. }
  41346. this.visibleBounds.min = new Vector3(Infinity, Infinity, Infinity);
  41347. this.visibleBounds.max = new Vector3(-Infinity, -Infinity, -Infinity);
  41348. for (let i = 0; i < leafNodes.length; i++) {
  41349. let node = leafNodes[i];
  41350. this.visibleBounds.expandByPoint(node.getBoundingBox().min);
  41351. this.visibleBounds.expandByPoint(node.getBoundingBox().max);
  41352. }
  41353. }
  41354. updateMaterial (material, visibleNodes, camera, renderer) {
  41355. material.fov = camera.fov * (Math.PI / 180);
  41356. material.screenWidth = renderer.domElement.clientWidth;
  41357. material.screenHeight = renderer.domElement.clientHeight;
  41358. material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  41359. material.near = camera.near;
  41360. material.far = camera.far;
  41361. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  41362. }
  41363. computeVisibilityTextureData(nodes, camera){
  41364. if(Potree.measureTimings) performance.mark("computeVisibilityTextureData-start");
  41365. let data = new Uint8Array(nodes.length * 4);
  41366. let visibleNodeTextureOffsets = new Map();
  41367. // copy array
  41368. nodes = nodes.slice();
  41369. // sort by level and index, e.g. r, r0, r3, r4, r01, r07, r30, ...
  41370. let sort = function (a, b) {
  41371. let na = a.geometryNode.name;
  41372. let nb = b.geometryNode.name;
  41373. if (na.length !== nb.length) return na.length - nb.length;
  41374. if (na < nb) return -1;
  41375. if (na > nb) return 1;
  41376. return 0;
  41377. };
  41378. nodes.sort(sort);
  41379. let worldDir = new Vector3();
  41380. let nodeMap = new Map();
  41381. let offsetsToChild = new Array(nodes.length).fill(Infinity);
  41382. for(let i = 0; i < nodes.length; i++){
  41383. let node = nodes[i];
  41384. nodeMap.set(node.name, node);
  41385. visibleNodeTextureOffsets.set(node, i);
  41386. if(i > 0){
  41387. let index = parseInt(node.name.slice(-1));
  41388. let parentName = node.name.slice(0, -1);
  41389. let parent = nodeMap.get(parentName);
  41390. let parentOffset = visibleNodeTextureOffsets.get(parent);
  41391. let parentOffsetToChild = (i - parentOffset);
  41392. offsetsToChild[parentOffset] = Math.min(offsetsToChild[parentOffset], parentOffsetToChild);
  41393. data[parentOffset * 4 + 0] = data[parentOffset * 4 + 0] | (1 << index);
  41394. data[parentOffset * 4 + 1] = (offsetsToChild[parentOffset] >> 8);
  41395. data[parentOffset * 4 + 2] = (offsetsToChild[parentOffset] % 256);
  41396. }
  41397. let density = node.geometryNode.density;
  41398. if(typeof density === "number"){
  41399. let lodOffset = Math.log2(density) / 2 - 1.5;
  41400. let offsetUint8 = (lodOffset + 10) * 10;
  41401. data[i * 4 + 3] = offsetUint8;
  41402. }else {
  41403. data[i * 4 + 3] = 100;
  41404. }
  41405. }
  41406. if(Potree.measureTimings){
  41407. performance.mark("computeVisibilityTextureData-end");
  41408. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  41409. }
  41410. return {
  41411. data: data,
  41412. offsets: visibleNodeTextureOffsets
  41413. };
  41414. }
  41415. nodeIntersectsProfile (node, profile) {
  41416. let bbWorld = node.boundingBox.clone().applyMatrix4(this.matrixWorld);
  41417. let bsWorld = bbWorld.getBoundingSphere(new Sphere());
  41418. let intersects = false;
  41419. for (let i = 0; i < profile.points.length - 1; i++) {
  41420. let start = new Vector3(profile.points[i + 0].x, profile.points[i + 0].y, bsWorld.center.z);
  41421. let end = new Vector3(profile.points[i + 1].x, profile.points[i + 1].y, bsWorld.center.z);
  41422. let closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  41423. let distance = closest.distanceTo(bsWorld.center);
  41424. intersects = intersects || (distance < (bsWorld.radius + profile.width));
  41425. }
  41426. //console.log(`${node.name}: ${intersects}`);
  41427. return intersects;
  41428. }
  41429. deepestNodeAt(position){
  41430. const toObjectSpace = this.matrixWorld.clone().invert();
  41431. const objPos = position.clone().applyMatrix4(toObjectSpace);
  41432. let current = this.root;
  41433. while(true){
  41434. let containingChild = null;
  41435. for(const child of current.children){
  41436. if(child !== undefined){
  41437. if(child.getBoundingBox().containsPoint(objPos)){
  41438. containingChild = child;
  41439. }
  41440. }
  41441. }
  41442. if(containingChild !== null && containingChild instanceof PointCloudOctreeNode){
  41443. current = containingChild;
  41444. }else {
  41445. break;
  41446. }
  41447. }
  41448. const deepest = current;
  41449. return deepest;
  41450. }
  41451. nodesOnRay (nodes, ray) {
  41452. let nodesOnRay = [];
  41453. let _ray = ray.clone();
  41454. for (let i = 0; i < nodes.length; i++) {
  41455. let node = nodes[i];
  41456. let sphere = node.getBoundingSphere().clone().applyMatrix4(this.matrixWorld);
  41457. if (_ray.intersectsSphere(sphere)) {
  41458. nodesOnRay.push(node);
  41459. }
  41460. }
  41461. return nodesOnRay;
  41462. }
  41463. updateMatrixWorld (force) {
  41464. if (this.matrixAutoUpdate === true) this.updateMatrix();
  41465. if (this.matrixWorldNeedsUpdate === true || force === true) {
  41466. if (!this.parent) {
  41467. this.matrixWorld.copy(this.matrix);
  41468. } else {
  41469. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  41470. }
  41471. this.matrixWorldNeedsUpdate = false;
  41472. force = true;
  41473. }
  41474. }
  41475. hideDescendants (object) {
  41476. let stack = [];
  41477. for (let i = 0; i < object.children.length; i++) {
  41478. let child = object.children[i];
  41479. if (child.visible) {
  41480. stack.push(child);
  41481. }
  41482. }
  41483. while (stack.length > 0) {
  41484. let object = stack.shift();
  41485. object.visible = false;
  41486. for (let i = 0; i < object.children.length; i++) {
  41487. let child = object.children[i];
  41488. if (child.visible) {
  41489. stack.push(child);
  41490. }
  41491. }
  41492. }
  41493. }
  41494. moveToOrigin () {
  41495. this.position.set(0, 0, 0);
  41496. this.updateMatrixWorld(true);
  41497. let box = this.boundingBox;
  41498. let transform = this.matrixWorld;
  41499. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  41500. this.position.set(0, 0, 0).sub(tBox.getCenter(new Vector3()));
  41501. };
  41502. moveToGroundPlane () {
  41503. this.updateMatrixWorld(true);
  41504. let box = this.boundingBox;
  41505. let transform = this.matrixWorld;
  41506. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  41507. this.position.y += -tBox.min.y;
  41508. };
  41509. getBoundingBoxWorld () {
  41510. this.updateMatrixWorld(true);
  41511. let box = this.boundingBox;
  41512. let transform = this.matrixWorld;
  41513. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  41514. return tBox;
  41515. };
  41516. /**
  41517. * returns points inside the profile points
  41518. *
  41519. * maxDepth: search points up to the given octree depth
  41520. *
  41521. *
  41522. * The return value is an array with all segments of the profile path
  41523. * let segment = {
  41524. * start: THREE.Vector3,
  41525. * end: THREE.Vector3,
  41526. * points: {}
  41527. * project: function()
  41528. * };
  41529. *
  41530. * The project() function inside each segment can be used to transform
  41531. * that segments point coordinates to line up along the x-axis.
  41532. *
  41533. *
  41534. */
  41535. getPointsInProfile (profile, maxDepth, callback) {
  41536. if (callback) {
  41537. let request = new Potree.ProfileRequest(this, profile, maxDepth, callback);
  41538. this.profileRequests.push(request);
  41539. return request;
  41540. }
  41541. let points = {
  41542. segments: [],
  41543. boundingBox: new Box3(),
  41544. projectedBoundingBox: new Box2()
  41545. };
  41546. // evaluate segments
  41547. for (let i = 0; i < profile.points.length - 1; i++) {
  41548. let start = profile.points[i];
  41549. let end = profile.points[i + 1];
  41550. let ps = this.getProfile(start, end, profile.width, maxDepth);
  41551. let segment = {
  41552. start: start,
  41553. end: end,
  41554. points: ps,
  41555. project: null
  41556. };
  41557. points.segments.push(segment);
  41558. points.boundingBox.expandByPoint(ps.boundingBox.min);
  41559. points.boundingBox.expandByPoint(ps.boundingBox.max);
  41560. }
  41561. // add projection functions to the segments
  41562. let mileage = new Vector3();
  41563. for (let i = 0; i < points.segments.length; i++) {
  41564. let segment = points.segments[i];
  41565. let start = segment.start;
  41566. let end = segment.end;
  41567. let project = (function (_start, _end, _mileage, _boundingBox) {
  41568. let start = _start;
  41569. let end = _end;
  41570. let mileage = _mileage;
  41571. let boundingBox = _boundingBox;
  41572. let xAxis = new Vector3(1, 0, 0);
  41573. let dir = new Vector3().subVectors(end, start);
  41574. dir.y = 0;
  41575. dir.normalize();
  41576. let alpha = Math.acos(xAxis.dot(dir));
  41577. if (dir.z > 0) {
  41578. alpha = -alpha;
  41579. }
  41580. return function (position) {
  41581. let toOrigin = new Matrix4().makeTranslation(-start.x, -boundingBox.min.y, -start.z);
  41582. let alignWithX = new Matrix4().makeRotationY(-alpha);
  41583. let applyMileage = new Matrix4().makeTranslation(mileage.x, 0, 0);
  41584. let pos = position.clone();
  41585. pos.applyMatrix4(toOrigin);
  41586. pos.applyMatrix4(alignWithX);
  41587. pos.applyMatrix4(applyMileage);
  41588. return pos;
  41589. };
  41590. }(start, end, mileage.clone(), points.boundingBox.clone()));
  41591. segment.project = project;
  41592. mileage.x += new Vector3(start.x, 0, start.z).distanceTo(new Vector3(end.x, 0, end.z));
  41593. mileage.y += end.y - start.y;
  41594. }
  41595. points.projectedBoundingBox.min.x = 0;
  41596. points.projectedBoundingBox.min.y = points.boundingBox.min.y;
  41597. points.projectedBoundingBox.max.x = mileage.x;
  41598. points.projectedBoundingBox.max.y = points.boundingBox.max.y;
  41599. return points;
  41600. }
  41601. /**
  41602. * returns points inside the given profile bounds.
  41603. *
  41604. * start:
  41605. * end:
  41606. * width:
  41607. * depth: search points up to the given octree depth
  41608. * callback: if specified, points are loaded before searching
  41609. *
  41610. *
  41611. */
  41612. getProfile (start, end, width, depth, callback) {
  41613. let request = new Potree.ProfileRequest(start, end, width, depth, callback);
  41614. this.profileRequests.push(request);
  41615. };
  41616. getVisibleExtent () {
  41617. return this.visibleBounds.applyMatrix4(this.matrixWorld);
  41618. };
  41619. intersectsPoint(position){
  41620. let rootAvailable = this.pcoGeometry.root && this.pcoGeometry.root.geometry;
  41621. if(!rootAvailable){
  41622. return false;
  41623. }
  41624. if(typeof this.signedDistanceField === "undefined"){
  41625. const resolution = 32;
  41626. const field = new Float32Array(resolution ** 3).fill(Infinity);
  41627. const positions = this.pcoGeometry.root.geometry.attributes.position;
  41628. const boundingBox = this.boundingBox;
  41629. const n = positions.count;
  41630. for(let i = 0; i < n; i = i + 3){
  41631. const x = positions.array[3 * i + 0];
  41632. const y = positions.array[3 * i + 1];
  41633. const z = positions.array[3 * i + 2];
  41634. const ix = parseInt(Math.min(resolution * (x / boundingBox.max.x), resolution - 1));
  41635. const iy = parseInt(Math.min(resolution * (y / boundingBox.max.y), resolution - 1));
  41636. const iz = parseInt(Math.min(resolution * (z / boundingBox.max.z), resolution - 1));
  41637. const index = ix + iy * resolution + iz * resolution * resolution;
  41638. field[index] = 0;
  41639. }
  41640. const sdf = {
  41641. resolution: resolution,
  41642. field: field,
  41643. };
  41644. this.signedDistanceField = sdf;
  41645. }
  41646. {
  41647. const sdf = this.signedDistanceField;
  41648. const boundingBox = this.boundingBox;
  41649. const toObjectSpace = this.matrixWorld.clone().invert();
  41650. const objPos = position.clone().applyMatrix4(toObjectSpace);
  41651. const resolution = sdf.resolution;
  41652. const ix = parseInt(resolution * (objPos.x / boundingBox.max.x));
  41653. const iy = parseInt(resolution * (objPos.y / boundingBox.max.y));
  41654. const iz = parseInt(resolution * (objPos.z / boundingBox.max.z));
  41655. if(ix < 0 || iy < 0 || iz < 0){
  41656. return false;
  41657. }
  41658. if(ix >= resolution || iy >= resolution || iz >= resolution){
  41659. return false;
  41660. }
  41661. const index = ix + iy * resolution + iz * resolution * resolution;
  41662. const value = sdf.field[index];
  41663. if(value === 0){
  41664. return true;
  41665. }
  41666. }
  41667. return false;
  41668. }
  41669. /**
  41670. *
  41671. *
  41672. *
  41673. * params.pickWindowSize: Look for points inside a pixel window of this size.
  41674. * Use odd values: 1, 3, 5, ...
  41675. *
  41676. *
  41677. * TODO: only draw pixels that are actually read with readPixels().
  41678. *
  41679. */
  41680. pick(viewer, camera, ray, params = {}){
  41681. let renderer = viewer.renderer;
  41682. let pRenderer = viewer.pRenderer;
  41683. performance.mark("pick-start");
  41684. let getVal = (a, b) => a !== undefined ? a : b;
  41685. let pickWindowSize = getVal(params.pickWindowSize, 65);
  41686. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  41687. let size = renderer.getSize(new Vector2());
  41688. let width = Math.ceil(getVal(params.width, size.width));
  41689. let height = Math.ceil(getVal(params.height, size.height));
  41690. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  41691. let pointSize = getVal(params.pointSize, this.material.size);
  41692. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  41693. if (nodes.length === 0) {
  41694. return null;
  41695. }
  41696. if (!this.pickState) {
  41697. let scene = new Scene();
  41698. let material = new Potree.PointCloudMaterial();
  41699. material.activeAttributeName = "indices";
  41700. let renderTarget = new WebGLRenderTarget(
  41701. 1, 1,
  41702. { minFilter: LinearFilter,
  41703. magFilter: NearestFilter,
  41704. format: RGBAFormat }
  41705. );
  41706. this.pickState = {
  41707. renderTarget: renderTarget,
  41708. material: material,
  41709. scene: scene
  41710. };
  41711. };
  41712. let pickState = this.pickState;
  41713. let pickMaterial = pickState.material;
  41714. { // update pick material
  41715. pickMaterial.pointSizeType = pointSizeType;
  41716. //pickMaterial.shape = this.material.shape;
  41717. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  41718. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  41719. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  41720. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  41721. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  41722. pickMaterial.activeAttributeName = "indices";
  41723. pickMaterial.size = pointSize;
  41724. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  41725. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  41726. pickMaterial.classification = this.material.classification;
  41727. pickMaterial.recomputeClassification();
  41728. if(params.pickClipped){
  41729. pickMaterial.clipBoxes = this.material.clipBoxes;
  41730. pickMaterial.uniforms.clipBoxes = this.material.uniforms.clipBoxes;
  41731. if(this.material.clipTask === Potree.ClipTask.HIGHLIGHT){
  41732. pickMaterial.clipTask = Potree.ClipTask.NONE;
  41733. }else {
  41734. pickMaterial.clipTask = this.material.clipTask;
  41735. }
  41736. pickMaterial.clipMethod = this.material.clipMethod;
  41737. }else {
  41738. pickMaterial.clipBoxes = [];
  41739. }
  41740. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  41741. }
  41742. pickState.renderTarget.setSize(width, height);
  41743. let pixelPos = new Vector2(params.x, params.y);
  41744. let gl = renderer.getContext();
  41745. gl.enable(gl.SCISSOR_TEST);
  41746. gl.scissor(
  41747. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  41748. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  41749. parseInt(pickWindowSize), parseInt(pickWindowSize));
  41750. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  41751. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  41752. renderer.state.setBlending(NoBlending);
  41753. { // RENDER
  41754. renderer.setRenderTarget(pickState.renderTarget);
  41755. gl.clearColor(0, 0, 0, 0);
  41756. renderer.clear(true, true, true);
  41757. let tmp = this.material;
  41758. this.material = pickMaterial;
  41759. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  41760. this.material = tmp;
  41761. }
  41762. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  41763. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  41764. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  41765. let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  41766. let h = parseInt(Math.min(y + pickWindowSize, height) - y);
  41767. let pixelCount = w * h;
  41768. let buffer = new Uint8Array(4 * pixelCount);
  41769. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  41770. renderer.setRenderTarget(null);
  41771. renderer.state.reset();
  41772. renderer.setScissorTest(false);
  41773. gl.disable(gl.SCISSOR_TEST);
  41774. let pixels = buffer;
  41775. let ibuffer = new Uint32Array(buffer.buffer);
  41776. // find closest hit inside pixelWindow boundaries
  41777. let min = Number.MAX_VALUE;
  41778. let hits = [];
  41779. for (let u = 0; u < pickWindowSize; u++) {
  41780. for (let v = 0; v < pickWindowSize; v++) {
  41781. let offset = (u + v * pickWindowSize);
  41782. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  41783. let pcIndex = pixels[4 * offset + 3];
  41784. pixels[4 * offset + 3] = 0;
  41785. let pIndex = ibuffer[offset];
  41786. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  41787. let hit = {
  41788. pIndex: pIndex,
  41789. pcIndex: pcIndex,
  41790. distanceToCenter: distance
  41791. };
  41792. if(params.all){
  41793. hits.push(hit);
  41794. }else {
  41795. if(hits.length > 0){
  41796. if(distance < hits[0].distanceToCenter){
  41797. hits[0] = hit;
  41798. }
  41799. }else {
  41800. hits.push(hit);
  41801. }
  41802. }
  41803. }
  41804. }
  41805. }
  41806. // { // DEBUG: show panel with pick image
  41807. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  41808. // let screenshot = img.src;
  41809. // if(!this.debugDIV){
  41810. // this.debugDIV = $(`
  41811. // <div id="pickDebug"
  41812. // style="position: absolute;
  41813. // right: 400px; width: 300px;
  41814. // bottom: 44px; width: 300px;
  41815. // z-index: 1000;
  41816. // "></div>`);
  41817. // $(document.body).append(this.debugDIV);
  41818. // }
  41819. // this.debugDIV.empty();
  41820. // this.debugDIV.append($(`<img src="${screenshot}"
  41821. // style="transform: scaleY(-1); width: 300px"/>`));
  41822. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  41823. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  41824. // }
  41825. for(let hit of hits){
  41826. let point = {};
  41827. if (!nodes[hit.pcIndex]) {
  41828. return null;
  41829. }
  41830. let node = nodes[hit.pcIndex];
  41831. let pc = node.sceneNode;
  41832. let geometry = node.geometryNode.geometry;
  41833. for(let attributeName in geometry.attributes){
  41834. let attribute = geometry.attributes[attributeName];
  41835. if (attributeName === 'position') {
  41836. let x = attribute.array[3 * hit.pIndex + 0];
  41837. let y = attribute.array[3 * hit.pIndex + 1];
  41838. let z = attribute.array[3 * hit.pIndex + 2];
  41839. let position = new Vector3(x, y, z);
  41840. position.applyMatrix4(pc.matrixWorld);
  41841. point[attributeName] = position;
  41842. } else if (attributeName === 'indices') {
  41843. } else {
  41844. let values = attribute.array.slice(attribute.itemSize * hit.pIndex, attribute.itemSize * (hit.pIndex + 1)) ;
  41845. if(attribute.potree){
  41846. const {scale, offset} = attribute.potree;
  41847. values = values.map(v => v / scale + offset);
  41848. }
  41849. point[attributeName] = values;
  41850. //debugger;
  41851. //if (values.itemSize === 1) {
  41852. // point[attribute.name] = values.array[hit.pIndex];
  41853. //} else {
  41854. // let value = [];
  41855. // for (let j = 0; j < values.itemSize; j++) {
  41856. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  41857. // }
  41858. // point[attribute.name] = value;
  41859. //}
  41860. }
  41861. }
  41862. hit.point = point;
  41863. }
  41864. performance.mark("pick-end");
  41865. performance.measure("pick", "pick-start", "pick-end");
  41866. if(params.all){
  41867. return hits.map(hit => hit.point);
  41868. }else {
  41869. if(hits.length === 0){
  41870. return null;
  41871. }else {
  41872. return hits[0].point;
  41873. //let sorted = hits.sort( (a, b) => a.distanceToCenter - b.distanceToCenter);
  41874. //return sorted[0].point;
  41875. }
  41876. }
  41877. };
  41878. * getFittedBoxGen(boxNode){
  41879. let start = performance.now();
  41880. let shrinkedLocalBounds = new Box3();
  41881. let worldToBox = boxNode.matrixWorld.clone().invert();
  41882. for(let node of this.visibleNodes){
  41883. if(!node.sceneNode){
  41884. continue;
  41885. }
  41886. let buffer = node.geometryNode.buffer;
  41887. let posOffset = buffer.offset("position");
  41888. let stride = buffer.stride;
  41889. let view = new DataView(buffer.data);
  41890. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  41891. let pos = new Vector4();
  41892. for(let i = 0; i < buffer.numElements; i++){
  41893. let x = view.getFloat32(i * stride + posOffset + 0, true);
  41894. let y = view.getFloat32(i * stride + posOffset + 4, true);
  41895. let z = view.getFloat32(i * stride + posOffset + 8, true);
  41896. pos.set(x, y, z, 1);
  41897. pos.applyMatrix4(objectToBox);
  41898. if(-0.5 < pos.x && pos.x < 0.5){
  41899. if(-0.5 < pos.y && pos.y < 0.5){
  41900. if(-0.5 < pos.z && pos.z < 0.5){
  41901. shrinkedLocalBounds.expandByPoint(pos);
  41902. }
  41903. }
  41904. }
  41905. }
  41906. yield;
  41907. }
  41908. let fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  41909. let fitted = new Object3D();
  41910. fitted.position.copy(fittedPosition);
  41911. fitted.scale.copy(boxNode.scale);
  41912. fitted.rotation.copy(boxNode.rotation);
  41913. let ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  41914. fitted.scale.multiply(ds);
  41915. let duration = performance.now() - start;
  41916. console.log("duration: ", duration);
  41917. yield fitted;
  41918. }
  41919. getFittedBox(boxNode, maxLevel = Infinity){
  41920. maxLevel = Infinity;
  41921. let start = performance.now();
  41922. let shrinkedLocalBounds = new Box3();
  41923. let worldToBox = boxNode.matrixWorld.clone().invert();
  41924. for(let node of this.visibleNodes){
  41925. if(!node.sceneNode || node.getLevel() > maxLevel){
  41926. continue;
  41927. }
  41928. let buffer = node.geometryNode.buffer;
  41929. let posOffset = buffer.offset("position");
  41930. let stride = buffer.stride;
  41931. let view = new DataView(buffer.data);
  41932. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  41933. let pos = new Vector4();
  41934. for(let i = 0; i < buffer.numElements; i++){
  41935. let x = view.getFloat32(i * stride + posOffset + 0, true);
  41936. let y = view.getFloat32(i * stride + posOffset + 4, true);
  41937. let z = view.getFloat32(i * stride + posOffset + 8, true);
  41938. pos.set(x, y, z, 1);
  41939. pos.applyMatrix4(objectToBox);
  41940. if(-0.5 < pos.x && pos.x < 0.5){
  41941. if(-0.5 < pos.y && pos.y < 0.5){
  41942. if(-0.5 < pos.z && pos.z < 0.5){
  41943. shrinkedLocalBounds.expandByPoint(pos);
  41944. }
  41945. }
  41946. }
  41947. }
  41948. }
  41949. let fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  41950. let fitted = new Object3D();
  41951. fitted.position.copy(fittedPosition);
  41952. fitted.scale.copy(boxNode.scale);
  41953. fitted.rotation.copy(boxNode.rotation);
  41954. let ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  41955. fitted.scale.multiply(ds);
  41956. let duration = performance.now() - start;
  41957. console.log("duration: ", duration);
  41958. return fitted;
  41959. }
  41960. get progress () {
  41961. return this.visibleNodes.length / this.visibleGeometry.length;
  41962. }
  41963. find(name){
  41964. let node = null;
  41965. for(let char of name){
  41966. if(char === "r"){
  41967. node = this.root;
  41968. }else {
  41969. node = node.children[char];
  41970. }
  41971. }
  41972. return node;
  41973. }
  41974. get visible(){
  41975. return this._visible;
  41976. }
  41977. set visible(value){
  41978. if(value !== this._visible){
  41979. this._visible = value;
  41980. this.dispatchEvent({type: 'visibility_changed', pointcloud: this});
  41981. }
  41982. }
  41983. }
  41984. class PointCloudArena4DNode extends PointCloudTreeNode {
  41985. constructor () {
  41986. super();
  41987. this.left = null;
  41988. this.right = null;
  41989. this.sceneNode = null;
  41990. this.kdtree = null;
  41991. }
  41992. getNumPoints () {
  41993. return this.geometryNode.numPoints;
  41994. }
  41995. isLoaded () {
  41996. return true;
  41997. }
  41998. isTreeNode () {
  41999. return true;
  42000. }
  42001. isGeometryNode () {
  42002. return false;
  42003. }
  42004. getLevel () {
  42005. return this.geometryNode.level;
  42006. }
  42007. getBoundingSphere () {
  42008. return this.geometryNode.boundingSphere;
  42009. }
  42010. getBoundingBox () {
  42011. return this.geometryNode.boundingBox;
  42012. }
  42013. toTreeNode (child) {
  42014. let geometryNode = null;
  42015. if (this.left === child) {
  42016. geometryNode = this.left;
  42017. } else if (this.right === child) {
  42018. geometryNode = this.right;
  42019. }
  42020. if (!geometryNode.loaded) {
  42021. return;
  42022. }
  42023. let node = new PointCloudArena4DNode();
  42024. let sceneNode = PointCloud(geometryNode.geometry, this.kdtree.material);
  42025. sceneNode.visible = false;
  42026. node.kdtree = this.kdtree;
  42027. node.geometryNode = geometryNode;
  42028. node.sceneNode = sceneNode;
  42029. node.parent = this;
  42030. node.left = this.geometryNode.left;
  42031. node.right = this.geometryNode.right;
  42032. }
  42033. getChildren () {
  42034. let children = [];
  42035. if (this.left) {
  42036. children.push(this.left);
  42037. }
  42038. if (this.right) {
  42039. children.push(this.right);
  42040. }
  42041. return children;
  42042. }
  42043. };
  42044. class PointCloudArena4D$1 extends PointCloudTree{
  42045. constructor (geometry) {
  42046. super();
  42047. this.root = null;
  42048. if (geometry.root) {
  42049. this.root = geometry.root;
  42050. } else {
  42051. geometry.addEventListener('hierarchy_loaded', () => {
  42052. this.root = geometry.root;
  42053. });
  42054. }
  42055. this.visiblePointsTarget = 2 * 1000 * 1000;
  42056. this.minimumNodePixelSize = 150;
  42057. this.position.sub(geometry.offset);
  42058. this.updateMatrix();
  42059. this.numVisibleNodes = 0;
  42060. this.numVisiblePoints = 0;
  42061. this.boundingBoxNodes = [];
  42062. this.loadQueue = [];
  42063. this.visibleNodes = [];
  42064. this.pcoGeometry = geometry;
  42065. this.boundingBox = this.pcoGeometry.boundingBox;
  42066. this.boundingSphere = this.pcoGeometry.boundingSphere;
  42067. this.material = new PointCloudMaterial$1({vertexColors: VertexColors, size: 0.05, treeType: TreeType.KDTREE});
  42068. this.material.sizeType = PointSizeType.ATTENUATED;
  42069. this.material.size = 0.05;
  42070. this.profileRequests = [];
  42071. this.name = '';
  42072. }
  42073. getBoundingBoxWorld () {
  42074. this.updateMatrixWorld(true);
  42075. let box = this.boundingBox;
  42076. let transform = this.matrixWorld;
  42077. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  42078. return tBox;
  42079. };
  42080. setName (name) {
  42081. if (this.name !== name) {
  42082. this.name = name;
  42083. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  42084. }
  42085. }
  42086. getName () {
  42087. return this.name;
  42088. }
  42089. getLevel () {
  42090. return this.level;
  42091. }
  42092. toTreeNode (geometryNode, parent) {
  42093. let node = new PointCloudArena4DNode();
  42094. let sceneNode = new Points(geometryNode.geometry, this.material);
  42095. sceneNode.frustumCulled = false;
  42096. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  42097. if (material.program) {
  42098. _this.getContext().useProgram(material.program.program);
  42099. if (material.program.getUniforms().map.level) {
  42100. let level = geometryNode.getLevel();
  42101. material.uniforms.level.value = level;
  42102. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  42103. }
  42104. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  42105. let vnStart = this.visibleNodeTextureOffsets.get(node);
  42106. material.uniforms.vnStart.value = vnStart;
  42107. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  42108. }
  42109. if (material.program.getUniforms().map.pcIndex) {
  42110. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  42111. material.uniforms.pcIndex.value = i;
  42112. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  42113. }
  42114. }
  42115. };
  42116. node.geometryNode = geometryNode;
  42117. node.sceneNode = sceneNode;
  42118. node.pointcloud = this;
  42119. node.left = geometryNode.left;
  42120. node.right = geometryNode.right;
  42121. if (!parent) {
  42122. this.root = node;
  42123. this.add(sceneNode);
  42124. } else {
  42125. parent.sceneNode.add(sceneNode);
  42126. if (parent.left === geometryNode) {
  42127. parent.left = node;
  42128. } else if (parent.right === geometryNode) {
  42129. parent.right = node;
  42130. }
  42131. }
  42132. let disposeListener = function () {
  42133. parent.sceneNode.remove(node.sceneNode);
  42134. if (parent.left === node) {
  42135. parent.left = geometryNode;
  42136. } else if (parent.right === node) {
  42137. parent.right = geometryNode;
  42138. }
  42139. };
  42140. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  42141. return node;
  42142. }
  42143. updateMaterial (material, visibleNodes, camera, renderer) {
  42144. material.fov = camera.fov * (Math.PI / 180);
  42145. material.screenWidth = renderer.domElement.clientWidth;
  42146. material.screenHeight = renderer.domElement.clientHeight;
  42147. material.spacing = this.pcoGeometry.spacing;
  42148. material.near = camera.near;
  42149. material.far = camera.far;
  42150. // reduce shader source updates by setting maxLevel slightly higher than actually necessary
  42151. if (this.maxLevel > material.levels) {
  42152. material.levels = this.maxLevel + 2;
  42153. }
  42154. // material.uniforms.octreeSize.value = this.boundingBox.size().x;
  42155. let bbSize = this.boundingBox.getSize(new Vector3());
  42156. material.bbSize = [bbSize.x, bbSize.y, bbSize.z];
  42157. }
  42158. updateVisibleBounds () {
  42159. }
  42160. hideDescendants (object) {
  42161. let stack = [];
  42162. for (let i = 0; i < object.children.length; i++) {
  42163. let child = object.children[i];
  42164. if (child.visible) {
  42165. stack.push(child);
  42166. }
  42167. }
  42168. while (stack.length > 0) {
  42169. let child = stack.shift();
  42170. child.visible = false;
  42171. if (child.boundingBoxNode) {
  42172. child.boundingBoxNode.visible = false;
  42173. }
  42174. for (let i = 0; i < child.children.length; i++) {
  42175. let childOfChild = child.children[i];
  42176. if (childOfChild.visible) {
  42177. stack.push(childOfChild);
  42178. }
  42179. }
  42180. }
  42181. }
  42182. updateMatrixWorld (force) {
  42183. // node.matrixWorld.multiplyMatrices( node.parent.matrixWorld, node.matrix );
  42184. if (this.matrixAutoUpdate === true) this.updateMatrix();
  42185. if (this.matrixWorldNeedsUpdate === true || force === true) {
  42186. if (this.parent === undefined) {
  42187. this.matrixWorld.copy(this.matrix);
  42188. } else {
  42189. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  42190. }
  42191. this.matrixWorldNeedsUpdate = false;
  42192. force = true;
  42193. }
  42194. }
  42195. nodesOnRay (nodes, ray) {
  42196. let nodesOnRay = [];
  42197. let _ray = ray.clone();
  42198. for (let i = 0; i < nodes.length; i++) {
  42199. let node = nodes[i];
  42200. let sphere = node.getBoundingSphere().clone().applyMatrix4(node.sceneNode.matrixWorld);
  42201. // TODO Unused: let box = node.getBoundingBox().clone().applyMatrix4(node.sceneNode.matrixWorld);
  42202. if (_ray.intersectsSphere(sphere)) {
  42203. nodesOnRay.push(node);
  42204. }
  42205. // if(_ray.isIntersectionBox(box)){
  42206. // nodesOnRay.push(node);
  42207. // }
  42208. }
  42209. return nodesOnRay;
  42210. }
  42211. pick(viewer, camera, ray, params = {}){
  42212. let renderer = viewer.renderer;
  42213. let pRenderer = viewer.pRenderer;
  42214. performance.mark("pick-start");
  42215. let getVal = (a, b) => a !== undefined ? a : b;
  42216. let pickWindowSize = getVal(params.pickWindowSize, 17);
  42217. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  42218. let size = renderer.getSize(new Vector2());
  42219. let width = Math.ceil(getVal(params.width, size.width));
  42220. let height = Math.ceil(getVal(params.height, size.height));
  42221. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  42222. let pointSize = getVal(params.pointSize, this.material.size);
  42223. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  42224. if (nodes.length === 0) {
  42225. return null;
  42226. }
  42227. if (!this.pickState) {
  42228. let scene = new Scene();
  42229. let material = new PointCloudMaterial$1();
  42230. material.activeAttributeName = "indices";
  42231. let renderTarget = new WebGLRenderTarget(
  42232. 1, 1,
  42233. { minFilter: LinearFilter,
  42234. magFilter: NearestFilter,
  42235. format: RGBAFormat }
  42236. );
  42237. this.pickState = {
  42238. renderTarget: renderTarget,
  42239. material: material,
  42240. scene: scene
  42241. };
  42242. };
  42243. let pickState = this.pickState;
  42244. let pickMaterial = pickState.material;
  42245. { // update pick material
  42246. pickMaterial.pointSizeType = pointSizeType;
  42247. pickMaterial.shape = this.material.shape;
  42248. pickMaterial.size = pointSize;
  42249. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  42250. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  42251. pickMaterial.classification = this.material.classification;
  42252. if(params.pickClipped){
  42253. pickMaterial.clipBoxes = this.material.clipBoxes;
  42254. if(this.material.clipTask === ClipTask.HIGHLIGHT){
  42255. pickMaterial.clipTask = ClipTask.NONE;
  42256. }else {
  42257. pickMaterial.clipTask = this.material.clipTask;
  42258. }
  42259. }else {
  42260. pickMaterial.clipBoxes = [];
  42261. }
  42262. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  42263. }
  42264. pickState.renderTarget.setSize(width, height);
  42265. let pixelPos = new Vector2(params.x, params.y);
  42266. let gl = renderer.getContext();
  42267. gl.enable(gl.SCISSOR_TEST);
  42268. gl.scissor(
  42269. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  42270. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  42271. parseInt(pickWindowSize), parseInt(pickWindowSize));
  42272. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  42273. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  42274. renderer.state.setBlending(NoBlending);
  42275. renderer.clearTarget(pickState.renderTarget, true, true, true);
  42276. { // RENDER
  42277. renderer.setRenderTarget(pickState.renderTarget);
  42278. gl.clearColor(0, 0, 0, 0);
  42279. renderer.clearTarget( pickState.renderTarget, true, true, true );
  42280. let tmp = this.material;
  42281. this.material = pickMaterial;
  42282. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  42283. this.material = tmp;
  42284. }
  42285. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  42286. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  42287. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  42288. let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  42289. let h = parseInt(Math.min(y + pickWindowSize, height) - y);
  42290. let pixelCount = w * h;
  42291. let buffer = new Uint8Array(4 * pixelCount);
  42292. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  42293. renderer.setRenderTarget(null);
  42294. renderer.state.reset();
  42295. renderer.setScissorTest(false);
  42296. gl.disable(gl.SCISSOR_TEST);
  42297. let pixels = buffer;
  42298. let ibuffer = new Uint32Array(buffer.buffer);
  42299. // find closest hit inside pixelWindow boundaries
  42300. let min = Number.MAX_VALUE;
  42301. let hits = [];
  42302. for (let u = 0; u < pickWindowSize; u++) {
  42303. for (let v = 0; v < pickWindowSize; v++) {
  42304. let offset = (u + v * pickWindowSize);
  42305. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  42306. let pcIndex = pixels[4 * offset + 3];
  42307. pixels[4 * offset + 3] = 0;
  42308. let pIndex = ibuffer[offset];
  42309. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  42310. let hit = {
  42311. pIndex: pIndex,
  42312. pcIndex: pcIndex,
  42313. distanceToCenter: distance
  42314. };
  42315. if(params.all){
  42316. hits.push(hit);
  42317. }else {
  42318. if(hits.length > 0){
  42319. if(distance < hits[0].distanceToCenter){
  42320. hits[0] = hit;
  42321. }
  42322. }else {
  42323. hits.push(hit);
  42324. }
  42325. }
  42326. }
  42327. }
  42328. }
  42329. for(let hit of hits){
  42330. let point = {};
  42331. if (!nodes[hit.pcIndex]) {
  42332. return null;
  42333. }
  42334. let node = nodes[hit.pcIndex];
  42335. let pc = node.sceneNode;
  42336. let geometry = node.geometryNode.geometry;
  42337. for(let attributeName in geometry.attributes){
  42338. let attribute = geometry.attributes[attributeName];
  42339. if (attributeName === 'position') {
  42340. let x = attribute.array[3 * hit.pIndex + 0];
  42341. let y = attribute.array[3 * hit.pIndex + 1];
  42342. let z = attribute.array[3 * hit.pIndex + 2];
  42343. let position = new Vector3(x, y, z);
  42344. position.applyMatrix4(pc.matrixWorld);
  42345. point[attributeName] = position;
  42346. } else if (attributeName === 'indices') {
  42347. } else {
  42348. //if (values.itemSize === 1) {
  42349. // point[attribute.name] = values.array[hit.pIndex];
  42350. //} else {
  42351. // let value = [];
  42352. // for (let j = 0; j < values.itemSize; j++) {
  42353. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  42354. // }
  42355. // point[attribute.name] = value;
  42356. //}
  42357. }
  42358. }
  42359. hit.point = point;
  42360. }
  42361. performance.mark("pick-end");
  42362. performance.measure("pick", "pick-start", "pick-end");
  42363. if(params.all){
  42364. return hits.map(hit => hit.point);
  42365. }else {
  42366. if(hits.length === 0){
  42367. return null;
  42368. }else {
  42369. return hits[0].point;
  42370. }
  42371. }
  42372. }
  42373. computeVisibilityTextureData(nodes){
  42374. if(exports.measureTimings) performance.mark("computeVisibilityTextureData-start");
  42375. let data = new Uint8Array(nodes.length * 3);
  42376. let visibleNodeTextureOffsets = new Map();
  42377. // copy array
  42378. nodes = nodes.slice();
  42379. // sort by level and number
  42380. let sort = function (a, b) {
  42381. let la = a.geometryNode.level;
  42382. let lb = b.geometryNode.level;
  42383. let na = a.geometryNode.number;
  42384. let nb = b.geometryNode.number;
  42385. if (la !== lb) return la - lb;
  42386. if (na < nb) return -1;
  42387. if (na > nb) return 1;
  42388. return 0;
  42389. };
  42390. nodes.sort(sort);
  42391. let visibleNodeNames = [];
  42392. for (let i = 0; i < nodes.length; i++) {
  42393. visibleNodeNames.push(nodes[i].geometryNode.number);
  42394. }
  42395. for (let i = 0; i < nodes.length; i++) {
  42396. let node = nodes[i];
  42397. visibleNodeTextureOffsets.set(node, i);
  42398. let b1 = 0; // children
  42399. let b2 = 0; // offset to first child
  42400. let b3 = 0; // split
  42401. if (node.geometryNode.left && visibleNodeNames.indexOf(node.geometryNode.left.number) > 0) {
  42402. b1 += 1;
  42403. b2 = visibleNodeNames.indexOf(node.geometryNode.left.number) - i;
  42404. }
  42405. if (node.geometryNode.right && visibleNodeNames.indexOf(node.geometryNode.right.number) > 0) {
  42406. b1 += 2;
  42407. b2 = (b2 === 0) ? visibleNodeNames.indexOf(node.geometryNode.right.number) - i : b2;
  42408. }
  42409. if (node.geometryNode.split === 'X') {
  42410. b3 = 1;
  42411. } else if (node.geometryNode.split === 'Y') {
  42412. b3 = 2;
  42413. } else if (node.geometryNode.split === 'Z') {
  42414. b3 = 4;
  42415. }
  42416. data[i * 3 + 0] = b1;
  42417. data[i * 3 + 1] = b2;
  42418. data[i * 3 + 2] = b3;
  42419. }
  42420. if(exports.measureTimings){
  42421. performance.mark("computeVisibilityTextureData-end");
  42422. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  42423. }
  42424. return {
  42425. data: data,
  42426. offsets: visibleNodeTextureOffsets
  42427. };
  42428. }
  42429. get progress () {
  42430. if (this.pcoGeometry.root) {
  42431. return exports.numNodesLoading > 0 ? 0 : 1;
  42432. } else {
  42433. return 0;
  42434. }
  42435. }
  42436. };
  42437. // Copied from three.js: WebGLRenderer.js
  42438. function paramThreeToGL(_gl, p) {
  42439. let extension;
  42440. if (p === RepeatWrapping) return _gl.REPEAT;
  42441. if (p === ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  42442. if (p === MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  42443. if (p === NearestFilter) return _gl.NEAREST;
  42444. if (p === NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  42445. if (p === NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  42446. if (p === LinearFilter) return _gl.LINEAR;
  42447. if (p === LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  42448. if (p === LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  42449. if (p === UnsignedByteType) return _gl.UNSIGNED_BYTE;
  42450. if (p === UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  42451. if (p === UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  42452. if (p === UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  42453. if (p === ByteType) return _gl.BYTE;
  42454. if (p === ShortType) return _gl.SHORT;
  42455. if (p === UnsignedShortType) return _gl.UNSIGNED_SHORT;
  42456. if (p === IntType) return _gl.INT;
  42457. if (p === UnsignedIntType) return _gl.UNSIGNED_INT;
  42458. if (p === FloatType) return _gl.FLOAT;
  42459. if (p === HalfFloatType) {
  42460. extension = extensions.get('OES_texture_half_float');
  42461. if (extension !== null) return extension.HALF_FLOAT_OES;
  42462. }
  42463. if (p === AlphaFormat) return _gl.ALPHA;
  42464. if (p === RGBFormat) return _gl.RGB;
  42465. if (p === RGBAFormat) return _gl.RGBA;
  42466. if (p === LuminanceFormat) return _gl.LUMINANCE;
  42467. if (p === LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  42468. if (p === DepthFormat) return _gl.DEPTH_COMPONENT;
  42469. if (p === DepthStencilFormat) return _gl.DEPTH_STENCIL;
  42470. if (p === AddEquation) return _gl.FUNC_ADD;
  42471. if (p === SubtractEquation) return _gl.FUNC_SUBTRACT;
  42472. if (p === ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  42473. if (p === ZeroFactor) return _gl.ZERO;
  42474. if (p === OneFactor) return _gl.ONE;
  42475. if (p === SrcColorFactor) return _gl.SRC_COLOR;
  42476. if (p === OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  42477. if (p === SrcAlphaFactor) return _gl.SRC_ALPHA;
  42478. if (p === OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  42479. if (p === DstAlphaFactor) return _gl.DST_ALPHA;
  42480. if (p === OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  42481. if (p === DstColorFactor) return _gl.DST_COLOR;
  42482. if (p === OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  42483. if (p === SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  42484. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  42485. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  42486. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  42487. if (extension !== null) {
  42488. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  42489. if (p === RGBA_S3TC_DXT1_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  42490. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  42491. if (p === RGBA_S3TC_DXT5_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  42492. }
  42493. }
  42494. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  42495. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  42496. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  42497. if (extension !== null) {
  42498. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  42499. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  42500. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  42501. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  42502. }
  42503. }
  42504. if (p === RGB_ETC1_Format) {
  42505. extension = extensions.get('WEBGL_compressed_texture_etc1');
  42506. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  42507. }
  42508. if (p === MinEquation || p === MaxEquation) {
  42509. extension = extensions.get('EXT_blend_minmax');
  42510. if (extension !== null) {
  42511. if (p === MinEquation) return extension.MIN_EXT;
  42512. if (p === MaxEquation) return extension.MAX_EXT;
  42513. }
  42514. }
  42515. if (p === UnsignedInt248Type) {
  42516. extension = extensions.get('WEBGL_depth_texture');
  42517. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  42518. }
  42519. return 0;
  42520. };
  42521. let attributeLocations = {
  42522. "position": {name: "position", location: 0},
  42523. "color": {name: "color", location: 1},
  42524. "rgba": {name: "color", location: 1},
  42525. "intensity": {name: "intensity", location: 2},
  42526. "classification": {name: "classification", location: 3},
  42527. "returnNumber": {name: "returnNumber", location: 4},
  42528. "return number": {name: "returnNumber", location: 4},
  42529. "returns": {name: "returnNumber", location: 4},
  42530. "numberOfReturns": {name: "numberOfReturns", location: 5},
  42531. "number of returns": {name: "numberOfReturns", location: 5},
  42532. "pointSourceID": {name: "pointSourceID", location: 6},
  42533. "source id": {name: "pointSourceID", location: 6},
  42534. "point source id": {name: "pointSourceID", location: 6},
  42535. "indices": {name: "indices", location: 7},
  42536. "normal": {name: "normal", location: 8},
  42537. "spacing": {name: "spacing", location: 9},
  42538. "gps-time": {name: "gpsTime", location: 10},
  42539. "aExtra": {name: "aExtra", location: 11},
  42540. };
  42541. class Shader {
  42542. constructor(gl, name, vsSource, fsSource) {
  42543. this.gl = gl;
  42544. this.name = name;
  42545. this.vsSource = vsSource;
  42546. this.fsSource = fsSource;
  42547. this.cache = new Map();
  42548. this.vs = null;
  42549. this.fs = null;
  42550. this.program = null;
  42551. this.uniformLocations = {};
  42552. this.attributeLocations = {};
  42553. this.uniformBlockIndices = {};
  42554. this.uniformBlocks = {};
  42555. this.uniforms = {};
  42556. this.update(vsSource, fsSource);
  42557. }
  42558. update(vsSource, fsSource) {
  42559. this.vsSource = vsSource;
  42560. this.fsSource = fsSource;
  42561. this.linkProgram();
  42562. }
  42563. compileShader(shader, source){
  42564. let gl = this.gl;
  42565. gl.shaderSource(shader, source);
  42566. gl.compileShader(shader);
  42567. let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  42568. if (!success) {
  42569. let info = gl.getShaderInfoLog(shader);
  42570. let numberedSource = source.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n");
  42571. throw `could not compile shader ${this.name}: ${info}, \n${numberedSource}`;
  42572. }
  42573. }
  42574. linkProgram() {
  42575. const tStart = performance.now();
  42576. let gl = this.gl;
  42577. this.uniformLocations = {};
  42578. this.attributeLocations = {};
  42579. this.uniforms = {};
  42580. gl.useProgram(null);
  42581. let cached = this.cache.get(`${this.vsSource}, ${this.fsSource}`);
  42582. if (cached) {
  42583. this.program = cached.program;
  42584. this.vs = cached.vs;
  42585. this.fs = cached.fs;
  42586. this.attributeLocations = cached.attributeLocations;
  42587. this.uniformLocations = cached.uniformLocations;
  42588. this.uniformBlocks = cached.uniformBlocks;
  42589. this.uniforms = cached.uniforms;
  42590. return;
  42591. } else {
  42592. this.vs = gl.createShader(gl.VERTEX_SHADER);
  42593. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  42594. this.program = gl.createProgram();
  42595. for(let name of Object.keys(attributeLocations)){
  42596. let location = attributeLocations[name].location;
  42597. let glslName = attributeLocations[name].name;
  42598. gl.bindAttribLocation(this.program, location, glslName);
  42599. }
  42600. this.compileShader(this.vs, this.vsSource);
  42601. this.compileShader(this.fs, this.fsSource);
  42602. let program = this.program;
  42603. gl.attachShader(program, this.vs);
  42604. gl.attachShader(program, this.fs);
  42605. gl.linkProgram(program);
  42606. gl.detachShader(program, this.vs);
  42607. gl.detachShader(program, this.fs);
  42608. let success = gl.getProgramParameter(program, gl.LINK_STATUS);
  42609. if (!success) {
  42610. let info = gl.getProgramInfoLog(program);
  42611. throw `could not link program ${this.name}: ${info}`;
  42612. }
  42613. { // attribute locations
  42614. let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  42615. for (let i = 0; i < numAttributes; i++) {
  42616. let attribute = gl.getActiveAttrib(program, i);
  42617. let location = gl.getAttribLocation(program, attribute.name);
  42618. this.attributeLocations[attribute.name] = location;
  42619. }
  42620. }
  42621. { // uniform locations
  42622. let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  42623. for (let i = 0; i < numUniforms; i++) {
  42624. let uniform = gl.getActiveUniform(program, i);
  42625. let location = gl.getUniformLocation(program, uniform.name);
  42626. this.uniformLocations[uniform.name] = location;
  42627. this.uniforms[uniform.name] = {
  42628. location: location,
  42629. value: null,
  42630. };
  42631. }
  42632. }
  42633. // uniform blocks
  42634. if(typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext){
  42635. let numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  42636. for (let i = 0; i < numBlocks; i++) {
  42637. let blockName = gl.getActiveUniformBlockName(program, i);
  42638. let blockIndex = gl.getUniformBlockIndex(program, blockName);
  42639. this.uniformBlockIndices[blockName] = blockIndex;
  42640. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  42641. let dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  42642. let uBuffer = gl.createBuffer();
  42643. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  42644. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  42645. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  42646. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  42647. this.uniformBlocks[blockName] = {
  42648. name: blockName,
  42649. index: blockIndex,
  42650. dataSize: dataSize,
  42651. buffer: uBuffer
  42652. };
  42653. }
  42654. }
  42655. let cached = {
  42656. program: this.program,
  42657. vs: this.vs,
  42658. fs: this.fs,
  42659. attributeLocations: this.attributeLocations,
  42660. uniformLocations: this.uniformLocations,
  42661. uniforms: this.uniforms,
  42662. uniformBlocks: this.uniformBlocks,
  42663. };
  42664. this.cache.set(`${this.vsSource}, ${this.fsSource}`, cached);
  42665. }
  42666. const tEnd = performance.now();
  42667. const duration = tEnd - tStart;
  42668. console.log(`shader compile duration: ${duration.toFixed(3)}`);
  42669. }
  42670. setUniformMatrix4(name, value) {
  42671. const gl = this.gl;
  42672. const location = this.uniformLocations[name];
  42673. if (location == null) {
  42674. return;
  42675. }
  42676. let tmp = new Float32Array(value.elements);
  42677. gl.uniformMatrix4fv(location, false, tmp);
  42678. }
  42679. setUniform1f(name, value) {
  42680. const gl = this.gl;
  42681. const uniform = this.uniforms[name];
  42682. if (uniform === undefined) {
  42683. return;
  42684. }
  42685. if(uniform.value === value){
  42686. return;
  42687. }
  42688. uniform.value = value;
  42689. gl.uniform1f(uniform.location, value);
  42690. }
  42691. setUniformBoolean(name, value) {
  42692. const gl = this.gl;
  42693. const uniform = this.uniforms[name];
  42694. if (uniform === undefined) {
  42695. return;
  42696. }
  42697. if(uniform.value === value){
  42698. return;
  42699. }
  42700. uniform.value = value;
  42701. gl.uniform1i(uniform.location, value);
  42702. }
  42703. setUniformTexture(name, value) {
  42704. const gl = this.gl;
  42705. const location = this.uniformLocations[name];
  42706. if (location == null) {
  42707. return;
  42708. }
  42709. gl.uniform1i(location, value);
  42710. }
  42711. setUniform2f(name, value) {
  42712. const gl = this.gl;
  42713. const location = this.uniformLocations[name];
  42714. if (location == null) {
  42715. return;
  42716. }
  42717. gl.uniform2f(location, value[0], value[1]);
  42718. }
  42719. setUniform3f(name, value) {
  42720. const gl = this.gl;
  42721. const location = this.uniformLocations[name];
  42722. if (location == null) {
  42723. return;
  42724. }
  42725. gl.uniform3f(location, value[0], value[1], value[2]);
  42726. }
  42727. setUniform(name, value) {
  42728. if (value.constructor === Matrix4) {
  42729. this.setUniformMatrix4(name, value);
  42730. } else if (typeof value === "number") {
  42731. this.setUniform1f(name, value);
  42732. } else if (typeof value === "boolean") {
  42733. this.setUniformBoolean(name, value);
  42734. } else if (value instanceof WebGLTexture) {
  42735. this.setUniformTexture(name, value);
  42736. } else if (value instanceof Array) {
  42737. if (value.length === 2) {
  42738. this.setUniform2f(name, value);
  42739. } else if (value.length === 3) {
  42740. this.setUniform3f(name, value);
  42741. }
  42742. } else {
  42743. console.error("unhandled uniform type: ", name, value);
  42744. }
  42745. }
  42746. setUniform1i(name, value) {
  42747. let gl = this.gl;
  42748. let location = this.uniformLocations[name];
  42749. if (location == null) {
  42750. return;
  42751. }
  42752. gl.uniform1i(location, value);
  42753. }
  42754. };
  42755. class WebGLTexture {
  42756. constructor(gl, texture) {
  42757. this.gl = gl;
  42758. this.texture = texture;
  42759. this.id = gl.createTexture();
  42760. this.target = gl.TEXTURE_2D;
  42761. this.version = -1;
  42762. this.update(texture);
  42763. }
  42764. update() {
  42765. if (!this.texture.image) {
  42766. this.version = this.texture.version;
  42767. return;
  42768. }
  42769. let gl = this.gl;
  42770. let texture = this.texture;
  42771. if (this.version === texture.version) {
  42772. return;
  42773. }
  42774. this.target = gl.TEXTURE_2D;
  42775. gl.bindTexture(this.target, this.id);
  42776. let level = 0;
  42777. let internalFormat = paramThreeToGL(gl, texture.format);
  42778. let width = texture.image.width;
  42779. let height = texture.image.height;
  42780. let border = 0;
  42781. let srcFormat = internalFormat;
  42782. let srcType = paramThreeToGL(gl, texture.type);
  42783. let data;
  42784. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  42785. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  42786. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  42787. if (texture instanceof DataTexture) {
  42788. data = texture.image.data;
  42789. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  42790. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  42791. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  42792. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  42793. gl.texImage2D(this.target, level, internalFormat,
  42794. width, height, border, srcFormat, srcType,
  42795. data);
  42796. } else if ((texture instanceof CanvasTexture) || (texture instanceof Texture)) {
  42797. data = texture.image;
  42798. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL(gl, texture.wrapS));
  42799. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL(gl, texture.wrapT));
  42800. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  42801. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  42802. gl.texImage2D(this.target, level, internalFormat,
  42803. internalFormat, srcType, data);
  42804. if (texture instanceof Texture) {gl.generateMipmap(gl.TEXTURE_2D);}
  42805. }
  42806. gl.bindTexture(this.target, null);
  42807. this.version = texture.version;
  42808. }
  42809. };
  42810. class WebGLBuffer {
  42811. constructor() {
  42812. this.numElements = 0;
  42813. this.vao = null;
  42814. this.vbos = new Map();
  42815. }
  42816. };
  42817. class Renderer {
  42818. constructor(threeRenderer) {
  42819. this.threeRenderer = threeRenderer;
  42820. this.gl = this.threeRenderer.getContext();
  42821. this.buffers = new Map();
  42822. this.shaders = new Map();
  42823. this.textures = new Map();
  42824. this.glTypeMapping = new Map();
  42825. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  42826. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  42827. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  42828. this.toggle = 0;
  42829. }
  42830. deleteBuffer(geometry) {
  42831. let gl = this.gl;
  42832. let webglBuffer = this.buffers.get(geometry);
  42833. if (webglBuffer != null) {
  42834. for (let attributeName in geometry.attributes) {
  42835. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  42836. }
  42837. this.buffers.delete(geometry);
  42838. }
  42839. }
  42840. createBuffer(geometry){
  42841. let gl = this.gl;
  42842. let webglBuffer = new WebGLBuffer();
  42843. webglBuffer.vao = gl.createVertexArray();
  42844. webglBuffer.numElements = geometry.attributes.position.count;
  42845. gl.bindVertexArray(webglBuffer.vao);
  42846. for(let attributeName in geometry.attributes){
  42847. let bufferAttribute = geometry.attributes[attributeName];
  42848. let vbo = gl.createBuffer();
  42849. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  42850. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  42851. let normalized = bufferAttribute.normalized;
  42852. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  42853. if(attributeLocations[attributeName] === undefined){
  42854. //attributeLocation = attributeLocations["aExtra"];
  42855. }else {
  42856. let attributeLocation = attributeLocations[attributeName].location;
  42857. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  42858. gl.enableVertexAttribArray(attributeLocation);
  42859. }
  42860. webglBuffer.vbos.set(attributeName, {
  42861. handle: vbo,
  42862. name: attributeName,
  42863. count: bufferAttribute.count,
  42864. itemSize: bufferAttribute.itemSize,
  42865. type: geometry.attributes.position.array.constructor,
  42866. version: 0
  42867. });
  42868. }
  42869. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  42870. gl.bindVertexArray(null);
  42871. let disposeHandler = (event) => {
  42872. this.deleteBuffer(geometry);
  42873. geometry.removeEventListener("dispose", disposeHandler);
  42874. };
  42875. geometry.addEventListener("dispose", disposeHandler);
  42876. return webglBuffer;
  42877. }
  42878. updateBuffer(geometry){
  42879. let gl = this.gl;
  42880. let webglBuffer = this.buffers.get(geometry);
  42881. gl.bindVertexArray(webglBuffer.vao);
  42882. for(let attributeName in geometry.attributes){
  42883. let bufferAttribute = geometry.attributes[attributeName];
  42884. let normalized = bufferAttribute.normalized;
  42885. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  42886. let vbo = null;
  42887. if(!webglBuffer.vbos.has(attributeName)){
  42888. vbo = gl.createBuffer();
  42889. webglBuffer.vbos.set(attributeName, {
  42890. handle: vbo,
  42891. name: attributeName,
  42892. count: bufferAttribute.count,
  42893. itemSize: bufferAttribute.itemSize,
  42894. type: geometry.attributes.position.array.constructor,
  42895. version: bufferAttribute.version
  42896. });
  42897. }else {
  42898. vbo = webglBuffer.vbos.get(attributeName).handle;
  42899. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  42900. }
  42901. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  42902. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  42903. if(attributeLocations[attributeName] === undefined){
  42904. //attributeLocation = attributeLocations["aExtra"];
  42905. }else {
  42906. let attributeLocation = attributeLocations[attributeName].location;
  42907. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  42908. gl.enableVertexAttribArray(attributeLocation);
  42909. }
  42910. }
  42911. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  42912. gl.bindVertexArray(null);
  42913. }
  42914. traverse(scene) {
  42915. let octrees = [];
  42916. let stack = [scene];
  42917. while (stack.length > 0) {
  42918. let node = stack.pop();
  42919. if (node instanceof PointCloudTree) {
  42920. octrees.push(node);
  42921. continue;
  42922. }
  42923. let visibleChildren = node.children.filter(c => c.visible);
  42924. stack.push(...visibleChildren);
  42925. }
  42926. let result = {
  42927. octrees: octrees
  42928. };
  42929. return result;
  42930. }
  42931. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  42932. if (exports.measureTimings) performance.mark("renderNodes-start");
  42933. let gl = this.gl;
  42934. let material = params.material ? params.material : octree.material;
  42935. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  42936. let view = camera.matrixWorldInverse;
  42937. if(params.viewOverride){
  42938. view = params.viewOverride;
  42939. }
  42940. let worldView = new Matrix4();
  42941. let mat4holder = new Float32Array(16);
  42942. let i = 0;
  42943. for (let node of nodes) {
  42944. if(exports.debug.allowedNodes !== undefined){
  42945. if(!exports.debug.allowedNodes.includes(node.name)){
  42946. continue;
  42947. }
  42948. }
  42949. let world = node.sceneNode.matrixWorld;
  42950. worldView.multiplyMatrices(view, world);
  42951. if (visibilityTextureData) {
  42952. let vnStart = visibilityTextureData.offsets.get(node);
  42953. shader.setUniform1f("uVNStart", vnStart);
  42954. }
  42955. let level = node.getLevel();
  42956. if(node.debug){
  42957. shader.setUniform("uDebug", true);
  42958. }else {
  42959. shader.setUniform("uDebug", false);
  42960. }
  42961. // let isLeaf = false;
  42962. // if(node instanceof PointCloudOctreeNode){
  42963. // isLeaf = Object.keys(node.children).length === 0;
  42964. // }else if(node instanceof PointCloudArena4DNode){
  42965. // isLeaf = node.geometryNode.isLeaf;
  42966. // }
  42967. // shader.setUniform("uIsLeafNode", isLeaf);
  42968. // let isLeaf = node.children.filter(n => n != null).length === 0;
  42969. // if(!isLeaf){
  42970. // continue;
  42971. // }
  42972. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  42973. const lModel = shader.uniformLocations["modelMatrix"];
  42974. if (lModel) {
  42975. mat4holder.set(world.elements);
  42976. gl.uniformMatrix4fv(lModel, false, mat4holder);
  42977. }
  42978. const lModelView = shader.uniformLocations["modelViewMatrix"];
  42979. //mat4holder.set(worldView.elements);
  42980. // faster then set in chrome 63
  42981. for(let j = 0; j < 16; j++){
  42982. mat4holder[j] = worldView.elements[j];
  42983. }
  42984. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  42985. { // Clip Polygons
  42986. if(material.clipPolygons && material.clipPolygons.length > 0){
  42987. let clipPolygonVCount = [];
  42988. let worldViewProjMatrices = [];
  42989. for(let clipPolygon of material.clipPolygons){
  42990. let view = clipPolygon.viewMatrix;
  42991. let proj = clipPolygon.projMatrix;
  42992. let worldViewProj = proj.clone().multiply(view).multiply(world);
  42993. clipPolygonVCount.push(clipPolygon.markers.length);
  42994. worldViewProjMatrices.push(worldViewProj);
  42995. }
  42996. let flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  42997. let flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  42998. for(let i = 0; i < material.clipPolygons.length; i++){
  42999. let clipPolygon = material.clipPolygons[i];
  43000. for(let j = 0; j < clipPolygon.markers.length; j++){
  43001. flattenedVertices[i * 24 + (j * 3 + 0)] = clipPolygon.markers[j].position.x;
  43002. flattenedVertices[i * 24 + (j * 3 + 1)] = clipPolygon.markers[j].position.y;
  43003. flattenedVertices[i * 24 + (j * 3 + 2)] = clipPolygon.markers[j].position.z;
  43004. }
  43005. }
  43006. const lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  43007. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  43008. const lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  43009. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  43010. const lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  43011. gl.uniform3fv(lClipPolygons, flattenedVertices);
  43012. }
  43013. }
  43014. //shader.setUniformMatrix4("modelMatrix", world);
  43015. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  43016. shader.setUniform1f("uLevel", level);
  43017. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  43018. shader.setUniform1f("uPCIndex", i);
  43019. // uBBSize
  43020. if (shadowMaps.length > 0) {
  43021. const lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  43022. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  43023. let bindingStart = 5;
  43024. let bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => (a + i));
  43025. gl.uniform1iv(lShadowMap, bindingPoints);
  43026. for (let i = 0; i < shadowMaps.length; i++) {
  43027. let shadowMap = shadowMaps[i];
  43028. let bindingPoint = bindingPoints[i];
  43029. let glTexture = this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  43030. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  43031. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  43032. }
  43033. {
  43034. let worldViewMatrices = shadowMaps
  43035. .map(sm => sm.camera.matrixWorldInverse)
  43036. .map(view => new Matrix4().multiplyMatrices(view, world));
  43037. let flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  43038. const lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  43039. gl.uniformMatrix4fv(lWorldView, false, flattenedMatrices);
  43040. }
  43041. {
  43042. let flattenedMatrices = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  43043. const lProj = shader.uniformLocations["uShadowProj[0]"];
  43044. gl.uniformMatrix4fv(lProj, false, flattenedMatrices);
  43045. }
  43046. }
  43047. const geometry = node.geometryNode.geometry;
  43048. if(geometry.attributes["gps-time"]){
  43049. const bufferAttribute = geometry.attributes["gps-time"];
  43050. const attGPS = octree.getAttribute("gps-time");
  43051. let initialRange = attGPS.initialRange;
  43052. let initialRangeSize = initialRange[1] - initialRange[0];
  43053. let globalRange = attGPS.range;
  43054. let globalRangeSize = globalRange[1] - globalRange[0];
  43055. let scale = initialRangeSize / globalRangeSize;
  43056. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  43057. scale = Number.isNaN(scale) ? 1 : scale;
  43058. offset = Number.isNaN(offset) ? 0 : offset;
  43059. shader.setUniform1f("uGpsScale", scale);
  43060. shader.setUniform1f("uGpsOffset", offset);
  43061. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  43062. let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  43063. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  43064. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  43065. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  43066. let normalizedClipRange = [
  43067. (uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize,
  43068. (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize,
  43069. ];
  43070. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  43071. // // ranges in full gps coordinate system
  43072. // const globalRange = attGPS.range;
  43073. // const bufferRange = bufferAttribute.potree.range;
  43074. // // ranges in [0, 1]
  43075. // // normalizedGlobalRange = [0, 1]
  43076. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  43077. // const globalWidth = globalRange[1] - globalRange[0];
  43078. // const normalizedBufferRange = [
  43079. // (bufferRange[0] - globalRange[0]) / globalWidth,
  43080. // (bufferRange[1] - globalRange[0]) / globalWidth,
  43081. // ];
  43082. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  43083. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  43084. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  43085. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  43086. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  43087. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  43088. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  43089. }
  43090. {
  43091. let uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  43092. let uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  43093. let uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  43094. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  43095. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  43096. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  43097. }
  43098. let webglBuffer = null;
  43099. if(!this.buffers.has(geometry)){
  43100. webglBuffer = this.createBuffer(geometry);
  43101. this.buffers.set(geometry, webglBuffer);
  43102. }else {
  43103. webglBuffer = this.buffers.get(geometry);
  43104. for(let attributeName in geometry.attributes){
  43105. let attribute = geometry.attributes[attributeName];
  43106. if(attribute.version > webglBuffer.vbos.get(attributeName).version){
  43107. this.updateBuffer(geometry);
  43108. }
  43109. }
  43110. }
  43111. gl.bindVertexArray(webglBuffer.vao);
  43112. let isExtraAttribute =
  43113. attributeLocations[material.activeAttributeName] === undefined
  43114. && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  43115. if(isExtraAttribute){
  43116. const attributeLocation = attributeLocations["aExtra"].location;
  43117. for(const attributeName in geometry.attributes){
  43118. const bufferAttribute = geometry.attributes[attributeName];
  43119. const vbo = webglBuffer.vbos.get(attributeName);
  43120. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  43121. gl.disableVertexAttribArray(attributeLocation);
  43122. }
  43123. const attName = material.activeAttributeName;
  43124. const bufferAttribute = geometry.attributes[attName];
  43125. const vbo = webglBuffer.vbos.get(attName);
  43126. if(bufferAttribute !== undefined && vbo !== undefined){
  43127. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  43128. let normalized = bufferAttribute.normalized;
  43129. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  43130. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  43131. gl.enableVertexAttribArray(attributeLocation);
  43132. }
  43133. {
  43134. const attExtra = octree.pcoGeometry.pointAttributes.attributes
  43135. .find(a => a.name === attName);
  43136. let range = material.getRange(attName);
  43137. if(!range){
  43138. range = attExtra.range;
  43139. }
  43140. if(!range){
  43141. range = [0, 1];
  43142. }
  43143. let initialRange = attExtra.initialRange;
  43144. let initialRangeSize = initialRange[1] - initialRange[0];
  43145. let globalRange = range;
  43146. let globalRangeSize = globalRange[1] - globalRange[0];
  43147. let scale = initialRangeSize / globalRangeSize;
  43148. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  43149. scale = Number.isNaN(scale) ? 1 : scale;
  43150. offset = Number.isNaN(offset) ? 0 : offset;
  43151. shader.setUniform1f("uExtraScale", scale);
  43152. shader.setUniform1f("uExtraOffset", offset);
  43153. }
  43154. }else {
  43155. for(const attributeName in geometry.attributes){
  43156. const bufferAttribute = geometry.attributes[attributeName];
  43157. const vbo = webglBuffer.vbos.get(attributeName);
  43158. if(attributeLocations[attributeName] !== undefined){
  43159. const attributeLocation = attributeLocations[attributeName].location;
  43160. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  43161. let normalized = bufferAttribute.normalized;
  43162. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  43163. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  43164. gl.enableVertexAttribArray(attributeLocation);
  43165. }
  43166. }
  43167. }
  43168. let numPoints = webglBuffer.numElements;
  43169. gl.drawArrays(gl.POINTS, 0, numPoints);
  43170. i++;
  43171. }
  43172. gl.bindVertexArray(null);
  43173. if (exports.measureTimings) {
  43174. performance.mark("renderNodes-end");
  43175. performance.measure("render.renderNodes", "renderNodes-start", "renderNodes-end");
  43176. }
  43177. }
  43178. renderOctree(octree, nodes, camera, target, params = {}){
  43179. let gl = this.gl;
  43180. let material = params.material ? params.material : octree.material;
  43181. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  43182. let view = camera.matrixWorldInverse;
  43183. let viewInv = camera.matrixWorld;
  43184. if(params.viewOverride){
  43185. view = params.viewOverride;
  43186. viewInv = view.clone().invert();
  43187. }
  43188. let proj = camera.projectionMatrix;
  43189. let projInv = proj.clone().invert();
  43190. //let worldView = new THREE.Matrix4();
  43191. let shader = null;
  43192. let visibilityTextureData = null;
  43193. let currentTextureBindingPoint = 0;
  43194. if (material.pointSizeType >= 0) {
  43195. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  43196. material.activeAttributeName === "level of detail") {
  43197. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  43198. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  43199. const vnt = material.visibleNodesTexture;
  43200. const data = vnt.image.data;
  43201. data.set(visibilityTextureData.data);
  43202. vnt.needsUpdate = true;
  43203. }
  43204. }
  43205. { // UPDATE SHADER AND TEXTURES
  43206. if (!this.shaders.has(material)) {
  43207. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  43208. let shader = new Shader(gl, "pointcloud", vs, fs);
  43209. this.shaders.set(material, shader);
  43210. }
  43211. shader = this.shaders.get(material);
  43212. //if(material.needsUpdate){
  43213. {
  43214. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  43215. let numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  43216. let numClipBoxes = (material.clipBoxes && material.clipBoxes.length) ? material.clipBoxes.length : 0;
  43217. let numClipSpheres = (params.clipSpheres && params.clipSpheres.length) ? params.clipSpheres.length : 0;
  43218. let numClipPolygons = (material.clipPolygons && material.clipPolygons.length) ? material.clipPolygons.length : 0;
  43219. let defines = [
  43220. `#define num_shadowmaps ${shadowMaps.length}`,
  43221. `#define num_snapshots ${numSnapshots}`,
  43222. `#define num_clipboxes ${numClipBoxes}`,
  43223. `#define num_clipspheres ${numClipSpheres}`,
  43224. `#define num_clippolygons ${numClipPolygons}`,
  43225. ];
  43226. if(octree.pcoGeometry.root.isLoaded()){
  43227. let attributes = octree.pcoGeometry.root.geometry.attributes;
  43228. if(attributes["gps-time"]){
  43229. defines.push("#define clip_gps_enabled");
  43230. }
  43231. if(attributes["return number"]){
  43232. defines.push("#define clip_return_number_enabled");
  43233. }
  43234. if(attributes["number of returns"]){
  43235. defines.push("#define clip_number_of_returns_enabled");
  43236. }
  43237. if(attributes["source id"] || attributes["point source id"]){
  43238. defines.push("#define clip_point_source_id_enabled");
  43239. }
  43240. }
  43241. let definesString = defines.join("\n");
  43242. let vsVersionIndex = vs.indexOf("#version ");
  43243. let fsVersionIndex = fs.indexOf("#version ");
  43244. if(vsVersionIndex >= 0){
  43245. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  43246. }else {
  43247. vs = `${definesString}\n${vs}`;
  43248. }
  43249. if(fsVersionIndex >= 0){
  43250. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  43251. }else {
  43252. fs = `${definesString}\n${fs}`;
  43253. }
  43254. shader.update(vs, fs);
  43255. material.needsUpdate = false;
  43256. }
  43257. for (let uniformName of Object.keys(material.uniforms)) {
  43258. let uniform = material.uniforms[uniformName];
  43259. if (uniform.type == "t") {
  43260. let texture = uniform.value;
  43261. if (!texture) {
  43262. continue;
  43263. }
  43264. if (!this.textures.has(texture)) {
  43265. let webglTexture = new WebGLTexture(gl, texture);
  43266. this.textures.set(texture, webglTexture);
  43267. }
  43268. let webGLTexture = this.textures.get(texture);
  43269. webGLTexture.update();
  43270. }
  43271. }
  43272. }
  43273. gl.useProgram(shader.program);
  43274. let transparent = false;
  43275. if(params.transparent !== undefined){
  43276. transparent = params.transparent && material.opacity < 1;
  43277. }else {
  43278. transparent = material.opacity < 1;
  43279. }
  43280. if (transparent){
  43281. gl.enable(gl.BLEND);
  43282. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  43283. gl.depthMask(false);
  43284. gl.disable(gl.DEPTH_TEST);
  43285. } else {
  43286. gl.disable(gl.BLEND);
  43287. gl.depthMask(true);
  43288. gl.enable(gl.DEPTH_TEST);
  43289. }
  43290. if(params.blendFunc !== undefined){
  43291. gl.enable(gl.BLEND);
  43292. gl.blendFunc(...params.blendFunc);
  43293. }
  43294. if(params.depthTest !== undefined){
  43295. if(params.depthTest === true){
  43296. gl.enable(gl.DEPTH_TEST);
  43297. }else {
  43298. gl.disable(gl.DEPTH_TEST);
  43299. }
  43300. }
  43301. if(params.depthWrite !== undefined){
  43302. if(params.depthWrite === true){
  43303. gl.depthMask(true);
  43304. }else {
  43305. gl.depthMask(false);
  43306. }
  43307. }
  43308. { // UPDATE UNIFORMS
  43309. shader.setUniformMatrix4("projectionMatrix", proj);
  43310. shader.setUniformMatrix4("viewMatrix", view);
  43311. shader.setUniformMatrix4("uViewInv", viewInv);
  43312. shader.setUniformMatrix4("uProjInv", projInv);
  43313. let screenWidth = target ? target.width : material.screenWidth;
  43314. let screenHeight = target ? target.height : material.screenHeight;
  43315. shader.setUniform1f("uScreenWidth", screenWidth);
  43316. shader.setUniform1f("uScreenHeight", screenHeight);
  43317. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  43318. shader.setUniform1f("near", camera.near);
  43319. shader.setUniform1f("far", camera.far);
  43320. if(camera instanceof OrthographicCamera){
  43321. shader.setUniform("uUseOrthographicCamera", true);
  43322. shader.setUniform("uOrthoWidth", camera.right - camera.left);
  43323. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  43324. }else {
  43325. shader.setUniform("uUseOrthographicCamera", false);
  43326. }
  43327. if(material.clipBoxes.length + material.clipPolygons.length === 0){
  43328. shader.setUniform1i("clipTask", ClipTask.NONE);
  43329. }else {
  43330. shader.setUniform1i("clipTask", material.clipTask);
  43331. }
  43332. shader.setUniform1i("clipMethod", material.clipMethod);
  43333. if (material.clipBoxes && material.clipBoxes.length > 0) {
  43334. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  43335. //const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  43336. //gl.uniformMatrix4fv(lClipBoxes, false, flattenedMatrices);
  43337. const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  43338. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes.value);
  43339. }
  43340. // TODO CLIPSPHERES
  43341. if(params.clipSpheres && params.clipSpheres.length > 0){
  43342. let clipSpheres = params.clipSpheres;
  43343. let matrices = [];
  43344. for(let clipSphere of clipSpheres){
  43345. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  43346. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  43347. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  43348. let clipToWorld = clipSphere.matrixWorld;
  43349. let viewToWorld = camera.matrixWorld;
  43350. let worldToClip = clipToWorld.clone().invert();
  43351. let viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  43352. matrices.push(viewToClip);
  43353. }
  43354. let flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  43355. const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  43356. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  43357. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  43358. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  43359. }
  43360. shader.setUniform1f("size", material.size);
  43361. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  43362. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  43363. // uniform float uPCIndex
  43364. shader.setUniform1f("uOctreeSpacing", material.spacing);
  43365. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  43366. //uniform vec3 uColor;
  43367. shader.setUniform3f("uColor", material.color.toArray());
  43368. //uniform float opacity;
  43369. shader.setUniform1f("uOpacity", material.opacity);
  43370. shader.setUniform2f("elevationRange", material.elevationRange);
  43371. shader.setUniform2f("intensityRange", material.intensityRange);
  43372. shader.setUniform3f("uIntensity_gbc", [
  43373. material.intensityGamma,
  43374. material.intensityBrightness,
  43375. material.intensityContrast
  43376. ]);
  43377. shader.setUniform3f("uRGB_gbc", [
  43378. material.rgbGamma,
  43379. material.rgbBrightness,
  43380. material.rgbContrast
  43381. ]);
  43382. shader.setUniform1f("uTransition", material.transition);
  43383. shader.setUniform1f("wRGB", material.weightRGB);
  43384. shader.setUniform1f("wIntensity", material.weightIntensity);
  43385. shader.setUniform1f("wElevation", material.weightElevation);
  43386. shader.setUniform1f("wClassification", material.weightClassification);
  43387. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  43388. shader.setUniform1f("wSourceID", material.weightSourceID);
  43389. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  43390. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);
  43391. if(vnWebGLTexture){
  43392. shader.setUniform1i("visibleNodesTexture", currentTextureBindingPoint);
  43393. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  43394. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  43395. currentTextureBindingPoint++;
  43396. }
  43397. let gradientTexture = this.textures.get(material.gradientTexture);
  43398. shader.setUniform1i("gradient", currentTextureBindingPoint);
  43399. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  43400. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  43401. const repeat = material.elevationGradientRepeat;
  43402. if(repeat === ElevationGradientRepeat.REPEAT){
  43403. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  43404. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  43405. }else if(repeat === ElevationGradientRepeat.MIRRORED_REPEAT){
  43406. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  43407. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  43408. }else {
  43409. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  43410. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  43411. }
  43412. currentTextureBindingPoint++;
  43413. let classificationTexture = this.textures.get(material.classificationTexture);
  43414. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  43415. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  43416. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  43417. currentTextureBindingPoint++;
  43418. let matcapTexture = this.textures.get(material.matcapTexture);
  43419. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  43420. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  43421. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  43422. currentTextureBindingPoint++;
  43423. if (material.snapEnabled === true) {
  43424. {
  43425. const lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  43426. const lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  43427. let bindingStart = currentTextureBindingPoint;
  43428. let lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => (a + i));
  43429. let lSnapshotDepthBindingPoints = new Array(5)
  43430. .fill(1 + Math.max(...lSnapshotBindingPoints))
  43431. .map((a, i) => (a + i));
  43432. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  43433. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  43434. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  43435. for (let i = 0; i < 5; i++) {
  43436. let texture = material.uniforms[`uSnapshot`].value[i];
  43437. let textureDepth = material.uniforms[`uSnapshotDepth`].value[i];
  43438. if (!texture) {
  43439. break;
  43440. }
  43441. let snapTexture = this.threeRenderer.properties.get(texture).__webglTexture;
  43442. let snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  43443. let bindingPoint = lSnapshotBindingPoints[i];
  43444. let depthBindingPoint = lSnapshotDepthBindingPoints[i];
  43445. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  43446. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  43447. gl.activeTexture(gl[`TEXTURE${depthBindingPoint}`]);
  43448. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  43449. }
  43450. }
  43451. {
  43452. let flattenedMatrices = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  43453. const lSnapView = shader.uniformLocations["uSnapView[0]"];
  43454. gl.uniformMatrix4fv(lSnapView, false, flattenedMatrices);
  43455. }
  43456. {
  43457. let flattenedMatrices = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  43458. const lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  43459. gl.uniformMatrix4fv(lSnapProj, false, flattenedMatrices);
  43460. }
  43461. {
  43462. let flattenedMatrices = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  43463. const lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  43464. gl.uniformMatrix4fv(lSnapProjInv, false, flattenedMatrices);
  43465. }
  43466. {
  43467. let flattenedMatrices = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  43468. const lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  43469. gl.uniformMatrix4fv(lSnapViewInv, false, flattenedMatrices);
  43470. }
  43471. }
  43472. }
  43473. this.renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params);
  43474. gl.activeTexture(gl.TEXTURE2);
  43475. gl.bindTexture(gl.TEXTURE_2D, null);
  43476. gl.activeTexture(gl.TEXTURE0);
  43477. }
  43478. render(scene, camera, target = null, params = {}) {
  43479. const gl = this.gl;
  43480. // PREPARE
  43481. if (target != null) {
  43482. this.threeRenderer.setRenderTarget(target);
  43483. }
  43484. //camera.updateProjectionMatrix();
  43485. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  43486. const traversalResult = this.traverse(scene);
  43487. // RENDER
  43488. for (const octree of traversalResult.octrees) {
  43489. let nodes = octree.visibleNodes;
  43490. this.renderOctree(octree, nodes, camera, target, params);
  43491. }
  43492. // CLEANUP
  43493. gl.activeTexture(gl.TEXTURE1);
  43494. gl.bindTexture(gl.TEXTURE_2D, null);
  43495. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  43496. gl.bindVertexArray(null);
  43497. this.threeRenderer.resetState();
  43498. }
  43499. };
  43500. function copyMaterial(source, target){
  43501. for(let name of Object.keys(target.uniforms)){
  43502. target.uniforms[name].value = source.uniforms[name].value;
  43503. }
  43504. target.gradientTexture = source.gradientTexture;
  43505. target.visibleNodesTexture = source.visibleNodesTexture;
  43506. target.classificationTexture = source.classificationTexture;
  43507. target.matcapTexture = source.matcapTexture;
  43508. target.activeAttributeName = source.activeAttributeName;
  43509. target.ranges = source.ranges;
  43510. //target.updateShaderSource();
  43511. }
  43512. class Batch{
  43513. constructor(geometry, material){
  43514. this.geometry = geometry;
  43515. this.material = material;
  43516. this.sceneNode = new Points(geometry, material);
  43517. this.geometryNode = {
  43518. estimatedSpacing: 1.0,
  43519. geometry: geometry,
  43520. };
  43521. }
  43522. getLevel(){
  43523. return 0;
  43524. }
  43525. }
  43526. class ProfileFakeOctree extends PointCloudTree{
  43527. constructor(octree){
  43528. super();
  43529. this.trueOctree = octree;
  43530. this.pcoGeometry = octree.pcoGeometry;
  43531. this.points = [];
  43532. this.visibleNodes = [];
  43533. //this.material = this.trueOctree.material;
  43534. this.material = new PointCloudMaterial$1();
  43535. //this.material.copy(this.trueOctree.material);
  43536. copyMaterial(this.trueOctree.material, this.material);
  43537. this.material.pointSizeType = PointSizeType.FIXED;
  43538. this.batchSize = 100 * 1000;
  43539. this.currentBatch = null;
  43540. }
  43541. getAttribute(name){
  43542. return this.trueOctree.getAttribute(name);
  43543. }
  43544. dispose(){
  43545. for(let node of this.visibleNodes){
  43546. node.geometry.dispose();
  43547. }
  43548. this.visibleNodes = [];
  43549. this.currentBatch = null;
  43550. this.points = [];
  43551. }
  43552. addPoints(data){
  43553. // since each call to addPoints can deliver very very few points,
  43554. // we're going to batch them into larger buffers for efficiency.
  43555. if(this.currentBatch === null){
  43556. this.currentBatch = this.createNewBatch(data);
  43557. }
  43558. this.points.push(data);
  43559. let updateRange = {
  43560. start: this.currentBatch.geometry.drawRange.count,
  43561. count: 0
  43562. };
  43563. let projectedBox = new Box3();
  43564. let truePos = new Vector3();
  43565. for(let i = 0; i < data.numPoints; i++){
  43566. if(updateRange.start + updateRange.count >= this.batchSize){
  43567. // current batch full, start new batch
  43568. for(let key of Object.keys(this.currentBatch.geometry.attributes)){
  43569. let attribute = this.currentBatch.geometry.attributes[key];
  43570. attribute.updateRange.offset = updateRange.start;
  43571. attribute.updateRange.count = updateRange.count;
  43572. attribute.needsUpdate = true;
  43573. }
  43574. this.currentBatch.geometry.computeBoundingBox();
  43575. this.currentBatch.geometry.computeBoundingSphere();
  43576. this.currentBatch = this.createNewBatch(data);
  43577. updateRange = {
  43578. start: 0,
  43579. count: 0
  43580. };
  43581. }
  43582. truePos.set(
  43583. data.data.position[3 * i + 0] + this.trueOctree.position.x,
  43584. data.data.position[3 * i + 1] + this.trueOctree.position.y,
  43585. data.data.position[3 * i + 2] + this.trueOctree.position.z,
  43586. );
  43587. let x = data.data.mileage[i];
  43588. let y = 0;
  43589. let z = truePos.z;
  43590. projectedBox.expandByPoint(new Vector3(x, y, z));
  43591. let index = updateRange.start + updateRange.count;
  43592. let geometry = this.currentBatch.geometry;
  43593. for(let attributeName of Object.keys(data.data)){
  43594. let source = data.data[attributeName];
  43595. let target = geometry.attributes[attributeName];
  43596. let numElements = target.itemSize;
  43597. for(let item = 0; item < numElements; item++){
  43598. target.array[numElements * index + item] = source[numElements * i + item];
  43599. }
  43600. }
  43601. {
  43602. let position = geometry.attributes.position;
  43603. position.array[3 * index + 0] = x;
  43604. position.array[3 * index + 1] = y;
  43605. position.array[3 * index + 2] = z;
  43606. }
  43607. updateRange.count++;
  43608. this.currentBatch.geometry.drawRange.count++;
  43609. }
  43610. for(let key of Object.keys(this.currentBatch.geometry.attributes)){
  43611. let attribute = this.currentBatch.geometry.attributes[key];
  43612. attribute.updateRange.offset = updateRange.start;
  43613. attribute.updateRange.count = updateRange.count;
  43614. attribute.needsUpdate = true;
  43615. }
  43616. data.projectedBox = projectedBox;
  43617. this.projectedBox = this.points.reduce( (a, i) => a.union(i.projectedBox), new Box3());
  43618. }
  43619. createNewBatch(data){
  43620. let geometry = new BufferGeometry();
  43621. // create new batches with batch_size elements of the same type as the attribute
  43622. for(let attributeName of Object.keys(data.data)){
  43623. let buffer = data.data[attributeName];
  43624. let numElements = buffer.length / data.numPoints; // 3 for pos, 4 for col, 1 for scalars
  43625. let constructor = buffer.constructor;
  43626. let normalized = false;
  43627. if(this.trueOctree.root.sceneNode){
  43628. if(this.trueOctree.root.sceneNode.geometry.attributes[attributeName]){
  43629. normalized = this.trueOctree.root.sceneNode.geometry.attributes[attributeName].normalized;
  43630. }
  43631. }
  43632. let batchBuffer = new constructor(numElements * this.batchSize);
  43633. let bufferAttribute = new BufferAttribute(batchBuffer, numElements, normalized);
  43634. bufferAttribute.potree = {
  43635. range: [0, 1],
  43636. };
  43637. geometry.setAttribute(attributeName, bufferAttribute);
  43638. }
  43639. geometry.drawRange.start = 0;
  43640. geometry.drawRange.count = 0;
  43641. let batch = new Batch(geometry, this.material);
  43642. this.visibleNodes.push(batch);
  43643. return batch;
  43644. }
  43645. computeVisibilityTextureData(){
  43646. let data = new Uint8Array(this.visibleNodes.length * 4);
  43647. let offsets = new Map();
  43648. for(let i = 0; i < this.visibleNodes.length; i++){
  43649. let node = this.visibleNodes[i];
  43650. offsets[node] = i;
  43651. }
  43652. return {
  43653. data: data,
  43654. offsets: offsets,
  43655. };
  43656. }
  43657. }
  43658. class ProfileWindow extends EventDispatcher$1 {
  43659. constructor (viewer) {
  43660. super();
  43661. this.viewer = viewer;
  43662. this.elRoot = $('#profile_window');
  43663. this.renderArea = this.elRoot.find('#profileCanvasContainer');
  43664. this.svg = d3.select('svg#profileSVG');
  43665. this.mouseIsDown = false;
  43666. this.projectedBox = new Box3();
  43667. this.pointclouds = new Map();
  43668. this.numPoints = 0;
  43669. this.lastAddPointsTimestamp = undefined;
  43670. this.mouse = new Vector2(0, 0);
  43671. this.scale = new Vector3(1, 1, 1);
  43672. this.autoFitEnabled = true; // completely disable/enable
  43673. this.autoFit = false; // internal
  43674. let cwIcon = `${exports.resourcePath}/icons/arrow_cw.svg`;
  43675. $('#potree_profile_rotate_cw').attr('src', cwIcon);
  43676. let ccwIcon = `${exports.resourcePath}/icons/arrow_ccw.svg`;
  43677. $('#potree_profile_rotate_ccw').attr('src', ccwIcon);
  43678. let forwardIcon = `${exports.resourcePath}/icons/arrow_up.svg`;
  43679. $('#potree_profile_move_forward').attr('src', forwardIcon);
  43680. let backwardIcon = `${exports.resourcePath}/icons/arrow_down.svg`;
  43681. $('#potree_profile_move_backward').attr('src', backwardIcon);
  43682. let csvIcon = `${exports.resourcePath}/icons/file_csv_2d.svg`;
  43683. $('#potree_download_csv_icon').attr('src', csvIcon);
  43684. let lasIcon = `${exports.resourcePath}/icons/file_las_3d.svg`;
  43685. $('#potree_download_las_icon').attr('src', lasIcon);
  43686. let closeIcon = `${exports.resourcePath}/icons/close.svg`;
  43687. $('#closeProfileContainer').attr("src", closeIcon);
  43688. this.initTHREE();
  43689. this.initSVG();
  43690. this.initListeners();
  43691. this.pRenderer = new Renderer(this.renderer);
  43692. this.elRoot.i18n();
  43693. }
  43694. initListeners () {
  43695. $(window).resize(() => {
  43696. if (this.enabled) {
  43697. this.render();
  43698. }
  43699. });
  43700. this.renderArea.mousedown(e => {
  43701. this.mouseIsDown = true;
  43702. });
  43703. this.renderArea.mouseup(e => {
  43704. this.mouseIsDown = false;
  43705. });
  43706. let viewerPickSphereSizeHandler = () => {
  43707. let camera = this.viewer.scene.getActiveCamera();
  43708. let domElement = this.viewer.renderer.domElement;
  43709. let distance = this.viewerPickSphere.position.distanceTo(camera.position);
  43710. let pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  43711. let scale = (10 / pr);
  43712. this.viewerPickSphere.scale.set(scale, scale, scale);
  43713. };
  43714. this.renderArea.mousemove(e => {
  43715. if (this.pointclouds.size === 0) {
  43716. return;
  43717. }
  43718. let rect = this.renderArea[0].getBoundingClientRect();
  43719. let x = e.clientX - rect.left;
  43720. let y = e.clientY - rect.top;
  43721. let newMouse = new Vector2(x, y);
  43722. if (this.mouseIsDown) {
  43723. // DRAG
  43724. this.autoFit = false;
  43725. this.lastDrag = new Date().getTime();
  43726. let cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  43727. let ncPos = [this.scaleX.invert(newMouse.x), this.scaleY.invert(newMouse.y)];
  43728. this.camera.position.x -= ncPos[0] - cPos[0];
  43729. this.camera.position.z -= ncPos[1] - cPos[1];
  43730. this.render();
  43731. } else if (this.pointclouds.size > 0) {
  43732. // FIND HOVERED POINT
  43733. let radius = Math.abs(this.scaleX.invert(0) - this.scaleX.invert(40));
  43734. let mileage = this.scaleX.invert(newMouse.x);
  43735. let elevation = this.scaleY.invert(newMouse.y);
  43736. let closest = this.selectPoint(mileage, elevation, radius);
  43737. if (closest) {
  43738. let point = closest.point;
  43739. let position = new Float64Array([
  43740. point.position[0] + closest.pointcloud.position.x,
  43741. point.position[1] + closest.pointcloud.position.y,
  43742. point.position[2] + closest.pointcloud.position.z
  43743. ]);
  43744. this.elRoot.find('#profileSelectionProperties').fadeIn(200);
  43745. this.pickSphere.visible = true;
  43746. this.pickSphere.scale.set(0.5 * radius, 0.5 * radius, 0.5 * radius);
  43747. this.pickSphere.position.set(point.mileage, 0, position[2]);
  43748. this.viewerPickSphere.position.set(...position);
  43749. if(!this.viewer.scene.scene.children.includes(this.viewerPickSphere)){
  43750. this.viewer.scene.scene.add(this.viewerPickSphere);
  43751. if(!this.viewer.hasEventListener("update", viewerPickSphereSizeHandler)){
  43752. this.viewer.addEventListener("update", viewerPickSphereSizeHandler);
  43753. }
  43754. }
  43755. let info = this.elRoot.find('#profileSelectionProperties');
  43756. let html = '<table>';
  43757. for (let attributeName of Object.keys(point)) {
  43758. let value = point[attributeName];
  43759. let attribute = closest.pointcloud.getAttribute(attributeName);
  43760. let transform = value => value;
  43761. if(attribute && attribute.type.size > 4){
  43762. let range = attribute.initialRange;
  43763. let scale = 1 / (range[1] - range[0]);
  43764. let offset = range[0];
  43765. transform = value => value / scale + offset;
  43766. }
  43767. if (attributeName === 'position') {
  43768. let values = [...position].map(v => Utils.addCommas(v.toFixed(3)));
  43769. html += `
  43770. <tr>
  43771. <td>x</td>
  43772. <td>${values[0]}</td>
  43773. </tr>
  43774. <tr>
  43775. <td>y</td>
  43776. <td>${values[1]}</td>
  43777. </tr>
  43778. <tr>
  43779. <td>z</td>
  43780. <td>${values[2]}</td>
  43781. </tr>`;
  43782. } else if (attributeName === 'rgba') {
  43783. html += `
  43784. <tr>
  43785. <td>${attributeName}</td>
  43786. <td>${value.join(', ')}</td>
  43787. </tr>`;
  43788. } else if (attributeName === 'normal') {
  43789. continue;
  43790. } else if (attributeName === 'mileage') {
  43791. html += `
  43792. <tr>
  43793. <td>${attributeName}</td>
  43794. <td>${value.toFixed(3)}</td>
  43795. </tr>`;
  43796. } else {
  43797. html += `
  43798. <tr>
  43799. <td>${attributeName}</td>
  43800. <td>${transform(value)}</td>
  43801. </tr>`;
  43802. }
  43803. }
  43804. html += '</table>';
  43805. info.html(html);
  43806. this.selectedPoint = point;
  43807. } else {
  43808. // this.pickSphere.visible = false;
  43809. // this.selectedPoint = null;
  43810. this.viewer.scene.scene.add(this.viewerPickSphere);
  43811. let index = this.viewer.scene.scene.children.indexOf(this.viewerPickSphere);
  43812. if(index >= 0){
  43813. this.viewer.scene.scene.children.splice(index, 1);
  43814. }
  43815. this.viewer.removeEventListener("update", viewerPickSphereSizeHandler);
  43816. }
  43817. this.render();
  43818. }
  43819. this.mouse.copy(newMouse);
  43820. });
  43821. let onWheel = e => {
  43822. this.autoFit = false;
  43823. let delta = 0;
  43824. if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9
  43825. delta = e.wheelDelta;
  43826. } else if (e.detail !== undefined) { // Firefox
  43827. delta = -e.detail;
  43828. }
  43829. let ndelta = Math.sign(delta);
  43830. let cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  43831. if (ndelta > 0) {
  43832. // + 10%
  43833. this.scale.multiplyScalar(1.1);
  43834. } else {
  43835. // - 10%
  43836. this.scale.multiplyScalar(100 / 110);
  43837. }
  43838. this.updateScales();
  43839. let ncPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  43840. this.camera.position.x -= ncPos[0] - cPos[0];
  43841. this.camera.position.z -= ncPos[1] - cPos[1];
  43842. this.render();
  43843. this.updateScales();
  43844. };
  43845. $(this.renderArea)[0].addEventListener('mousewheel', onWheel, false);
  43846. $(this.renderArea)[0].addEventListener('DOMMouseScroll', onWheel, false); // Firefox
  43847. $('#closeProfileContainer').click(() => {
  43848. this.hide();
  43849. });
  43850. let getProfilePoints = () => {
  43851. let points = new Points$1();
  43852. for(let [pointcloud, entry] of this.pointclouds){
  43853. for(let pointSet of entry.points){
  43854. let originPos = pointSet.data.position;
  43855. let trueElevationPosition = new Float32Array(originPos);
  43856. for(let i = 0; i < pointSet.numPoints; i++){
  43857. trueElevationPosition[3 * i + 2] += pointcloud.position.z;
  43858. }
  43859. pointSet.data.position = trueElevationPosition;
  43860. points.add(pointSet);
  43861. pointSet.data.position = originPos;
  43862. }
  43863. }
  43864. return points;
  43865. };
  43866. $('#potree_download_csv_icon').click(() => {
  43867. let points = getProfilePoints();
  43868. let string = CSVExporter.toString(points);
  43869. let blob = new Blob([string], {type: "text/string"});
  43870. $('#potree_download_profile_ortho_link').attr('href', URL.createObjectURL(blob));
  43871. });
  43872. $('#potree_download_las_icon').click(() => {
  43873. let points = getProfilePoints();
  43874. let buffer = LASExporter.toLAS(points);
  43875. let blob = new Blob([buffer], {type: "application/octet-binary"});
  43876. $('#potree_download_profile_link').attr('href', URL.createObjectURL(blob));
  43877. });
  43878. }
  43879. selectPoint (mileage, elevation, radius) {
  43880. let closest = {
  43881. distance: Infinity,
  43882. pointcloud: null,
  43883. points: null,
  43884. index: null
  43885. };
  43886. let pointBox = new Box2(
  43887. new Vector2(mileage - radius, elevation - radius),
  43888. new Vector2(mileage + radius, elevation + radius));
  43889. let numTested = 0;
  43890. let numSkipped = 0;
  43891. let numTestedPoints = 0;
  43892. let numSkippedPoints = 0;
  43893. for (let [pointcloud, entry] of this.pointclouds) {
  43894. for(let points of entry.points){
  43895. let collisionBox = new Box2(
  43896. new Vector2(points.projectedBox.min.x, points.projectedBox.min.z),
  43897. new Vector2(points.projectedBox.max.x, points.projectedBox.max.z)
  43898. );
  43899. let intersects = collisionBox.intersectsBox(pointBox);
  43900. if(!intersects){
  43901. numSkipped++;
  43902. numSkippedPoints += points.numPoints;
  43903. continue;
  43904. }
  43905. numTested++;
  43906. numTestedPoints += points.numPoints;
  43907. for (let i = 0; i < points.numPoints; i++) {
  43908. let m = points.data.mileage[i] - mileage;
  43909. let e = points.data.position[3 * i + 2] - elevation + pointcloud.position.z;
  43910. let r = Math.sqrt(m * m + e * e);
  43911. const withinDistance = r < radius && r < closest.distance;
  43912. let unfilteredClass = true;
  43913. if(points.data.classification){
  43914. const classification = pointcloud.material.classification;
  43915. const pointClassID = points.data.classification[i];
  43916. const pointClassValue = classification[pointClassID];
  43917. if(pointClassValue && (!pointClassValue.visible || pointClassValue.color.w === 0)){
  43918. unfilteredClass = false;
  43919. }
  43920. }
  43921. if (withinDistance && unfilteredClass) {
  43922. closest = {
  43923. distance: r,
  43924. pointcloud: pointcloud,
  43925. points: points,
  43926. index: i
  43927. };
  43928. }
  43929. }
  43930. }
  43931. }
  43932. //console.log(`nodes: ${numTested}, ${numSkipped} || points: ${numTestedPoints}, ${numSkippedPoints}`);
  43933. if (closest.distance < Infinity) {
  43934. let points = closest.points;
  43935. let point = {};
  43936. let attributes = Object.keys(points.data);
  43937. for (let attribute of attributes) {
  43938. let attributeData = points.data[attribute];
  43939. let itemSize = attributeData.length / points.numPoints;
  43940. let value = attributeData.subarray(itemSize * closest.index, itemSize * closest.index + itemSize);
  43941. if (value.length === 1) {
  43942. point[attribute] = value[0];
  43943. } else {
  43944. point[attribute] = value;
  43945. }
  43946. }
  43947. closest.point = point;
  43948. return closest;
  43949. } else {
  43950. return null;
  43951. }
  43952. }
  43953. initTHREE () {
  43954. this.renderer = new WebGLRenderer({alpha: true, premultipliedAlpha: false});
  43955. this.renderer.setClearColor(0x000000, 0);
  43956. this.renderer.setSize(10, 10);
  43957. this.renderer.autoClear = false;
  43958. this.renderArea.append($(this.renderer.domElement));
  43959. this.renderer.domElement.tabIndex = '2222';
  43960. $(this.renderer.domElement).css('width', '100%');
  43961. $(this.renderer.domElement).css('height', '100%');
  43962. {
  43963. let gl = this.renderer.getContext();
  43964. if(gl.createVertexArray == null){
  43965. let extVAO = gl.getExtension('OES_vertex_array_object');
  43966. if(!extVAO){
  43967. throw new Error("OES_vertex_array_object extension not supported");
  43968. }
  43969. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  43970. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  43971. }
  43972. }
  43973. this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000);
  43974. this.camera.up.set(0, 0, 1);
  43975. this.camera.rotation.order = "ZXY";
  43976. this.camera.rotation.x = Math.PI / 2.0;
  43977. this.scene = new Scene();
  43978. this.profileScene = new Scene();
  43979. let sg = new SphereGeometry(1, 16, 16);
  43980. let sm = new MeshNormalMaterial();
  43981. this.pickSphere = new Mesh(sg, sm);
  43982. this.scene.add(this.pickSphere);
  43983. this.viewerPickSphere = new Mesh(sg, sm);
  43984. }
  43985. initSVG () {
  43986. let width = this.renderArea[0].clientWidth;
  43987. let height = this.renderArea[0].clientHeight;
  43988. let marginLeft = this.renderArea[0].offsetLeft;
  43989. this.svg.selectAll('*').remove();
  43990. this.scaleX = d3.scale.linear()
  43991. .domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x])
  43992. .range([0, width]);
  43993. this.scaleY = d3.scale.linear()
  43994. .domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z])
  43995. .range([height, 0]);
  43996. this.xAxis = d3.svg.axis()
  43997. .scale(this.scaleX)
  43998. .orient('bottom')
  43999. .innerTickSize(-height)
  44000. .outerTickSize(1)
  44001. .tickPadding(10)
  44002. .ticks(width / 50);
  44003. this.yAxis = d3.svg.axis()
  44004. .scale(this.scaleY)
  44005. .orient('left')
  44006. .innerTickSize(-width)
  44007. .outerTickSize(1)
  44008. .tickPadding(10)
  44009. .ticks(height / 20);
  44010. this.elXAxis = this.svg.append('g')
  44011. .attr('class', 'x axis')
  44012. .attr('transform', `translate(${marginLeft}, ${height})`)
  44013. .call(this.xAxis);
  44014. this.elYAxis = this.svg.append('g')
  44015. .attr('class', 'y axis')
  44016. .attr('transform', `translate(${marginLeft}, 0)`)
  44017. .call(this.yAxis);
  44018. }
  44019. addPoints (pointcloud, points) {
  44020. if(points.numPoints === 0){
  44021. return;
  44022. }
  44023. let entry = this.pointclouds.get(pointcloud);
  44024. if(!entry){
  44025. entry = new ProfileFakeOctree(pointcloud);
  44026. this.pointclouds.set(pointcloud, entry);
  44027. this.profileScene.add(entry);
  44028. let materialChanged = () => {
  44029. this.render();
  44030. };
  44031. materialChanged();
  44032. pointcloud.material.addEventListener('material_property_changed', materialChanged);
  44033. this.addEventListener("on_reset_once", () => {
  44034. pointcloud.material.removeEventListener('material_property_changed', materialChanged);
  44035. });
  44036. }
  44037. entry.addPoints(points);
  44038. this.projectedBox.union(entry.projectedBox);
  44039. if (this.autoFit && this.autoFitEnabled) {
  44040. let width = this.renderArea[0].clientWidth;
  44041. let height = this.renderArea[0].clientHeight;
  44042. let size = this.projectedBox.getSize(new Vector3());
  44043. let sx = width / size.x;
  44044. let sy = height / size.z;
  44045. let scale = Math.min(sx, sy);
  44046. let center = this.projectedBox.getCenter(new Vector3());
  44047. this.scale.set(scale, scale, 1);
  44048. this.camera.position.copy(center);
  44049. //console.log("camera: ", this.camera.position.toArray().join(", "));
  44050. }
  44051. //console.log(entry);
  44052. this.render();
  44053. let numPoints = 0;
  44054. for (let [key, value] of this.pointclouds.entries()) {
  44055. numPoints += value.points.reduce( (a, i) => a + i.numPoints, 0);
  44056. }
  44057. $(`#profile_num_points`).html(Utils.addCommas(numPoints));
  44058. }
  44059. reset () {
  44060. this.lastReset = new Date().getTime();
  44061. this.dispatchEvent({type: "on_reset_once"});
  44062. this.removeEventListeners("on_reset_once");
  44063. this.autoFit = true;
  44064. this.projectedBox = new Box3();
  44065. for(let [key, entry] of this.pointclouds){
  44066. entry.dispose();
  44067. }
  44068. this.pointclouds.clear();
  44069. this.mouseIsDown = false;
  44070. this.mouse.set(0, 0);
  44071. if(this.autoFitEnabled){
  44072. this.scale.set(1, 1, 1);
  44073. }
  44074. this.pickSphere.visible = false;
  44075. this.elRoot.find('#profileSelectionProperties').hide();
  44076. this.render();
  44077. }
  44078. show () {
  44079. this.elRoot.fadeIn();
  44080. this.enabled = true;
  44081. }
  44082. hide () {
  44083. this.elRoot.fadeOut();
  44084. this.enabled = false;
  44085. }
  44086. updateScales () {
  44087. let width = this.renderArea[0].clientWidth;
  44088. let height = this.renderArea[0].clientHeight;
  44089. let left = (-width / 2) / this.scale.x;
  44090. let right = (+width / 2) / this.scale.x;
  44091. let top = (+height / 2) / this.scale.y;
  44092. let bottom = (-height / 2) / this.scale.y;
  44093. this.camera.left = left;
  44094. this.camera.right = right;
  44095. this.camera.top = top;
  44096. this.camera.bottom = bottom;
  44097. this.camera.updateProjectionMatrix();
  44098. this.scaleX.domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x])
  44099. .range([0, width]);
  44100. this.scaleY.domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z])
  44101. .range([height, 0]);
  44102. let marginLeft = this.renderArea[0].offsetLeft;
  44103. this.xAxis.scale(this.scaleX)
  44104. .orient('bottom')
  44105. .innerTickSize(-height)
  44106. .outerTickSize(1)
  44107. .tickPadding(10)
  44108. .ticks(width / 50);
  44109. this.yAxis.scale(this.scaleY)
  44110. .orient('left')
  44111. .innerTickSize(-width)
  44112. .outerTickSize(1)
  44113. .tickPadding(10)
  44114. .ticks(height / 20);
  44115. this.elXAxis
  44116. .attr('transform', `translate(${marginLeft}, ${height})`)
  44117. .call(this.xAxis);
  44118. this.elYAxis
  44119. .attr('transform', `translate(${marginLeft}, 0)`)
  44120. .call(this.yAxis);
  44121. }
  44122. requestScaleUpdate(){
  44123. let threshold = 100;
  44124. let allowUpdate = ((this.lastReset === undefined) || (this.lastScaleUpdate === undefined))
  44125. || ((new Date().getTime() - this.lastReset) > threshold && (new Date().getTime() - this.lastScaleUpdate) > threshold);
  44126. if(allowUpdate){
  44127. this.updateScales();
  44128. this.lastScaleUpdate = new Date().getTime();
  44129. this.scaleUpdatePending = false;
  44130. }else if(!this.scaleUpdatePending) {
  44131. setTimeout(this.requestScaleUpdate.bind(this), 100);
  44132. this.scaleUpdatePending = true;
  44133. }
  44134. }
  44135. render () {
  44136. let width = this.renderArea[0].clientWidth;
  44137. let height = this.renderArea[0].clientHeight;
  44138. let {renderer, pRenderer, camera, profileScene, scene} = this;
  44139. let {scaleX, pickSphere} = this;
  44140. renderer.setSize(width, height);
  44141. renderer.setClearColor(0x000000, 0);
  44142. renderer.clear(true, true, false);
  44143. for(let pointcloud of this.pointclouds.keys()){
  44144. let source = pointcloud.material;
  44145. let target = this.pointclouds.get(pointcloud).material;
  44146. copyMaterial(source, target);
  44147. target.size = 2;
  44148. }
  44149. pRenderer.render(profileScene, camera, null);
  44150. let radius = Math.abs(scaleX.invert(0) - scaleX.invert(5));
  44151. if (radius === 0) {
  44152. pickSphere.visible = false;
  44153. } else {
  44154. pickSphere.scale.set(radius, radius, radius);
  44155. pickSphere.visible = true;
  44156. }
  44157. renderer.render(scene, camera);
  44158. this.requestScaleUpdate();
  44159. }
  44160. };
  44161. class ProfileWindowController {
  44162. constructor (viewer) {
  44163. this.viewer = viewer;
  44164. this.profileWindow = viewer.profileWindow;
  44165. this.profile = null;
  44166. this.numPoints = 0;
  44167. this.threshold = 60 * 1000;
  44168. this.rotateAmount = 10;
  44169. this.scheduledRecomputeTime = null;
  44170. this.enabled = true;
  44171. this.requests = [];
  44172. this._recompute = () => { this.recompute(); };
  44173. this.viewer.addEventListener("scene_changed", e => {
  44174. e.oldScene.removeEventListener("pointcloud_added", this._recompute);
  44175. e.scene.addEventListener("pointcloud_added", this._recompute);
  44176. });
  44177. this.viewer.scene.addEventListener("pointcloud_added", this._recompute);
  44178. $("#potree_profile_rotate_amount").val(parseInt(this.rotateAmount));
  44179. $("#potree_profile_rotate_amount").on("input", (e) => {
  44180. const str = $("#potree_profile_rotate_amount").val();
  44181. if(!isNaN(str)){
  44182. const value = parseFloat(str);
  44183. this.rotateAmount = value;
  44184. $("#potree_profile_rotate_amount").css("background-color", "");
  44185. }else {
  44186. $("#potree_profile_rotate_amount").css("background-color", "#ff9999");
  44187. }
  44188. });
  44189. const rotate = (radians) => {
  44190. const profile = this.profile;
  44191. const points = profile.points;
  44192. const start = points[0];
  44193. const end = points[points.length - 1];
  44194. const center = start.clone().add(end).multiplyScalar(0.5);
  44195. const mMoveOrigin = new Matrix4().makeTranslation(-center.x, -center.y, -center.z);
  44196. const mRotate = new Matrix4().makeRotationZ(radians);
  44197. const mMoveBack = new Matrix4().makeTranslation(center.x, center.y, center.z);
  44198. //const transform = mMoveOrigin.multiply(mRotate).multiply(mMoveBack);
  44199. const transform = mMoveBack.multiply(mRotate).multiply(mMoveOrigin);
  44200. const rotatedPoints = points.map( point => point.clone().applyMatrix4(transform) );
  44201. this.profileWindow.autoFitEnabled = false;
  44202. for(let i = 0; i < points.length; i++){
  44203. profile.setPosition(i, rotatedPoints[i]);
  44204. }
  44205. };
  44206. $("#potree_profile_rotate_cw").click( () => {
  44207. const radians = MathUtils.degToRad(this.rotateAmount);
  44208. rotate(-radians);
  44209. });
  44210. $("#potree_profile_rotate_ccw").click( () => {
  44211. const radians = MathUtils.degToRad(this.rotateAmount);
  44212. rotate(radians);
  44213. });
  44214. $("#potree_profile_move_forward").click( () => {
  44215. const profile = this.profile;
  44216. const points = profile.points;
  44217. const start = points[0];
  44218. const end = points[points.length - 1];
  44219. const dir = end.clone().sub(start).normalize();
  44220. const up = new Vector3(0, 0, 1);
  44221. const forward = up.cross(dir);
  44222. const move = forward.clone().multiplyScalar(profile.width / 2);
  44223. this.profileWindow.autoFitEnabled = false;
  44224. for(let i = 0; i < points.length; i++){
  44225. profile.setPosition(i, points[i].clone().add(move));
  44226. }
  44227. });
  44228. $("#potree_profile_move_backward").click( () => {
  44229. const profile = this.profile;
  44230. const points = profile.points;
  44231. const start = points[0];
  44232. const end = points[points.length - 1];
  44233. const dir = end.clone().sub(start).normalize();
  44234. const up = new Vector3(0, 0, 1);
  44235. const forward = up.cross(dir);
  44236. const move = forward.clone().multiplyScalar(-profile.width / 2);
  44237. this.profileWindow.autoFitEnabled = false;
  44238. for(let i = 0; i < points.length; i++){
  44239. profile.setPosition(i, points[i].clone().add(move));
  44240. }
  44241. });
  44242. }
  44243. setProfile (profile) {
  44244. if (this.profile !== null && this.profile !== profile) {
  44245. this.profile.removeEventListener('marker_moved', this._recompute);
  44246. this.profile.removeEventListener('marker_added', this._recompute);
  44247. this.profile.removeEventListener('marker_removed', this._recompute);
  44248. this.profile.removeEventListener('width_changed', this._recompute);
  44249. }
  44250. this.profile = profile;
  44251. {
  44252. this.profile.addEventListener('marker_moved', this._recompute);
  44253. this.profile.addEventListener('marker_added', this._recompute);
  44254. this.profile.addEventListener('marker_removed', this._recompute);
  44255. this.profile.addEventListener('width_changed', this._recompute);
  44256. }
  44257. this.recompute();
  44258. }
  44259. reset () {
  44260. this.profileWindow.reset();
  44261. this.numPoints = 0;
  44262. if (this.profile) {
  44263. for (let request of this.requests) {
  44264. request.cancel();
  44265. }
  44266. }
  44267. }
  44268. progressHandler (pointcloud, progress) {
  44269. for (let segment of progress.segments) {
  44270. this.profileWindow.addPoints(pointcloud, segment.points);
  44271. this.numPoints += segment.points.numPoints;
  44272. }
  44273. }
  44274. cancel () {
  44275. for (let request of this.requests) {
  44276. request.cancel();
  44277. // request.finishLevelThenCancel();
  44278. }
  44279. this.requests = [];
  44280. };
  44281. finishLevelThenCancel(){
  44282. for (let request of this.requests) {
  44283. request.finishLevelThenCancel();
  44284. }
  44285. this.requests = [];
  44286. }
  44287. recompute () {
  44288. if (!this.profile) {
  44289. return;
  44290. }
  44291. if (this.scheduledRecomputeTime !== null && this.scheduledRecomputeTime > new Date().getTime()) {
  44292. return;
  44293. } else {
  44294. this.scheduledRecomputeTime = new Date().getTime() + 100;
  44295. }
  44296. this.scheduledRecomputeTime = null;
  44297. this.reset();
  44298. for (let pointcloud of this.viewer.scene.pointclouds.filter(p => p.visible)) {
  44299. let request = pointcloud.getPointsInProfile(this.profile, null, {
  44300. 'onProgress': (event) => {
  44301. if (!this.enabled) {
  44302. return;
  44303. }
  44304. this.progressHandler(pointcloud, event.points);
  44305. if (this.numPoints > this.threshold) {
  44306. this.finishLevelThenCancel();
  44307. }
  44308. },
  44309. 'onFinish': (event) => {
  44310. if (!this.enabled) {
  44311. }
  44312. },
  44313. 'onCancel': () => {
  44314. if (!this.enabled) {
  44315. }
  44316. }
  44317. });
  44318. this.requests.push(request);
  44319. }
  44320. }
  44321. };
  44322. //import { EventDispatcher } from "../EventDispatcher.js";
  44323. class VolumeTool extends EventDispatcher{
  44324. constructor (viewer) {
  44325. super();
  44326. this.viewer = viewer;
  44327. this.renderer = viewer.renderer;
  44328. this.addEventListener('start_inserting_volume', e => {
  44329. this.viewer.dispatchEvent({
  44330. type: 'cancel_insertions'
  44331. });
  44332. });
  44333. this.scene = new Scene();
  44334. this.scene.name = 'scene_volume';
  44335. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  44336. this.onRemove = e => {
  44337. this.scene.remove(e.volume);
  44338. };
  44339. this.onAdd = e => {
  44340. this.scene.add(e.volume);
  44341. };
  44342. for(let volume of viewer.scene.volumes){
  44343. this.onAdd({volume: volume});
  44344. }
  44345. this.viewer.inputHandler.addEventListener('delete', e => {
  44346. let volumes = e.selection.filter(e => (e instanceof Volume));
  44347. volumes.forEach(e => this.viewer.scene.removeVolume(e));
  44348. });
  44349. viewer.addEventListener("update", this.update.bind(this));
  44350. viewer.addEventListener("render.pass.scene", e => this.render(e));
  44351. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  44352. viewer.scene.addEventListener('volume_added', this.onAdd);
  44353. viewer.scene.addEventListener('volume_removed', this.onRemove);
  44354. }
  44355. onSceneChange(e){
  44356. if(e.oldScene){
  44357. e.oldScene.removeEventListeners('volume_added', this.onAdd);
  44358. e.oldScene.removeEventListeners('volume_removed', this.onRemove);
  44359. }
  44360. e.scene.addEventListener('volume_added', this.onAdd);
  44361. e.scene.addEventListener('volume_removed', this.onRemove);
  44362. }
  44363. startInsertion (args = {}) {
  44364. let volume;
  44365. if(args.type){
  44366. volume = new args.type();
  44367. }else {
  44368. volume = new BoxVolume();
  44369. }
  44370. volume.clip = args.clip || false;
  44371. volume.name = args.name || 'Volume';
  44372. this.dispatchEvent({
  44373. type: 'start_inserting_volume',
  44374. volume: volume
  44375. });
  44376. this.viewer.scene.addVolume(volume);
  44377. this.scene.add(volume);
  44378. let cancel = {
  44379. callback: null
  44380. };
  44381. let drag = e => {
  44382. let camera = this.viewer.scene.getActiveCamera();
  44383. let I = Utils.getMousePointCloudIntersection(
  44384. e.drag.end,
  44385. this.viewer.scene.getActiveCamera(),
  44386. this.viewer,
  44387. this.viewer.scene.pointclouds,
  44388. {pickClipped: false});
  44389. if (I) {
  44390. volume.position.copy(I.location);
  44391. let wp = volume.getWorldPosition(new Vector3()).applyMatrix4(camera.matrixWorldInverse);
  44392. // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix);
  44393. let w = Math.abs((wp.z / 5));
  44394. volume.scale.set(w, w, w);
  44395. }
  44396. };
  44397. let drop = e => {
  44398. volume.removeEventListener('drag', drag);
  44399. volume.removeEventListener('drop', drop);
  44400. cancel.callback();
  44401. };
  44402. cancel.callback = e => {
  44403. volume.removeEventListener('drag', drag);
  44404. volume.removeEventListener('drop', drop);
  44405. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  44406. };
  44407. volume.addEventListener('drag', drag);
  44408. volume.addEventListener('drop', drop);
  44409. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  44410. this.viewer.inputHandler.startDragging(volume);
  44411. return volume;
  44412. }
  44413. update(){
  44414. if (!this.viewer.scene) {
  44415. return;
  44416. }
  44417. let camera = this.viewer.scene.getActiveCamera();
  44418. let renderAreaSize = this.viewer.renderer.getSize(new Vector2());
  44419. let clientWidth = renderAreaSize.width;
  44420. let clientHeight = renderAreaSize.height;
  44421. let volumes = this.viewer.scene.volumes;
  44422. for (let volume of volumes) {
  44423. let label = volume.label;
  44424. {
  44425. let distance = label.position.distanceTo(camera.position);
  44426. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  44427. let scale = (70 / pr);
  44428. label.scale.set(scale, scale, scale);
  44429. }
  44430. let calculatedVolume = volume.getVolume();
  44431. 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
  44432. let text = Utils.addCommas(calculatedVolume.toFixed(3)) + ' ' + this.viewer.lengthUnitDisplay.code + '\u00B3';
  44433. label.setText(text);
  44434. }
  44435. }
  44436. render(params){
  44437. const renderer = this.viewer.renderer;
  44438. const oldTarget = renderer.getRenderTarget();
  44439. if(params.renderTarget){
  44440. renderer.setRenderTarget(params.renderTarget);
  44441. }
  44442. renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  44443. renderer.setRenderTarget(oldTarget);
  44444. }
  44445. }
  44446. /**
  44447. *
  44448. * code adapted from three.js BoxHelper.js
  44449. * https://github.com/mrdoob/three.js/blob/dev/src/helpers/BoxHelper.js
  44450. *
  44451. * @author mrdoob / http://mrdoob.com/
  44452. * @author Mugen87 / http://github.com/Mugen87
  44453. * @author mschuetz / http://potree.org
  44454. */
  44455. class Box3Helper$1 extends LineSegments {
  44456. constructor (box, color, depthTest = true) {
  44457. if (color === undefined) color = 0xffff00;
  44458. let 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 ]);
  44459. let positions = new Float32Array([
  44460. box.min.x, box.min.y, box.min.z,
  44461. box.max.x, box.min.y, box.min.z,
  44462. box.max.x, box.min.y, box.max.z,
  44463. box.min.x, box.min.y, box.max.z,
  44464. box.min.x, box.max.y, box.min.z,
  44465. box.max.x, box.max.y, box.min.z,
  44466. box.max.x, box.max.y, box.max.z,
  44467. box.min.x, box.max.y, box.max.z
  44468. ]);
  44469. let geometry = new BufferGeometry();
  44470. geometry.setIndex(new BufferAttribute(indices, 1));
  44471. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  44472. let material = new LineBasicMaterial({ color: color , depthTest});
  44473. super(geometry, material);
  44474. }
  44475. }
  44476. const KeyCodes = {
  44477. LEFT: 37,
  44478. UP: 38,
  44479. RIGHT: 39,
  44480. BOTTOM: 40,
  44481. DELETE: 46,
  44482. A: 'A'.charCodeAt(0),
  44483. S: 'S'.charCodeAt(0),
  44484. D: 'D'.charCodeAt(0),
  44485. W: 'W'.charCodeAt(0),
  44486. Q: 'Q'.charCodeAt(0),
  44487. E: 'E'.charCodeAt(0),
  44488. R: 'R'.charCodeAt(0),
  44489. F: 'F'.charCodeAt(0)
  44490. };
  44491. class NormalizationMaterial extends RawShaderMaterial{
  44492. constructor(parameters = {}){
  44493. super();
  44494. let uniforms = {
  44495. uDepthMap: { type: 't', value: null },
  44496. uWeightMap: { type: 't', value: null },
  44497. };
  44498. this.setValues({
  44499. uniforms: uniforms,
  44500. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  44501. fragmentShader: this.getDefines() + Shaders['normalize.fs'],
  44502. });
  44503. }
  44504. getDefines() {
  44505. let defines = '';
  44506. return defines;
  44507. }
  44508. updateShaderSource() {
  44509. let vs = this.getDefines() + Shaders['normalize.vs'];
  44510. let fs = this.getDefines() + Shaders['normalize.fs'];
  44511. this.setValues({
  44512. vertexShader: vs,
  44513. fragmentShader: fs
  44514. });
  44515. this.needsUpdate = true;
  44516. }
  44517. }
  44518. class NormalizationEDLMaterial extends RawShaderMaterial{
  44519. constructor(parameters = {}){
  44520. super();
  44521. let uniforms = {
  44522. screenWidth: { type: 'f', value: 0 },
  44523. screenHeight: { type: 'f', value: 0 },
  44524. edlStrength: { type: 'f', value: 1.0 },
  44525. radius: { type: 'f', value: 1.0 },
  44526. neighbours: { type: '2fv', value: [] },
  44527. uEDLMap: { type: 't', value: null },
  44528. uDepthMap: { type: 't', value: null },
  44529. uWeightMap: { type: 't', value: null },
  44530. };
  44531. this.setValues({
  44532. uniforms: uniforms,
  44533. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  44534. fragmentShader: this.getDefines() + Shaders['normalize_and_edl.fs'],
  44535. });
  44536. this.neighbourCount = 8;
  44537. }
  44538. getDefines() {
  44539. let defines = '';
  44540. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  44541. return defines;
  44542. }
  44543. updateShaderSource() {
  44544. let vs = this.getDefines() + Shaders['normalize.vs'];
  44545. let fs = this.getDefines() + Shaders['normalize_and_edl.fs'];
  44546. this.setValues({
  44547. vertexShader: vs,
  44548. fragmentShader: fs
  44549. });
  44550. this.uniforms.neighbours.value = this.neighbours;
  44551. this.needsUpdate = true;
  44552. }
  44553. get neighbourCount(){
  44554. return this._neighbourCount;
  44555. }
  44556. set neighbourCount(value){
  44557. if (this._neighbourCount !== value) {
  44558. this._neighbourCount = value;
  44559. this.neighbours = new Float32Array(this._neighbourCount * 2);
  44560. for (let c = 0; c < this._neighbourCount; c++) {
  44561. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  44562. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  44563. }
  44564. this.updateShaderSource();
  44565. }
  44566. }
  44567. }
  44568. //在potree.shim中修改。 。official中用不到且有bug
  44569. class HQSplatRenderer{
  44570. constructor(viewer){
  44571. this.viewer = viewer;
  44572. this.depthMaterials = new Map();
  44573. this.attributeMaterials = new Map();
  44574. this.normalizationMaterial = null;
  44575. this.rtDepth = null;
  44576. this.rtAttribute = null;
  44577. this.gl = viewer.renderer.getContext();
  44578. this.initialized = false;
  44579. }
  44580. init(){
  44581. if (this.initialized) {
  44582. return;
  44583. }
  44584. this.normalizationMaterial = new NormalizationMaterial();
  44585. this.normalizationMaterial.depthTest = true;
  44586. this.normalizationMaterial.depthWrite = true;
  44587. this.normalizationMaterial.transparent = true;
  44588. this.normalizationEDLMaterial = new NormalizationEDLMaterial();
  44589. this.normalizationEDLMaterial.depthTest = true;
  44590. this.normalizationEDLMaterial.depthWrite = true;
  44591. this.normalizationEDLMaterial.transparent = true;
  44592. this.rtDepth = new WebGLRenderTarget(1024, 1024, {
  44593. minFilter: NearestFilter,
  44594. magFilter: NearestFilter,
  44595. format: RGBAFormat,
  44596. type: FloatType,
  44597. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  44598. });
  44599. this.rtAttribute = new WebGLRenderTarget(1024, 1024, {
  44600. minFilter: NearestFilter,
  44601. magFilter: NearestFilter,
  44602. format: RGBAFormat,
  44603. type: FloatType,
  44604. depthTexture: this.rtDepth.depthTexture,
  44605. });
  44606. this.initialized = true;
  44607. };
  44608. resize(width, height){
  44609. this.rtDepth.setSize(width, height);
  44610. this.rtAttribute.setSize(width, height);
  44611. }
  44612. clearTargets(){
  44613. const viewer = this.viewer;
  44614. const {renderer} = viewer;
  44615. const oldTarget = renderer.getRenderTarget();
  44616. renderer.setClearColor(0x000000, 0);
  44617. renderer.setRenderTarget( this.rtDepth );
  44618. renderer.clear( true, true, true );
  44619. renderer.setRenderTarget( this.rtAttribute );
  44620. renderer.clear( true, true, true );
  44621. renderer.setRenderTarget(oldTarget);
  44622. }
  44623. clear(){
  44624. this.init();
  44625. const {renderer, background} = this.viewer;
  44626. if(background === "skybox"){
  44627. renderer.setClearColor(0x000000, 0);
  44628. } else if (background === 'gradient') {
  44629. renderer.setClearColor(0x000000, 0);
  44630. } else if (background === 'black') {
  44631. renderer.setClearColor(0x000000, 1);
  44632. } else if (background === 'white') {
  44633. renderer.setClearColor(0xFFFFFF, 1);
  44634. } else {
  44635. renderer.setClearColor(0x000000, 0);
  44636. }
  44637. renderer.clear();
  44638. this.clearTargets();
  44639. }
  44640. render (params) {
  44641. this.init();
  44642. const viewer = this.viewer;
  44643. const camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  44644. const {width, height} = this.viewer.renderer.getSize(new Vector2());
  44645. viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  44646. this.resize(width, height);
  44647. const visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible);
  44648. const originalMaterials = new Map();
  44649. for(let pointcloud of visiblePointClouds){
  44650. originalMaterials.set(pointcloud, pointcloud.material);
  44651. if(!this.attributeMaterials.has(pointcloud)){
  44652. let attributeMaterial = new PointCloudMaterial$1();
  44653. this.attributeMaterials.set(pointcloud, attributeMaterial);
  44654. }
  44655. if(!this.depthMaterials.has(pointcloud)){
  44656. let depthMaterial = new PointCloudMaterial$1();
  44657. depthMaterial.setDefine("depth_pass", "#define hq_depth_pass");
  44658. depthMaterial.setDefine("use_edl", "#define use_edl");
  44659. this.depthMaterials.set(pointcloud, depthMaterial);
  44660. }
  44661. }
  44662. { // DEPTH PASS
  44663. for (let pointcloud of visiblePointClouds) {
  44664. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  44665. let material = originalMaterials.get(pointcloud);
  44666. let depthMaterial = this.depthMaterials.get(pointcloud);
  44667. depthMaterial.size = material.size;
  44668. depthMaterial.minSize = material.minSize;
  44669. depthMaterial.maxSize = material.maxSize;
  44670. depthMaterial.pointSizeType = material.pointSizeType;
  44671. depthMaterial.visibleNodesTexture = material.visibleNodesTexture;
  44672. depthMaterial.weighted = false;
  44673. depthMaterial.screenWidth = width;
  44674. depthMaterial.shape = PointShape$1.CIRCLE;
  44675. depthMaterial.screenHeight = height;
  44676. depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  44677. depthMaterial.uniforms.octreeSize.value = octreeSize;
  44678. depthMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  44679. depthMaterial.classification = material.classification;
  44680. depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  44681. depthMaterial.classificationTexture.needsUpdate = true;
  44682. depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  44683. depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  44684. depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  44685. depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  44686. depthMaterial.clipTask = material.clipTask;
  44687. depthMaterial.clipMethod = material.clipMethod;
  44688. depthMaterial.setClipBoxes(material.clipBoxes);
  44689. depthMaterial.setClipPolygons(material.clipPolygons);
  44690. pointcloud.material = depthMaterial;
  44691. }
  44692. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtDepth, {
  44693. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume$1)),
  44694. });
  44695. }
  44696. { // ATTRIBUTE PASS
  44697. for (let pointcloud of visiblePointClouds) {
  44698. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  44699. let material = originalMaterials.get(pointcloud);
  44700. let attributeMaterial = this.attributeMaterials.get(pointcloud);
  44701. attributeMaterial.size = material.size;
  44702. attributeMaterial.minSize = material.minSize;
  44703. attributeMaterial.maxSize = material.maxSize;
  44704. attributeMaterial.pointSizeType = material.pointSizeType;
  44705. attributeMaterial.activeAttributeName = material.activeAttributeName;
  44706. attributeMaterial.visibleNodesTexture = material.visibleNodesTexture;
  44707. attributeMaterial.weighted = true;
  44708. attributeMaterial.screenWidth = width;
  44709. attributeMaterial.screenHeight = height;
  44710. attributeMaterial.shape = PointShape$1.CIRCLE;
  44711. attributeMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  44712. attributeMaterial.uniforms.octreeSize.value = octreeSize;
  44713. attributeMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  44714. attributeMaterial.classification = material.classification;
  44715. attributeMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  44716. attributeMaterial.classificationTexture.needsUpdate = true;
  44717. attributeMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  44718. attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  44719. attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  44720. attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  44721. attributeMaterial.elevationGradientRepeat = material.elevationGradientRepeat;
  44722. attributeMaterial.elevationRange = material.elevationRange;
  44723. attributeMaterial.gradient = material.gradient;
  44724. attributeMaterial.matcap = material.matcap;
  44725. attributeMaterial.intensityRange = material.intensityRange;
  44726. attributeMaterial.intensityGamma = material.intensityGamma;
  44727. attributeMaterial.intensityContrast = material.intensityContrast;
  44728. attributeMaterial.intensityBrightness = material.intensityBrightness;
  44729. attributeMaterial.rgbGamma = material.rgbGamma;
  44730. attributeMaterial.rgbContrast = material.rgbContrast;
  44731. attributeMaterial.rgbBrightness = material.rgbBrightness;
  44732. attributeMaterial.weightRGB = material.weightRGB;
  44733. attributeMaterial.weightIntensity = material.weightIntensity;
  44734. attributeMaterial.weightElevation = material.weightElevation;
  44735. attributeMaterial.weightRGB = material.weightRGB;
  44736. attributeMaterial.weightClassification = material.weightClassification;
  44737. attributeMaterial.weightReturnNumber = material.weightReturnNumber;
  44738. attributeMaterial.weightSourceID = material.weightSourceID;
  44739. attributeMaterial.color = material.color;
  44740. attributeMaterial.clipTask = material.clipTask;
  44741. attributeMaterial.clipMethod = material.clipMethod;
  44742. attributeMaterial.setClipBoxes(material.clipBoxes);
  44743. attributeMaterial.setClipPolygons(material.clipPolygons);
  44744. pointcloud.material = attributeMaterial;
  44745. }
  44746. let gl = this.gl;
  44747. viewer.renderer.setRenderTarget(null);
  44748. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, {
  44749. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume$1)),
  44750. //material: this.attributeMaterial,
  44751. blendFunc: [gl.SRC_ALPHA, gl.ONE],
  44752. //depthTest: false,
  44753. depthWrite: false
  44754. });
  44755. }
  44756. for(let [pointcloud, material] of originalMaterials){
  44757. pointcloud.material = material;
  44758. }
  44759. viewer.renderer.setRenderTarget(null);
  44760. if(viewer.background === "skybox"){
  44761. viewer.renderer.setClearColor(0x000000, 0);
  44762. viewer.renderer.clear();
  44763. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  44764. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  44765. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  44766. viewer.skybox.parent.rotation.x = 0;
  44767. viewer.skybox.parent.updateMatrixWorld();
  44768. viewer.skybox.camera.updateProjectionMatrix();
  44769. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  44770. } else if (viewer.background === 'gradient') {
  44771. viewer.renderer.setClearColor(0x000000, 0);
  44772. viewer.renderer.clear();
  44773. viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  44774. } else if (viewer.background === 'black') {
  44775. viewer.renderer.setClearColor(0x000000, 1);
  44776. viewer.renderer.clear();
  44777. } else if (viewer.background === 'white') {
  44778. viewer.renderer.setClearColor(0xFFFFFF, 1);
  44779. viewer.renderer.clear();
  44780. } else {
  44781. viewer.renderer.setClearColor(0x000000, 0);
  44782. viewer.renderer.clear();
  44783. }
  44784. { // NORMALIZATION PASS
  44785. let normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial;
  44786. if(this.useEDL){
  44787. normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength;
  44788. normalizationMaterial.uniforms.radius.value = viewer.edlRadius;
  44789. normalizationMaterial.uniforms.screenWidth.value = width;
  44790. normalizationMaterial.uniforms.screenHeight.value = height;
  44791. normalizationMaterial.uniforms.uEDLMap.value = this.rtDepth.texture;
  44792. }
  44793. normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture;
  44794. normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture;
  44795. Utils.screenPass.render(viewer.renderer, normalizationMaterial);
  44796. }
  44797. viewer.renderer.render(viewer.scene.scene, camera);
  44798. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  44799. viewer.renderer.clearDepth();
  44800. viewer.transformationTool.update();
  44801. viewer.dispatchEvent({type: "render.pass.perspective_overlay",viewer: viewer});
  44802. viewer.renderer.render(viewer.controls.sceneControls, camera);
  44803. viewer.renderer.render(viewer.clippingTool.sceneVolume, camera);
  44804. viewer.renderer.render(viewer.transformationTool.scene, camera);
  44805. viewer.renderer.setViewport(width - viewer.navigationCube.width,
  44806. height - viewer.navigationCube.width,
  44807. viewer.navigationCube.width, viewer.navigationCube.width);
  44808. viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  44809. viewer.renderer.setViewport(0, 0, width, height);
  44810. viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  44811. }
  44812. }
  44813. class LRUItem{
  44814. constructor(node){
  44815. this.previous = null;
  44816. this.next = null;
  44817. this.node = node;
  44818. }
  44819. }
  44820. /**
  44821. *
  44822. * @class A doubly-linked-list of the least recently used elements.
  44823. */
  44824. class LRU{
  44825. constructor(){ //类似链表存储
  44826. // the least recently used item
  44827. this.first = null;
  44828. // the most recently used item
  44829. this.last = null;
  44830. // a list of all items in the lru list
  44831. this.items = {}; //按node的id存储。(id为0的就是root,name='r')
  44832. this.elements = 0;
  44833. this.numPoints = 0;
  44834. }
  44835. size(){
  44836. return this.elements;
  44837. }
  44838. contains(node){
  44839. return this.items[node.id] == null;
  44840. }
  44841. touch(node){//链接node,并且永远放在最后. (每次updatePointClouds都要刷新一次链表)
  44842. if (!node.loaded) {
  44843. return;
  44844. }
  44845. let item;
  44846. if (this.items[node.id] == null) {
  44847. // add to list
  44848. item = new LRUItem(node);
  44849. item.previous = this.last;
  44850. this.last = item;
  44851. if (item.previous !== null) {
  44852. item.previous.next = item;
  44853. }
  44854. this.items[node.id] = item;
  44855. this.elements++;
  44856. if (this.first === null) {
  44857. this.first = item;
  44858. }
  44859. this.numPoints += node.numPoints;
  44860. } else {
  44861. // update in list
  44862. item = this.items[node.id];
  44863. if (item.previous === null) {
  44864. // handle touch on first element
  44865. if (item.next !== null) {
  44866. this.first = item.next;
  44867. this.first.previous = null;
  44868. item.previous = this.last;
  44869. item.next = null;
  44870. this.last = item;
  44871. item.previous.next = item;
  44872. }
  44873. } else if (item.next === null) {
  44874. // handle touch on last element
  44875. } else {//从原来的位置挑出放最后
  44876. // handle touch on any other element
  44877. item.previous.next = item.next;
  44878. item.next.previous = item.previous;
  44879. item.previous = this.last;
  44880. item.next = null;
  44881. this.last = item;
  44882. item.previous.next = item;
  44883. }
  44884. }
  44885. }
  44886. //因为需要显示的都放末尾,所以不显示的部分都在前面,删除时从头删除。(但并不代表开头的一定是不显示的,所以如果第一个仍是显示的,它很可能是root,也就是name='r'的nodeGeo,删除它也就会删除全部)
  44887. remove(node){
  44888. let lruItem = this.items[node.id];
  44889. if (lruItem) {
  44890. if (this.elements === 1) {
  44891. this.first = null;
  44892. this.last = null;
  44893. } else {
  44894. if (!lruItem.previous) {
  44895. this.first = lruItem.next;
  44896. this.first.previous = null;
  44897. }
  44898. if (!lruItem.next) {
  44899. this.last = lruItem.previous;
  44900. this.last.next = null;
  44901. }
  44902. if (lruItem.previous && lruItem.next) {
  44903. lruItem.previous.next = lruItem.next;
  44904. lruItem.next.previous = lruItem.previous;
  44905. }
  44906. }
  44907. delete this.items[node.id];
  44908. this.elements--;
  44909. this.numPoints -= node.numPoints;
  44910. }
  44911. }
  44912. getLRUItem(){
  44913. if (this.first === null) {
  44914. return null;
  44915. }
  44916. let lru = this.first;
  44917. return lru.node;
  44918. }
  44919. toString(){
  44920. let string = '{ ';
  44921. let curr = this.first;
  44922. while (curr !== null) {
  44923. string += curr.node.id;
  44924. if (curr.next !== null) {
  44925. string += ', ';
  44926. }
  44927. curr = curr.next;
  44928. }
  44929. string += '}';
  44930. string += '(' + this.size() + ')';
  44931. return string;
  44932. }
  44933. freeMemory(){
  44934. if (this.elements <= 1) {
  44935. return;
  44936. }
  44937. while (this.numPoints > Potree.pointLoadLimit) {
  44938. let element = this.first;
  44939. let node = element.node;
  44940. this.disposeDescendants(node);
  44941. }
  44942. }
  44943. disposeDescendants(node){
  44944. let stack = [];
  44945. stack.push(node);
  44946. while (stack.length > 0) {
  44947. let current = stack.pop();
  44948. // console.log(current);
  44949. current.dispose(); //真正删除geometry等
  44950. this.remove(current);
  44951. for (let key in current.children) {
  44952. if (current.children.hasOwnProperty(key)) {
  44953. let child = current.children[key];
  44954. if (child.loaded) {
  44955. stack.push(current.children[key]);
  44956. }
  44957. }
  44958. }
  44959. }
  44960. }
  44961. }
  44962. //
  44963. // how to calculate the radius of a projected sphere in screen space
  44964. // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
  44965. // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere
  44966. //
  44967. class ExtendPointCloudMaterial extends PointCloudMaterial$1 {
  44968. constructor (parameters = {}) {
  44969. super(parameters);
  44970. let getValid = (a, b) => {
  44971. if(a !== undefined){
  44972. return a;
  44973. }else {
  44974. return b;
  44975. }
  44976. };
  44977. let maxSize = getValid(parameters.maxSize, 1550.0);
  44978. this._gradient = Gradients.RAINBOW;//Gradients.SPECTRAL;//海拔贴图种类
  44979. this.gradientTexture = ExtendPointCloudMaterial.generateGradientTexture(this._gradient);
  44980. //this.matcapTexture = ExtendPointCloudMaterial.generateMatcapTexture(this._matcap);
  44981. delete this.uniforms.screenWidth;
  44982. delete this.uniforms.screenHeight;
  44983. delete this.uniforms.clipBoxes;
  44984. delete this.uniforms.clipPolygons;
  44985. delete this.uniforms.clipPolygonVCount;
  44986. delete this.uniforms.clipPolygonVP;
  44987. delete this.uniforms.clipBoxCount;
  44988. //注意:这里修改了uniforms后,还需要在PotreeRender中手动传递到shader, like: gl.uniformMatrix4fv(....
  44989. Object.assign(this.uniforms,{
  44990. resolution: { type: 'v2', value: new Vector2() },
  44991. maxSize: { type: "f", value: maxSize },
  44992. gradient: { type: "t", value: this.gradientTexture },
  44993. clipBoxes_in: { type: "Matrix4fv", value: [] },
  44994. clipBoxes_out: { type: "Matrix4fv", value: [] },
  44995. clipBoxBig_in: { type: "Matrix4fv", value: [] },
  44996. boxes_highlight: { type: "Matrix4fv", value: [] },
  44997. progress: {
  44998. type: "f",
  44999. value: 0
  45000. },
  45001. easeInOutRatio:{
  45002. type: "f",
  45003. value: 0.3
  45004. },
  45005. pano0Map: {
  45006. type: "t",
  45007. value: null
  45008. },
  45009. pano0Position: {
  45010. type: "v3",
  45011. value: new Vector3
  45012. },
  45013. pano0Matrix: {
  45014. type: "m4",
  45015. value: new Matrix4
  45016. },
  45017. pano1Map: {
  45018. type: "t",
  45019. value: null
  45020. },
  45021. pano1Position: {
  45022. type: "v3",
  45023. value: new Vector3
  45024. },
  45025. pano1Matrix: {
  45026. type: "m4",
  45027. value: new Matrix4
  45028. },
  45029. });
  45030. delete this.clipBoxes;
  45031. this.clipBoxes_in = [];
  45032. this.clipBoxes_out = [];
  45033. this.highlightBoxes = [];
  45034. this.updateShaderSource();
  45035. }
  45036. updateShaderSource () {
  45037. let vs = Shaders['pointcloud_new.vs']; //改
  45038. let fs = Shaders['pointcloud_new.fs']; //改
  45039. let definesString = this.getDefines();
  45040. let vsVersionIndex = vs.indexOf("#version ");
  45041. let fsVersionIndex = fs.indexOf("#version ");
  45042. if(vsVersionIndex >= 0){
  45043. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  45044. }else {
  45045. vs = `${definesString}\n${vs}`;
  45046. }
  45047. if(fsVersionIndex >= 0){
  45048. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  45049. }else {
  45050. fs = `${definesString}\n${fs}`;
  45051. }
  45052. this.vertexShader = vs;
  45053. this.fragmentShader = fs;
  45054. if (this.opacity === 1.0 && !this.useFilterByNormal) {//add useFilterByNormal
  45055. this.blending = NoBlending;
  45056. this.transparent = false;
  45057. this.depthTest = true;
  45058. this.depthWrite = true;
  45059. this.depthFunc = LessEqualDepth;
  45060. } else if ( (this.opacity < 1.0 ||this.useFilterByNormal) && !this.useEDL) {//add useFilterByNormal
  45061. this.blending = AdditiveBlending;
  45062. this.transparent = true;
  45063. this.depthTest = false;
  45064. this.depthWrite = true;
  45065. this.depthFunc = AlwaysDepth;
  45066. }
  45067. if (this.weighted) {
  45068. this.blending = AdditiveBlending;
  45069. this.transparent = true;
  45070. this.depthTest = true;
  45071. this.depthWrite = false;
  45072. }
  45073. this.shaderNeedsUpdate = true;
  45074. }
  45075. getDefines () {
  45076. let defines = [];
  45077. if (this.pointSizeType === PointSizeType.FIXED) {
  45078. defines.push('#define fixed_point_size');
  45079. } else if (this.pointSizeType === PointSizeType.ATTENUATED) {
  45080. defines.push('#define attenuated_point_size');
  45081. } else if (this.pointSizeType === PointSizeType.ADAPTIVE) {
  45082. defines.push('#define adaptive_point_size');
  45083. }
  45084. if(!Features.EXT_DEPTH.isSupported() && this.shape === PointShape$1.PARABOLOID){
  45085. this.shape = PointShape$1.SQUARE ;//强行替换
  45086. }
  45087. if (this.shape === PointShape$1.SQUARE) {
  45088. defines.push('#define square_point_shape');
  45089. } else if (this.shape === PointShape$1.CIRCLE) {
  45090. defines.push('#define circle_point_shape');
  45091. } else if (this.shape === PointShape$1.PARABOLOID) {
  45092. defines.push('#define paraboloid_point_shape');
  45093. }
  45094. //console.log('this.shape PARABOLOID', this.shape, this.shape === PointShape.PARABOLOID)
  45095. if (this._useEDL || this.fakeEDL) {
  45096. defines.push('#define use_edl');
  45097. }
  45098. if(this.activeAttributeName){
  45099. let attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_');
  45100. defines.push(`#define color_type_${attributeName}`);
  45101. }
  45102. if(this._treeType === TreeType.OCTREE){
  45103. defines.push('#define tree_type_octree');
  45104. }else if(this._treeType === TreeType.KDTREE){
  45105. defines.push('#define tree_type_kdtree');
  45106. }
  45107. if (this.weighted) {
  45108. defines.push('#define weighted_splats');
  45109. }
  45110. for(let [key, value] of this.defines){
  45111. defines.push(value);
  45112. }
  45113. return defines.join("\n");
  45114. }
  45115. get pointSizeType () {
  45116. return this._pointSizeType;
  45117. }
  45118. set pointSizeType (value) {
  45119. if(typeof value == 'string' )value = PointSizeType[value];
  45120. super.pointSizeType = value;
  45121. /* if (this._pointSizeType !== value) {
  45122. this._pointSizeType = value;
  45123. this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿
  45124. this.dispatchEvent({
  45125. type: 'point_size_type_changed',
  45126. target: this
  45127. });
  45128. this.dispatchEvent({
  45129. type: 'material_property_changed',
  45130. target: this
  45131. });
  45132. } */
  45133. }
  45134. get color () {
  45135. return this.uniforms.uColor.value;
  45136. }
  45137. set color (value) {//改
  45138. if(value == this.color_)return
  45139. let color = value;
  45140. //if (!this.uniforms.uColor.value.equals(value)) {
  45141. if(typeof value == 'string') {
  45142. var colorArr = Potree.config.colors[value];
  45143. if(!colorArr){
  45144. //console.warn('没找到该颜色值'+ value)
  45145. }else {
  45146. color = new Color().fromArray(colorArr).multiplyScalar(1/255);
  45147. }
  45148. }
  45149. this.uniforms.uColor.value.set(color);
  45150. //this.uniforms.uColor.value.copy(value);
  45151. this.dispatchEvent({
  45152. type: 'color_changed',
  45153. target: this
  45154. });
  45155. this.dispatchEvent({
  45156. type: 'material_property_changed',
  45157. target: this
  45158. });
  45159. //}
  45160. this.color_ = value; //记录下str
  45161. }
  45162. ////////////////////////add
  45163. setProjectedPanos(pano0, pano1, progressValue, easeInOutRatio){
  45164. //this.uniforms.usePanoMap.value = 1
  45165. this.usePanoMap = true;
  45166. progressValue!=void 0 && (this.uniforms.progress.value = progressValue);
  45167. //pano0.ensureSkyboxReadyForRender();
  45168. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();
  45169. this.uniforms.pano0Position.value.copy(pano0.position);
  45170. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix );
  45171. //pano1.ensureSkyboxReadyForRender();
  45172. this.uniforms.easeInOutRatio.value = easeInOutRatio || 0; //之前做点云和全景混合时加的,为了让点云颜色柔和切换到全景颜色。如不混合就0
  45173. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();
  45174. this.uniforms.pano1Position.value.copy(pano1.position);
  45175. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix );
  45176. //this.updateShaderSource()
  45177. //this.needsUpdate = true;
  45178. }
  45179. stopProjectedPanos(){
  45180. //this.uniforms.usePanoMap.value = 0
  45181. this.usePanoMap = false;
  45182. }
  45183. setClipBoxes (bigClipInBox, clipBoxes_in,clipBoxes_out, highlightBoxes) {
  45184. if (!clipBoxes_in || !clipBoxes_out) {
  45185. return;
  45186. }
  45187. let doUpdate = (this.clipBoxes_in.length !== clipBoxes_in.length) || (this.clipBoxes_out.length != clipBoxes_out.length)
  45188. || this.highlightBoxes.length !== highlightBoxes.length || this.bigClipInBox != bigClipInBox;
  45189. //this.clipBoxes = clipBoxes;
  45190. if (doUpdate) {
  45191. this.shaderNeedsUpdate = true;//this.updateShaderSource();
  45192. viewer.dispatchEvent('content_changed');
  45193. }
  45194. this.bigClipInBox = bigClipInBox;
  45195. this.clipBoxes_in = clipBoxes_in;
  45196. this.clipBoxes_out = clipBoxes_out;
  45197. this.highlightBoxes = highlightBoxes;
  45198. this.uniforms.clipBoxBig_in.value = bigClipInBox && bigClipInBox.inverse;
  45199. this.uniforms.clipBoxes_in.value = new Float32Array(this.clipBoxes_in.length * 16);
  45200. this.uniforms.clipBoxes_out.value = new Float32Array(this.clipBoxes_out.length * 16);
  45201. this.uniforms.boxes_highlight.value = new Float32Array(this.highlightBoxes.length * 16);
  45202. for (let i = 0; i < this.clipBoxes_in.length; i++) {
  45203. let box = clipBoxes_in[i];
  45204. this.uniforms.clipBoxes_in.value.set(box.inverse.elements, 16 * i);
  45205. }
  45206. for (let i = 0; i < this.clipBoxes_out.length; i++) {
  45207. let box = clipBoxes_out[i];
  45208. this.uniforms.clipBoxes_out.value.set(box.inverse.elements, 16 * i);
  45209. }
  45210. for (let i = 0; i < this.highlightBoxes.length; i++) {
  45211. let box = highlightBoxes[i];
  45212. this.uniforms.boxes_highlight.value.set(box.inverse.elements, 16 * i);
  45213. }
  45214. /* for (let i = 0; i < this.uniforms.clipBoxes.value.length; i++) {??
  45215. if (Number.isNaN(this.uniforms.clipBoxes.value[i])) {
  45216. this.uniforms.clipBoxes.value[i] = Infinity;
  45217. }
  45218. } */
  45219. }
  45220. }
  45221. var defaultColor = new Color(1,1,1);//config.applicationName == "zhiHouse" ? Colors.zhiBlue : Colors.lightGreen;
  45222. function dealPosArr(points){//识别是否每个点都不一样,把连续点变为不连续的片段连接
  45223. if(points.length > 2 && !points[2].equals(points[1])){
  45224. let points2 = [] , len = points.length;
  45225. for(let i=0;i<len-1;i++){
  45226. points2.push(points[i], points[i+1]);
  45227. }
  45228. return points2
  45229. }else return points
  45230. }
  45231. var LineDraw = {
  45232. createLine: function (posArr, o={}) {
  45233. //多段普通线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序)
  45234. var mat;
  45235. if(o.mat){
  45236. mat = o.mat;
  45237. }else {
  45238. let prop = Object.assign({
  45239. lineWidth: o.lineWidth || 1,
  45240. //windows无效。 似乎mac/ios上粗细有效 ?
  45241. color: o.color || defaultColor
  45242. },o);
  45243. if(o.deshed ){
  45244. prop.dashSize = o.dashSize || 0.1,
  45245. prop.gapSize = o.gapSize || 0.1;
  45246. }
  45247. mat = new THREE$1[o.deshed ? "LineDashedMaterial" : "LineBasicMaterial"](prop);
  45248. }
  45249. var line = new LineSegments(new BufferGeometry, mat);
  45250. line.renderOrder = o.renderOrder || 4;
  45251. this.moveLine(line, posArr);
  45252. return line;
  45253. },
  45254. moveLine: function (line, posArr) {
  45255. if(posArr.length == 0)return
  45256. if(!line.uncontinuous)posArr = dealPosArr(posArr);
  45257. let position = [];
  45258. posArr.forEach(e=>position.push(e.x,e.y,e.z));
  45259. line.geometry.setAttribute('position', new Float32BufferAttribute(/* new Float32Array( */position/* ) */, 3));
  45260. line.geometry.attributes.position.needsUpdate = true;
  45261. line.geometry.computeBoundingSphere();
  45262. if(line.material instanceof LineDashedMaterial){
  45263. line.computeLineDistances();
  45264. //line.geometry.attributes.lineDistance.needsUpdate = true;
  45265. line.geometry.verticesNeedUpdate = true; //没用
  45266. }
  45267. }
  45268. ,
  45269. createFatLineMat : function(o){
  45270. var supportExtDepth = !!Features.EXT_DEPTH.isSupported();
  45271. let params = $.extend({}, {
  45272. //默认
  45273. lineWidth : 5,
  45274. color:0xffffff,
  45275. transparent : true, depthWrite:false, depthTest:false,
  45276. dashSize : 0.1, gapSize:0.1,
  45277. }, o, {
  45278. //修正覆盖:
  45279. dashed: o.dashWithDepth ? supportExtDepth && !!o.dashed : !!o.dashed ,
  45280. dashWithDepth:!!o.dashWithDepth,//只在被遮住的部分显示虚线
  45281. useDepth: !!o.useDepth,
  45282. supportExtDepth,
  45283. });
  45284. var mat = new LineMaterial(params);
  45285. //if(o.dashed)(mat.defines.USE_DASH = "")
  45286. return mat;
  45287. },
  45288. /*
  45289. 创建可以改变粗细的线。
  45290. */
  45291. createFatLine : function(posArr, o){
  45292. var geometry = new LineGeometry();
  45293. geometry.setColors( o.color || [1,1,1]);
  45294. var matLine = o.mat || this.createFatLineMat(o);
  45295. var line = new Line2( geometry, matLine );
  45296. //line.computeLineDistances();
  45297. line.uncontinuous = o.uncontinuous; //线不连续,由线段组成
  45298. line.scale.set( 1, 1, 1 );
  45299. line.renderOrder = 2;
  45300. this.moveFatLine(line, posArr);
  45301. return line;
  45302. },
  45303. moveFatLine: function(line, posArr){
  45304. var geometry = line.geometry;
  45305. var positions = [];
  45306. line.uncontinuous || (posArr = dealPosArr(posArr));
  45307. posArr.forEach(e=>{positions.push(...e.toArray());});
  45308. if(!geometry){
  45309. geometry = line.geometry = new LineGeometry();
  45310. }
  45311. if(geometry.attributes.instanceEnd && geometry.attributes.instanceEnd.data.array.length != positions.length){//positions个数改变会有部分显示不出来,所以重建
  45312. geometry.dispose();
  45313. geometry = new LineGeometry();
  45314. line.geometry = geometry;
  45315. }
  45316. geometry.setPositions( positions );
  45317. if(line.material.defines.USE_DASH != void 0){
  45318. //line.geometry.verticesNeedUpdate = true; //没用
  45319. line.geometry.computeBoundingSphere(); //for raycaster
  45320. line.computeLineDistances();
  45321. }
  45322. },
  45323. updateLine: function(line, posArr){
  45324. if(line instanceof Line2){
  45325. LineDraw.moveFatLine(line,posArr);
  45326. }else {
  45327. LineDraw.moveLine(line,posArr);
  45328. }
  45329. },
  45330. /*
  45331. 为line创建用于检测鼠标的透明mesh,实际是个1-2段圆台。
  45332. 由于近大远小的原因,假设没有透视畸变、创建的是等粗的圆柱的话, 所看到的线上每个位置的粗细应该和距离成反比。所以将圆柱改为根据距离线性渐变其截面半径的圆台,在最近点(相机到线的垂足)最细。如果最近点在线段上,则分成两段圆台,否则一段。
  45333. */
  45334. createBoldLine:function(points, o){
  45335. o = o || {};
  45336. var cylinder = o && o.cylinder;
  45337. var CD = points[1].clone().sub(points[0]);
  45338. var rotate = function(){//根据端点旋转好模型
  45339. cylinder.lastVector = CD;//记录本次的端点向量
  45340. var AB = new Vector3(0,-1,0);
  45341. var axisVec = AB.clone().cross(CD).normalize(); //得到垂直于它们的向量,也就是旋转轴
  45342. var rotationAngle = AB.angleTo(CD);
  45343. cylinder.quaternion.setFromAxisAngle( axisVec, rotationAngle );
  45344. };
  45345. if(o && o.type == "init"){
  45346. cylinder = new Mesh();
  45347. cylinder.material = o.mat;
  45348. if(CD.length() == 0)return cylinder;
  45349. rotate();
  45350. }
  45351. if(CD.length() == 0)return cylinder;
  45352. if(o.type != "update"){
  45353. var CDcenter = points[0].clone().add(points[1]).multiplyScalar(.5);
  45354. cylinder.position.copy(CDcenter);
  45355. if(!cylinder.lastVector || o.type == "moveAndRotate")rotate();
  45356. else if(cylinder.lastVector && CD.angleTo(cylinder.lastVector)>0) rotate();//线方向改了or线反向了 重新旋转一下模型
  45357. if(config.isEdit && !objects.mainDesign.editing )return cylinder;//节省初始加载时间?
  45358. }
  45359. //为了保证线段任何地方的可检测点击范围看起来一样大,更新圆台的结构(但是在镜头边缘会比中心看起来大)
  45360. var height = points[0].distanceTo(points[1]);
  45361. var standPos = o && o.standPos || objects.player.position;
  45362. var k = config.isMobile ? 20 : 40;
  45363. var dis1 = points[0].distanceTo(standPos);
  45364. var dis2 = points[1].distanceTo(standPos);
  45365. var foot = math.getFootPoint(standPos, points[0], points[1]);//垂足
  45366. if(o.constantBold || objects.player.mode != "panorama"){
  45367. var width = 0.1;//0.08;
  45368. var pts = [new Vector2(width ,height/2),new Vector2(width ,-height/2)];
  45369. }else if(foot.clone().sub(points[0]).dot( foot.clone().sub(points[1]) ) > 0){//foot不在线段上
  45370. var pts = [new Vector2(dis1 / k,height/2),new Vector2(dis2 / k,-height/2)];
  45371. }else {//在线段上的话,要在垂足这加一个节点,因它距离站位最近,而两端较远
  45372. var dis3 = foot.distanceTo(standPos);
  45373. var len = foot.distanceTo(points[0]);
  45374. var pts = [new Vector2(dis1 / k,height/2), new Vector2(dis3 / k,height/2-len), new Vector2(dis2 / k,-height/2)];
  45375. }
  45376. cylinder.geometry && cylinder.geometry.dispose();//若不删除会占用内存
  45377. cylinder.geometry = new LatheBufferGeometry( pts, 4/* Math.min(dis1,dis2)<10?4:3 */ );
  45378. cylinder.renderOrder = 2;
  45379. return cylinder;
  45380. },
  45381. updateBoldLine:function(cylinder, points, type, standPos, constantBold){
  45382. this.createBoldLine(points,{type:type, cylinder : cylinder, standPos:standPos, constantBold}); //type:move:平移 会改长短 , type:update根据距离和角度更新 不改长短
  45383. },
  45384. };
  45385. var MeshDraw = {
  45386. getShape:function(points, holes){
  45387. var shape = new Shape();
  45388. shape.moveTo( points[0].x, points[0].y );
  45389. for(var i=1,len=points.length; i<len; i++){
  45390. shape.lineTo(points[i].x, points[i].y );
  45391. }
  45392. /* var holePath = new THREE.Path()
  45393. .moveTo( 20, 10 )
  45394. .absarc( 10, 10, 10, 0, Math.PI * 2, true )
  45395. arcShape.holes.push( holePath );
  45396. */
  45397. if(holes){//挖空
  45398. holes.forEach((points)=>{
  45399. var holePath = new Path();
  45400. holePath.moveTo( points[0].x, points[0].y );
  45401. for(var i=1,len=points.length; i<len; i++){
  45402. holePath.lineTo(points[i].x, points[i].y );
  45403. }
  45404. shape.holes.push( holePath );
  45405. });
  45406. }
  45407. return shape
  45408. },
  45409. getShapeGeo: function(points, holes){//获取任意形状(多边形或弧形)的形状面 //quadraticCurveTo() 这是弧形的含函数
  45410. var geometry = new ShapeBufferGeometry( this.getShape(points, holes) ); //ShapeGeometry
  45411. /* var matrix = new THREE.Matrix4();//将竖直的面变为水平
  45412. matrix.set(//z = y
  45413. 1, 0, 0, 0,
  45414. 0, 0, 0, 0,
  45415. 0, 1, 0, 0,
  45416. 0, 0, 0, 1
  45417. )
  45418. geometry.applyMatrix(matrix) */
  45419. //geometry.computeVertexNormals();//对于光照需要的是点法线
  45420. return geometry;
  45421. },
  45422. getExtrudeGeo: function(points, holes, options={}){//获得挤出棱柱,可以选择传递height,或者extrudePath
  45423. var shape = this.getShape(points, holes); //points是横截面 [vector2,...]
  45424. if(options.extrudePath ){// 路径 :[vector3,...]
  45425. var length = extrudePath.reduce((total, currentValue, currentIndex, arr)=>{
  45426. if(currentIndex == 0)return 0
  45427. return total + currentValue.distanceTo(arr[currentIndex-1]);
  45428. },0);
  45429. options.extrudePath = new CatmullRomCurve3(extrudePath, options.closed , 'catmullrom' /* 'centripetal' */ , options.tension);
  45430. }
  45431. var extrudeSettings = $.extend(options,{
  45432. steps: options.steps != void 0 ? options.steps : ( options.extrudePath ? Math.round(length/0.3) : 1),
  45433. bevelEnabled: false, //不加的话,height为0时会有圆弧高度
  45434. //depth
  45435. });
  45436. var geometry = new ExtrudeBufferGeometry( shape, extrudeSettings );
  45437. return geometry;
  45438. },
  45439. getUnPosPlaneGeo : function(){//获取还没有赋值位置的plane geometry
  45440. var e = new Uint16Array([0, 1, 2, 0, 2, 3])
  45441. // , t = new Float32Array([-.5, -.5, 0, .5, -.5, 0, .5, .5, 0, -.5, .5, 0])
  45442. , i = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1])
  45443. , g = new BufferGeometry;
  45444. g.setIndex(new BufferAttribute(e, 1)),
  45445. //g.addAttribute("position", new n.BufferAttribute(t, 3)),
  45446. g.setAttribute("uv", new BufferAttribute(i, 2));
  45447. return function(){
  45448. return g
  45449. }
  45450. }(),
  45451. getPlaneGeo : function(A,B,C,D){
  45452. var geo = this.getUnPosPlaneGeo().clone();
  45453. var pos = [
  45454. A.x, A.y, A.z,
  45455. B.x, B.y, B.z,
  45456. C.x, C.y, C.z,
  45457. D.x, D.y, D.z
  45458. ];
  45459. //geo.addAttribute("position", new THREE.BufferAttribute(pos, 3))
  45460. geo.setAttribute('position', new Float32BufferAttribute(pos, 3));
  45461. geo.computeVertexNormals();
  45462. geo.computeBoundingSphere(); //for raycaster
  45463. return geo;
  45464. },
  45465. drawPlane : function(A,B,C,D, material){
  45466. var wall = new Mesh(this.getPlaneGeo(A,B,C,D), material);
  45467. return wall;
  45468. },
  45469. movePlane: function(mesh, A,B,C,D){
  45470. var pos = new Float32Array([
  45471. A.x, A.y, A.z,
  45472. B.x, B.y, B.z,
  45473. C.x, C.y, C.z,
  45474. D.x, D.y, D.z
  45475. ]);
  45476. mesh.geometry.addAttribute("position", new BufferAttribute(pos, 3));
  45477. mesh.geometry.computeBoundingSphere();//for checkIntersect
  45478. }
  45479. ,
  45480. createGeometry:function(posArr, faceArr, uvArr, normalArr ){//创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  45481. let geo = new BufferGeometry;
  45482. let positions = [];
  45483. posArr.forEach(p=>positions.push(p.x,p.y,p.z));
  45484. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  45485. if(faceArr){
  45486. let indice = [];
  45487. faceArr.forEach(f=>indice.push(...f));
  45488. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  45489. }
  45490. if(uvArr){
  45491. let uvs = [];
  45492. uvArr.forEach(uv=>uvs.push(uv.x,uv.y));
  45493. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  45494. }
  45495. if(normalArr){
  45496. let normals = [];
  45497. normalArr.forEach(n=>normals.push(n.x,n.y,n.z));
  45498. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  45499. }
  45500. /*
  45501. geo.computeVertexNormals()
  45502. geo.computeBoundingSphere() //for raycaster
  45503. */
  45504. return geo
  45505. },
  45506. updateGeometry:function(geo, posArr, faceArr, uvArr, normalArr ){//创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  45507. let positions = [];
  45508. posArr.forEach(p=>positions.push(p.x,p.y,p.z));
  45509. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  45510. geo.attributes.position.needsUpdate = true;
  45511. if(faceArr){
  45512. let indice = [];
  45513. faceArr.forEach(f=>indice.push(...f));
  45514. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  45515. }
  45516. if(uvArr){
  45517. let uvs = [];
  45518. uvArr.forEach(uv=>uvs.push(uv.x,uv.y));
  45519. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  45520. }
  45521. if(normalArr){
  45522. let normals = [];
  45523. normalArr.forEach(n=>normals.push(n.x,n.y,n.z));
  45524. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  45525. }
  45526. /*
  45527. geo.computeVertexNormals()
  45528. */
  45529. geo.computeBoundingSphere(); //for raycaster and visi
  45530. return geo
  45531. }
  45532. };
  45533. class DepthBasicMaterial extends ShaderMaterial{
  45534. constructor(o={}){
  45535. let {width, height} = viewer.renderer.getSize(new Vector2());
  45536. let uniforms = {
  45537. resolution: { type: 'v2', value: new Vector2(width, height ) },
  45538. viewportOffset: { type: 'v2', value: new Vector2(0, 0 ) }, //left, top
  45539. //uUseOrthographicCamera:{ type: "b", value: false },
  45540. nearPlane: { type: 'f', value: 0.1 },
  45541. farPlane: { type: 'f', value: 10000 },
  45542. depthTexture: { type: 't', value: null },
  45543. opacity: { type: 'f', value: 1 },
  45544. map: { type: 't', value: o.map },
  45545. baseColor: {type:'v3', value: o.color ? new Color(o.color) : new Color("#ffffff")},
  45546. backColor: {type:'v3', value: o.backColor ? new Color(o.backColor) : new Color("#ddd")},
  45547. clipDistance : { type: 'f', value: o.clipDistance || 4 }, //消失距离
  45548. occlusionDistance : { type: 'f', value: o.occlusionDistance || 1 }, //变为backColor距离
  45549. maxClipFactor : { type: 'f', value: o.maxClipFactor || 1 }, //0-1
  45550. maxOcclusionFactor : { type: 'f', value: o.maxOcclusionFactor || 1 }, //0-1
  45551. mapScale: { type: 'f', value: o.mapScale || 1 }, //0-1
  45552. };
  45553. super({
  45554. uniforms,
  45555. vertexShader: Shaders['depthBasic.vs'],
  45556. fragmentShader: Shaders['depthBasic.fs'],
  45557. depthWrite: false,
  45558. depthTest: false,
  45559. transparent: o.transparent == void 0 ? true : o.transparent,
  45560. side: o.side || 0 /* THREE.DoubleSide */,
  45561. });
  45562. this.events = {
  45563. setSize:(e)=>{//如果出现横条状的异常,往往是viewportOffset出错 //地图不需要
  45564. if(!this.realUseDepth || !e.viewport)return
  45565. let viewport = e.viewport;
  45566. let viewportOffset = viewport.offset || new Vector2();
  45567. this.uniforms.resolution.value.copy(viewport.resolution2); //2023.6.12突然发现ratio>1的用resolution不对,得用2才对。但是之前明明记得不是这样
  45568. this.uniforms.viewportOffset.value.copy(viewportOffset);
  45569. },
  45570. render:(e)=>{//before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  45571. this.updateDepthParams(e);
  45572. },
  45573. /* cameraChange:(e)=>{
  45574. if(e.changeInfo.projectionChanged){//resize时也会触发。虽然保守起见的话加上resize比较好//所以当时为何不用resize
  45575. //console.log('projectionChanged')
  45576. this.events.setSize(e)
  45577. }
  45578. } */
  45579. };
  45580. //-----其他----
  45581. this.autoDepthTest = o.autoDepthTest;
  45582. if(o.opacity != void 0){
  45583. this.opacity = o.opacity;
  45584. }
  45585. this.useDepth = o.useDepth;
  45586. this.map = o.map;
  45587. }
  45588. get useDepth(){
  45589. return this.useDepth_
  45590. }
  45591. set useDepth(value){
  45592. value = value && Features.EXT_DEPTH.isSupported(); //如果不支持 EXT_DEPTH 的话会失效
  45593. if(this.useDepth_ != value){
  45594. this.setRealDepth(value);
  45595. this.useDepth_ = value;
  45596. if(value){
  45597. viewer.addEventListener("render.begin", this.events.render);
  45598. //viewer.addEventListener('camera_changed', this.events.cameraChange)
  45599. viewer.addEventListener('resize', this.events.setSize);
  45600. this.updateDepthParams();
  45601. }else {
  45602. viewer.removeEventListener("render.begin", this.events.render);
  45603. viewer.removeEventListener('resize', this.events.setSize);
  45604. }
  45605. }
  45606. }
  45607. setRealDepth(useDepth, viewport){//确实使用到depthTex
  45608. if(this.realUseDepth != useDepth){
  45609. if(useDepth ){
  45610. this.defines.useDepth = '';
  45611. }else {
  45612. delete this.defines.useDepth;
  45613. }
  45614. this.realUseDepth = useDepth;
  45615. if(this.autoDepthTest)this.depthWrite = this.depthTest = !useDepth; //如果useDepth = false,使用原始的depthTest
  45616. this.needsUpdate = true;
  45617. if(!viewport)viewport = viewer.mainViewport; //暂时这么设置
  45618. useDepth && this.events.setSize({viewport});
  45619. }
  45620. }
  45621. get map(){
  45622. return this.uniforms.map.value
  45623. }
  45624. set map(map){
  45625. this.uniforms.map.value = map;
  45626. if(map){
  45627. this.defines.use_map = '';
  45628. }else {
  45629. delete this.defines.use_map;
  45630. }
  45631. }
  45632. get opacity(){
  45633. return this.uniforms.opacity.value
  45634. }
  45635. set opacity(o){
  45636. this.uniforms && (this.uniforms.opacity.value = o);
  45637. }
  45638. get color(){
  45639. return this.uniforms.baseColor.value
  45640. }
  45641. set color(c){
  45642. this.uniforms && (this.uniforms.baseColor.value.set(c));
  45643. }
  45644. /* dispose(){
  45645. super.dispose()
  45646. viewer.depthBasic
  45647. } */
  45648. copy(source){
  45649. super.copy(source);
  45650. this.useDepth = source.useDepth;
  45651. this.map = source.map;
  45652. return this
  45653. }
  45654. updateDepthParams(e={}){//主要用于点云遮住mesh
  45655. var viewport = e.viewport || viewer.mainViewport;
  45656. var camera = viewport.camera;
  45657. let hasDepth = this.useDepth && camera.isPerspectiveCamera &&
  45658. (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL);
  45659. this.setRealDepth(hasDepth, viewport);
  45660. if(hasDepth){
  45661. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行
  45662. this.uniforms.nearPlane.value = camera.near;
  45663. this.uniforms.farPlane.value = camera.far;
  45664. }
  45665. //this.uniforms.uUseOrthographicCamera.value = !camera.isPerspectiveCamera
  45666. }
  45667. }
  45668. const geo = new PlaneBufferGeometry(1,1);
  45669. class Sprite$2 extends Mesh{
  45670. constructor(options={}){
  45671. super(geo, options.mat || new DepthBasicMaterial(options));/* ({map:options.map, useDepth:options.useDepth})) */
  45672. this.root = options.root || this;
  45673. this.renderOrder = options.renderOrder != void 0 ? options.renderOrder : 4;
  45674. this.pickOrder = options.pickOrder || 0;
  45675. this.sizeInfo = options.sizeInfo;
  45676. this.dontFixOrient = options.dontFixOrient;
  45677. this.options = options;
  45678. this.position.y = options.disToLine || 0; //离线距离
  45679. this.matrixAutoUpdate = false;
  45680. this.matrixMap = new Map();
  45681. if(this.root != this){
  45682. this.matrixMapRoot = new Map();
  45683. this.root.matrixAutoUpdate = false;
  45684. }
  45685. this.visiMap = new Map();
  45686. this.name = options.name || 'sprite';
  45687. this.useViewport = null;
  45688. this.viewports = options.viewports;//指定更新的viewports
  45689. this.visible_ = true;
  45690. let clear = (e)=>{
  45691. this.matrixMap.clear();//清空后在所有viewport上都必须更新才能渲染 //this.needsUpdate = true
  45692. };
  45693. viewer.mapViewer && viewer.mapViewer.addEventListener("camera_changed", clear);
  45694. viewer.addEventListener("camera_changed", clear);
  45695. /* if(viewer.viewports.length == 1){//直接更新。如果有多个不在这更新,在"render.begin"
  45696. this.update(e)
  45697. } */
  45698. let applyMatrix = (e)=>{
  45699. this.applyMatrix(e);
  45700. };
  45701. viewer.addEventListener("raycaster", applyMatrix); //before render
  45702. viewer.addEventListener("render.begin", applyMatrix); //before render
  45703. viewer.addEventListener("render.begin2", applyMatrix);
  45704. viewer.addEventListener("cameraSetLayers", applyMatrix);
  45705. this.addEventListener('dispose', ()=>{
  45706. viewer.mapViewer && viewer.mapViewer.removeEventListener("camera_changed", clear);
  45707. viewer.removeEventListener("camera_changed", clear);
  45708. viewer.removeEventListener("raycaster", applyMatrix); //before render
  45709. viewer.removeEventListener("render.begin", applyMatrix);
  45710. viewer.removeEventListener("render.begin2", applyMatrix);
  45711. this.dispose();
  45712. });
  45713. }
  45714. set visible(v){
  45715. let oldV = this.visible_;
  45716. this.visible_ = v;
  45717. if(v && !oldV){
  45718. this.matrixMap && this.matrixMap.clear(); //this.update() //update内有unableCompute会无限回调
  45719. }
  45720. }
  45721. get visible(){
  45722. return this.visible_
  45723. }
  45724. realVisible(viewport, interactables/* , raycaster */){
  45725. if(interactables){
  45726. if(!interactables.some((object)=>{//interactables中是否能找到this
  45727. let finded;
  45728. object.traverse((object)=>{
  45729. if(object == this){
  45730. finded = true;
  45731. return {stopContinue:true}
  45732. }
  45733. });
  45734. return finded
  45735. }))return
  45736. }
  45737. /* if(interactables && viewport.name == 'mapViewport'){
  45738. console.log(this)
  45739. } */
  45740. if(!(/* raycaster || */viewport.camera).layers.test(this.layers)){//如地图上一般不可见测量线
  45741. return false
  45742. }
  45743. if(!this.visible && this.unvisibleReasons && this.unvisibleReasons.some(e=>e.reason != 'unableCompute')){
  45744. return false
  45745. }
  45746. let v = true;
  45747. let parent = this.parent;
  45748. let lastParent = this;
  45749. while(parent){
  45750. if(parent.visible === false){
  45751. v = false;
  45752. break;
  45753. }
  45754. lastParent = parent;
  45755. parent = parent.parent;
  45756. }
  45757. if(v && !(lastParent instanceof Scene)){//已被删除
  45758. v = false;
  45759. }
  45760. /* if(!this.latestRealVisi && v){//变为可见后先update
  45761. this.latestRealVisi = true
  45762. setTimeout(()=>{
  45763. this.update()
  45764. },1)//延迟 防止无限调用
  45765. return false
  45766. }
  45767. this.latestRealVisi = v */
  45768. return v;
  45769. }
  45770. waitUpdate(){
  45771. this.matrixMap.clear();//清空后在所有viewport上都必须更新才能渲染
  45772. //viewer.dispatchEvent('content_changed')
  45773. }
  45774. update(e={}){
  45775. if(!e.viewport){
  45776. let viewports = this.viewports || viewer.viewports;
  45777. if(!viewports)return
  45778. viewports.forEach(view=>{
  45779. this.update({viewport:view});
  45780. });
  45781. return;
  45782. }
  45783. if(!this.root || ! this.realVisible(e.viewport, e.interactables) /* this.visible */ )return
  45784. if(this.viewports && !this.viewports.includes(e.viewport) )return
  45785. if(e.viewport.name == 'magnifier')return
  45786. let camera = e.viewport.camera;
  45787. //rotation
  45788. if(!this.dontFixOrient){ //orthoCamera一般要加dontFixOrient
  45789. let orient2dAngle;
  45790. if(this.root.lineDir){
  45791. this.root.updateMatrix();//先更新,getWorldPosition才能得到正确的
  45792. this.root.updateMatrixWorld(true);
  45793. let center = this.root.getWorldPosition(new Vector3());
  45794. //由于两个端点容易在屏幕外,所以使用center和center加dir
  45795. let setVisi = (state)=>{
  45796. this.visiMap.set(e.viewport, state);
  45797. Potree.Utils.updateVisible(this, 'unableCompute', !!state);
  45798. };
  45799. let r1 = Potree.Utils.getPos2d(center, e.viewport, viewer.renderArea );
  45800. if(!r1.trueSide)return setVisi(false);// 但这句会使realVisible为false从而无法更新//console.error('!r1.trueSide') //中心点如果在背面直接不渲染了
  45801. let r2, point2;
  45802. let p2State = '', len=1, p2StateHistory = [];
  45803. while(p2State != 'got' && p2StateHistory.length<10){
  45804. point2 = center.clone().add(this.root.lineDir.clone().multiplyScalar(len));
  45805. r2 = Potree.Utils.getPos2d(point2, e.viewport , viewer.renderArea );
  45806. if(!r2.trueSide){ //很少遇到点2在背面的
  45807. if(!p2StateHistory.includes('tooLong-reverse')){
  45808. p2State = 'tooLong-reverse'; //先尝试反向
  45809. len = -len;
  45810. }else {
  45811. p2State = 'tooLong';
  45812. len = len / 2;
  45813. }
  45814. }else {
  45815. let dis = r2.pos.distanceTo(r1.pos);
  45816. if(math.closeTo(dis,0)){
  45817. //console.log('dis == 0')
  45818. setVisi(false);
  45819. return
  45820. break
  45821. }
  45822. if(dis<10 && !p2StateHistory.includes('tooLong')){//和r1的屏幕距离太近,要加长,否则精度过低
  45823. p2State = 'tooShort';
  45824. len = 100/dis * len;
  45825. }else {
  45826. p2State = 'got'; break;
  45827. }
  45828. }
  45829. p2StateHistory.push(p2State);
  45830. }
  45831. //console.log(p2StateHistory,len)
  45832. if(!r2.trueSide){
  45833. return setVisi(false)//, console.log(' !r2.trueSide', )
  45834. }
  45835. let p1 = r1.pos, p2 = r2.pos;
  45836. if(p2StateHistory.filter(e=>e == 'tooLong-reverse').length%2 == 1){//反,for marker
  45837. p2 = r1.pos, p1 = r2.pos;
  45838. }
  45839. let vec = new Vector2().subVectors(p1,p2);
  45840. orient2dAngle = -vec.angle(); //根据测量线在屏幕上的角度在旋转label,使之和屏幕上的二维线平行。
  45841. let y = Math.abs(this.position.y);
  45842. let facePlane = this.root.measure && this.root.measure.facePlane;
  45843. let eyeDir = new Vector3().subVectors(center,camera.position);
  45844. let clockWise = facePlane && facePlane.normal.dot(eyeDir/* e.viewport.view.direction */) < 0;
  45845. if(p1.x < p2.x){
  45846. orient2dAngle += Math.PI; //避免字是倒着的情况。(使字一直在线的下方)
  45847. clockWise != void 0 && (this.position.y = clockWise ? y : -y);
  45848. }else {
  45849. clockWise != void 0 && (this.position.y = clockWise ? -y : y); //使area类型的edgeLabel都在外侧
  45850. }
  45851. //this.parent.text && console.log(this.parent.text, clockWise, this.position.y, e.viewport.name /* THREE.Math.radToDeg(angle), p1.x < p2.x */ )
  45852. setVisi(true);
  45853. }
  45854. let parentQua = this.root.parent.getWorldQuaternion(new Quaternion);
  45855. this.root.quaternion.multiplyQuaternions(parentQua.invert(),camera.quaternion); //乘上parentQua.invert()是为了中和掉父结点的qua,使只剩下camera.quaternion
  45856. if(orient2dAngle){
  45857. let qua = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), orient2dAngle);
  45858. this.root.quaternion.multiply(qua);
  45859. }
  45860. }
  45861. //scale
  45862. var info = this.sizeInfo;
  45863. if(info){
  45864. this.root.updateMatrix();//先更新,getWorldPosition才能得到正确的
  45865. this.root.updateMatrixWorld(true);
  45866. var scale;
  45867. if(info.nearBound == void 0 && info.farBound != void 0 || info.nearBound != void 0 && info.farBound == void 0){//仅限制最大或最小的话,不判断像素大小,直接限制mesh的scale
  45868. //这个判断也可以写到getScaleForConstantSize里,可以更严谨控制像素宽度,这里只简单计算大小
  45869. var dis = camera.position.distanceTo(this.root.getWorldPosition(new Vector3()));
  45870. if(info.farBound == void 0 && dis < info.nearBound){
  45871. scale = info.scale * dis / info.nearBound;
  45872. }else if(info.nearBound == void 0 && dis > info.farBound){
  45873. scale = info.scale * dis / info.farBound;
  45874. }else {
  45875. scale = info.scale;
  45876. }
  45877. }else {
  45878. scale = math.getScaleForConstantSize($.extend(info,{//规定下最小最大像素
  45879. camera , position:this.root.getWorldPosition(new Vector3()) ,
  45880. resolution: e.viewport.resolution//2
  45881. }));
  45882. }
  45883. if(!isNaN(scale)){
  45884. this.root.scale.set(scale, scale, scale);
  45885. }
  45886. }
  45887. this.updateMatrix();
  45888. //this.root.updateMatrixWorld(true)
  45889. //console.log(this.root.text, this.root.matrix.elements)
  45890. this.matrixMap.set(e.viewport, this.matrix.clone());
  45891. if(this.root != this){
  45892. this.root.updateMatrix(); //因this.position可能在两个viewport不同
  45893. this.matrixMapRoot.set(e.viewport, this.root.matrix.clone());
  45894. }
  45895. this.needsUpdate = false;
  45896. this.useViewport = e.viewport;
  45897. }
  45898. applyMatrix(e){
  45899. if(!e)e = {viewport:viewer.mainViewport};//随便写一个viewport
  45900. let visi = this.visiMap.get(e.viewport); //还原可见性
  45901. Potree.Utils.updateVisible(this, 'unableCompute', visi == false ? false : true );
  45902. /* if(e.viewport.name == 'mapViewport' && visi && this.visiMap.get(viewer.mainViewport) == false){
  45903. console.log(1)
  45904. } */
  45905. if(e.viewport.name == 'magnifier')return
  45906. if(this.viewports && !this.viewports.includes(e.viewport) )return
  45907. if( !this.root || !this.realVisible(e.viewport, e.interactables) )return
  45908. var matrix = this.matrixMap.get(e.viewport);
  45909. if(!matrix){
  45910. this.update(e);
  45911. matrix = this.matrixMap.get(e.viewport);
  45912. if(!matrix)return
  45913. }
  45914. if(e.viewport == this.useViewport){
  45915. return
  45916. }
  45917. this.useViewport = e.viewport;
  45918. this.matrix.copy(matrix);
  45919. if(this.root != this){
  45920. var matrix2 = this.matrixMapRoot.get(e.viewport);
  45921. this.root.matrix.copy(matrix2);
  45922. }
  45923. e.raycaster && this.root.updateMatrixWorld(true);//渲染前会自动updateMatrixWorld,但raycaster不会
  45924. //console.log(this.root.name + e.viewport.name + " : "+this.root.matrixWorld.elements)
  45925. }
  45926. setUniforms(name,value){
  45927. this.material.setUniforms(name,value);
  45928. }
  45929. dispose(){
  45930. this.removeAllListeners();
  45931. this.parent && this.parent.remove(this);
  45932. }
  45933. }
  45934. /*
  45935. let orient2d
  45936. if(this.lineDir){
  45937. this.root.updateMatrix();//先更新,getWorldPosition才能得到正确的
  45938. this.root.updateMatrixWorld(true)
  45939. let center = this.root.getWorldPosition(new THREE.Vector3())
  45940. //由于两个端点容易在屏幕外,所以使用center和center加dir
  45941. let lineDir = this.lineDir.clone();
  45942. let r1 = Potree.Utils.getPos2d(center, camera, viewer.renderArea, e.viewport);
  45943. if(!r1.trueSide)return Potree.Utils.updateVisible(this, 'unableCompute', false);// 但这句会使realVisible为false从而无法更新//console.error('!r1.trueSide') //中心点如果在背面直接不渲染了
  45944. let r2, point2
  45945. let p2State = '', len=1, p2StateHistory = []
  45946. while(p2State != 'got' && p2StateHistory.length<10){
  45947. point2 = center.clone().add(lineDir.multiplyScalar(len));
  45948. r2 = Potree.Utils.getPos2d(point2, camera, viewer.renderArea, e.viewport);
  45949. if(!r2.trueSide){ //很少遇到点2在背面的
  45950. if(!p2StateHistory.includes('tooLong-reverse')){
  45951. p2State = 'tooLong-reverse' //先尝试反向
  45952. len = -len
  45953. }else{
  45954. p2State = 'tooLong'
  45955. len = len / 2
  45956. }
  45957. }else{
  45958. let dis = r2.pos.distanceTo(r1.pos)
  45959. if(dis == 0){
  45960. //console.log('dis == 0')
  45961. Potree.Utils.updateVisible(this, 'unableCompute', false)
  45962. return
  45963. break
  45964. }
  45965. if(dis<10 && !p2StateHistory.includes('tooLong')){//和r1的屏幕距离太近,要加长,否则精度过低
  45966. p2State = 'tooShort'
  45967. len = 100/dis * len
  45968. }else{
  45969. p2State = 'got'; break;
  45970. }
  45971. }
  45972. p2StateHistory.push(p2State)
  45973. }
  45974. //console.log(p2StateHistory,len)
  45975. if(!r2.trueSide){
  45976. return Potree.Utils.updateVisible(this, 'unableCompute', false)//, console.log(' !r2.trueSide', )
  45977. }
  45978. Potree.Utils.updateVisible(this, 'unableCompute', true)
  45979. let p1 = r1.pos, p2 = r2.pos
  45980. let vec = new THREE.Vector2().subVectors(p1,p2);
  45981. let angle = -vec.angle() //根据测量线在屏幕上的角度在旋转label,使之和屏幕上的二维线平行。
  45982. if(p1.x < p2.x) angle += Math.PI //避免字是倒着的情况
  45983. orient2d = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), angle)
  45984. //console.log(this.parent.text, THREE.Math.radToDeg(angle), p1.x < p2.x )
  45985. }
  45986. let parentQua = this.root.parent.getWorldQuaternion(new THREE.Quaternion)
  45987. this.root.quaternion.multiplyQuaternions(parentQua.invert(),camera.quaternion) //乘上parentQua.invert()是为了中和掉父结点的qua,使只剩下camera.quaternion
  45988. if(this.lineDir){
  45989. this.root.quaternion.multiply(orient2d)
  45990. }
  45991. */
  45992. //可能还是要用html写,因为要加按钮和图片
  45993. class TextSprite$2 extends Object3D{
  45994. //注:为了分两层控制scale,不直接extend Sprite
  45995. constructor( options={}){
  45996. super();
  45997. let map = new Texture();
  45998. map.minFilter = LinearFilter;
  45999. map.magFilter = LinearFilter;
  46000. this.sprite = new Sprite$2( Object.assign({
  46001. root:this
  46002. }
  46003. ,options,
  46004. {
  46005. map,
  46006. })
  46007. );
  46008. this.add(this.sprite);
  46009. this.fontWeight = options.fontWeight == void 0 ? 'Bold' : options.fontWeight;
  46010. this.rectBorderThick = options.rectBorderThick || 0;
  46011. this.textBorderThick = options.textBorderThick || 0;
  46012. this.fontface = 'Arial';
  46013. this.fontsize = options.fontsize || 16;
  46014. this.textBorderColor = options.textBorderColor ? Common$1.CloneObject(options.textBorderColor):{ r: 0, g: 0, b: 0, a: 0.0 };
  46015. this.backgroundColor = options.backgroundColor ? Common$1.CloneObject(options.backgroundColor):{ r: 255, g: 255, b: 255, a: 1.0 };
  46016. this.textColor = options.textColor ? Common$1.CloneObject(options.textColor):{r: 0, g: 0, b: 0, a: 1.0};
  46017. this.borderColor = options.borderColor ? Common$1.CloneObject(options.borderColor):{ r: 0, g: 0, b: 0, a: 0.0 };
  46018. this.borderRadius = options.borderRadius || 6;
  46019. this.margin = options.margin;
  46020. if(options.text != void 0)this.setText(options.text);
  46021. this.name = options.name;
  46022. //this.setText(text);
  46023. this.addEventListener('dispose', this.dispose.bind(this));
  46024. }
  46025. setText(text){
  46026. if (this.text !== text){
  46027. this.text = text + '';
  46028. this.updateTexture();
  46029. this.sprite.waitUpdate(); //重新计算各个viewport的matrix
  46030. }
  46031. }
  46032. setTextColor(color){
  46033. this.textColor = Common$1.CloneObject(color);
  46034. this.updateTexture();
  46035. }
  46036. setBorderColor(color){
  46037. this.borderColor = Common$1.CloneObject(color);
  46038. this.updateTexture();
  46039. }
  46040. setBackgroundColor(color){
  46041. this.backgroundColor = Common$1.CloneObject(color);
  46042. this.updateTexture();
  46043. }
  46044. setPos(pos){
  46045. this.position.copy(pos);
  46046. this.sprite.waitUpdate();
  46047. }
  46048. update(){
  46049. this.sprite.waitUpdate();
  46050. }
  46051. setVisible(v){
  46052. Potree.Utils.updateVisible(this, 'setVisible', v);
  46053. }
  46054. setUniforms(name,value){
  46055. this.sprite.setUniforms(name,value);
  46056. }
  46057. updateTexture(){
  46058. let canvas = document.createElement('canvas');
  46059. let context = canvas.getContext('2d');
  46060. const r = window.devicePixelRatio;
  46061. context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface;
  46062. //context["font-weight"] = 100; //语法与 CSS font 属性相同。
  46063. //this.text = '啊啊啊啊啊啊fag'
  46064. let metrics = context.measureText(this.text );
  46065. let textWidth = metrics.width;
  46066. let margin = (this.margin ? new Vector2().copy(this.margin) : new Vector2(this.fontsize, Math.max( this.fontsize*0.4, 10) )).clone().multiplyScalar(r);
  46067. let spriteWidth = 2 * margin.x + textWidth + 2 * this.rectBorderThick * r ;
  46068. let spriteHeight = 2 * margin.y + this.fontsize * r + 2 * this.rectBorderThick * r;
  46069. context.canvas.width = spriteWidth;
  46070. context.canvas.height = spriteHeight;
  46071. context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface;
  46072. /* let diff = 2//针对英文大部分在baseLine之上所以降低一点(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2
  46073. context.textBaseline = "middle"
  46074. */
  46075. let expand = Math.max(1, Math.pow(this.fontsize / 16, 1.3)) * r; // 针对英文大部分在baseLine之上所以降低一点,或者可以识别当不包含jgqp时才加这个值
  46076. //canvas原点在左上角
  46077. context.textBaseline = 'alphabetic'; // "middle" //设置文字基线。当起点y设置为0时,只有该线以下的部分被绘制出来。middle时文字显示一半(但是对该字体所有字的一半,有的字是不一定显示一半的,尤其汉字),alphabetic时是英文字母的那条基线。
  46078. //let actualHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent; // 当前文本字符串在这个字体下用的实际高度
  46079. //文字y向距离从textBaseline向上算
  46080. let actualBoundingBoxAscent = metrics.actualBoundingBoxAscent == void 0 ? this.fontsize * r * 0.8 : metrics.actualBoundingBoxAscent; //有的流览器没有。只能大概给一个
  46081. let y = actualBoundingBoxAscent + margin.y + expand;
  46082. //console.log(this.text, 'y' , y, 'actualBoundingBoxAscent', metrics.actualBoundingBoxAscent,'expand',expand )
  46083. // border color
  46084. context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' +
  46085. this.borderColor.b + ',' + this.borderColor.a + ')';
  46086. let rectBorderThick = this.rectBorderThick * r;
  46087. context.lineWidth = rectBorderThick;
  46088. // background color
  46089. context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' +
  46090. this.backgroundColor.b + ',' + this.backgroundColor.a + ')';
  46091. this.roundRect(context, rectBorderThick / 2 , rectBorderThick / 2,
  46092. spriteWidth - rectBorderThick, spriteHeight - rectBorderThick, this.borderRadius * r);
  46093. // text color
  46094. if(this.textBorderThick){
  46095. context.strokeStyle = 'rgba(' + this.textBorderColor.r + ',' + this.textBorderColor.g + ',' +
  46096. this.textBorderColor.b + ',' + this.textBorderColor.a + ')';
  46097. context.lineWidth = this.textBorderThick * r;
  46098. context.strokeText(this.text , rectBorderThick + margin.x, y /* spriteHeight/2 + diff */ );
  46099. }
  46100. context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' +
  46101. this.textColor.b + ',' + this.textColor.a + ')';
  46102. context.fillText(this.text , rectBorderThick + margin.x, y/* spriteHeight/2 + diff */ );//x,y
  46103. let texture = new Texture(canvas);
  46104. texture.minFilter = LinearFilter;
  46105. texture.magFilter = LinearFilter;
  46106. texture.needsUpdate = true;
  46107. //this.material.needsUpdate = true;
  46108. if(this.sprite.material.map){
  46109. this.sprite.material.map.dispose();
  46110. }
  46111. this.sprite.material.map = texture;
  46112. this.sprite.scale.set(spriteWidth * 0.01 / r, spriteHeight * 0.01 / r, 1.0);
  46113. }
  46114. roundRect(ctx, x, y, w, h, r){
  46115. ctx.beginPath();
  46116. ctx.moveTo(x + r, y);
  46117. ctx.lineTo(x + w - r, y);
  46118. ctx.arcTo(x + w, y, x + w, y + r, r );//圆弧。前四个参数同quadraticCurveTo
  46119. //ctx.quadraticCurveTo(x + w, y, x + w, y + r); //二次贝塞尔曲线需要两个点。第一个点是用于二次贝塞尔计算中的控制点,第二个点是曲线的结束点。
  46120. ctx.lineTo(x + w, y + h - r);
  46121. ctx.arcTo(x + w, y + h, x + w - r, y + h, r );
  46122. ctx.lineTo(x + r, y + h);
  46123. ctx.arcTo(x, y + h, x, y + h - r, r );
  46124. ctx.lineTo(x, y + r);
  46125. ctx.arcTo(x, y, x + r, y, r );
  46126. ctx.closePath();
  46127. ctx.fill();
  46128. ctx.stroke();
  46129. }
  46130. dispose(){
  46131. this.sprite.material.uniforms.map.value.dispose();
  46132. this.parent && this.parent.remove(this);
  46133. this.sprite.dispatchEvent({type:'dispose'});
  46134. this.removeAllListeners();
  46135. }
  46136. }
  46137. /*
  46138. z
  46139. |
  46140. |
  46141. |
  46142. |
  46143. x <-------| 中心为点云position加boudingbox中心
  46144. /
  46145. /
  46146. y
  46147. */
  46148. var lineLen$1 = 2, stemLen = 4, arrowLen = 2, lineDisToStem = 5;
  46149. var opacity = 0.5;
  46150. class Axis extends Object3D {// 坐标轴
  46151. constructor () {
  46152. super();
  46153. this.getArrow();
  46154. this.createArrows();
  46155. //this.position.copy(position) 点云的中心点就是在(0,0,0)
  46156. //this.scale.set(2,2,2)
  46157. /* viewer.addEventListener('camera_changed', e => {
  46158. if(e.viewport.name != 'MainView')return //只调整mainView,否则需要每次渲染前调整。缺点:地图上的大小变来变去
  46159. let s = Potree.math.getScaleForConstantSize( {//规定下最小最大像素
  46160. width2d:50, camera:e.camera , position:this.position,
  46161. resolution: e.viewport.resolution//2
  46162. })
  46163. this.scale.set(s,s,s)
  46164. }) */
  46165. }
  46166. getArrow(){
  46167. var arrowGroup = new Object3D();
  46168. var line = LineDraw.createLine([new Vector3, new Vector3(0,0,lineLen$1)]);
  46169. var stem = new Mesh(new BoxGeometry(0.3, 0.3, stemLen));
  46170. stem.position.set(0,0,lineLen$1+lineDisToStem+stemLen/2);
  46171. 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
  46172. arrow.position.set(0,0,lineLen$1+lineDisToStem+stemLen + arrowLen/2);
  46173. arrow.rotation.set(Math.PI/2,0,0);
  46174. arrowGroup.add(stem);
  46175. arrowGroup.add(line);
  46176. arrowGroup.add(arrow);
  46177. this.arrowGroup = arrowGroup;
  46178. }
  46179. createArrows(){
  46180. var material = new MeshBasicMaterial({color:"#00d7df",side:2,transparent:true,opacity:0.8, depthWrite:false});
  46181. ['x','y','z'].forEach((axisText)=>{
  46182. let color = new Color().set(Potree.config.axis[axisText].color);
  46183. var group = this.arrowGroup.clone();
  46184. group.children.forEach(e=>{
  46185. e.material = e.material.clone();
  46186. /* e.material.opacity = opacity
  46187. e.material.transparent = true */
  46188. e.material.color.copy(color);
  46189. });
  46190. var label = this.createLabel(axisText, color);
  46191. label.position.set(0, 0, lineLen$1 + stemLen + arrowLen + lineDisToStem + 3);
  46192. group.add(label);
  46193. if(axisText == 'y'){
  46194. group.rotation.x = -Math.PI / 2;
  46195. }else if(axisText == 'x'){
  46196. group.rotation.y = Math.PI / 2;
  46197. }
  46198. this.add(group);
  46199. });
  46200. }
  46201. createLabel(text,color){
  46202. let label = new TextSprite$2({ //无法解决 因其祖先有设定quaternion, 无法对着镜头
  46203. backgroundColor: {r: 0, g: 0, b: 0, a:0},
  46204. textColor: {r: color.r * 255, g: color.g*255, b: color.b*255, a:1},
  46205. fontsize:120,
  46206. //useDepth : true ,
  46207. renderOrder : 5,// pickOrder:5,
  46208. text, name:'axis'
  46209. });
  46210. label.scale.set(3,3,3);
  46211. return label
  46212. }
  46213. /* createLabel(text,color){
  46214. var canvas = document.createElement("canvas")
  46215. var context = canvas.getContext("2d");
  46216. canvas.width = 256,
  46217. canvas.height = 256;
  46218. var fontSize = 120
  46219. context.fillStyle = color //"#00ffee";
  46220. context.font = "normal " + fontSize + "px 微软雅黑"
  46221. var textWidth = context.measureText(text).width;
  46222. context.clearRect(0,0,canvas.width,canvas.height);
  46223. context.fillText(text, (canvas.width - textWidth) / 2 , (canvas.height + fontSize) / 2);
  46224. var tex = new THREE.Texture(canvas);
  46225. tex.needsUpdate = true
  46226. tex.minFilter = THREE.NearestFilter//防止边缘发黑
  46227. tex.magFilter = THREE.NearestFilter//防止边缘发黑
  46228. var sprite = new THREE.Sprite(new THREE.SpriteMaterial({
  46229. map: tex , // depthWrite:false,
  46230. }))
  46231. sprite.renderOrder = 1//防止在透明后还是出现白矩形挡住其他mesh
  46232. sprite.scale.set(3,3,3)
  46233. return sprite
  46234. } */
  46235. }
  46236. class Action extends EventDispatcher$1 {
  46237. constructor (args = {}) {
  46238. super();
  46239. this.icon = args.icon || '';
  46240. this.tooltip = args.tooltip;
  46241. if (args.onclick !== undefined) {
  46242. this.onclick = args.onclick;
  46243. }
  46244. }
  46245. onclick (event) {
  46246. }
  46247. pairWith (object) {
  46248. }
  46249. setIcon (newIcon) {
  46250. let oldIcon = this.icon;
  46251. if (newIcon === oldIcon) {
  46252. return;
  46253. }
  46254. this.icon = newIcon;
  46255. this.dispatchEvent({
  46256. type: 'icon_changed',
  46257. action: this,
  46258. icon: newIcon,
  46259. oldIcon: oldIcon
  46260. });
  46261. }
  46262. };
  46263. //Potree.Actions = {};
  46264. //
  46265. //Potree.Actions.ToggleAnnotationVisibility = class ToggleAnnotationVisibility extends Potree.Action {
  46266. // constructor (args = {}) {
  46267. // super(args);
  46268. //
  46269. // this.icon = Potree.resourcePath + '/icons/eye.svg';
  46270. // this.showIn = 'sidebar';
  46271. // this.tooltip = 'toggle visibility';
  46272. // }
  46273. //
  46274. // pairWith (annotation) {
  46275. // if (annotation.visible) {
  46276. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  46277. // } else {
  46278. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  46279. // }
  46280. //
  46281. // annotation.addEventListener('visibility_changed', e => {
  46282. // let annotation = e.annotation;
  46283. //
  46284. // if (annotation.visible) {
  46285. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  46286. // } else {
  46287. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  46288. // }
  46289. // });
  46290. // }
  46291. //
  46292. // onclick (event) {
  46293. // let annotation = event.annotation;
  46294. //
  46295. // annotation.visible = !annotation.visible;
  46296. //
  46297. // if (annotation.visible) {
  46298. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  46299. // } else {
  46300. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  46301. // }
  46302. // }
  46303. //};
  46304. class Annotation extends EventDispatcher$1 {
  46305. constructor (args = {}) {
  46306. super();
  46307. this.scene = null;
  46308. this._title = args.title || 'No Title';
  46309. this._description = args.description || '';
  46310. this.offset = new Vector3();
  46311. this.uuid = MathUtils.generateUUID();
  46312. if (!args.position) {
  46313. this.position = null;
  46314. } else if (args.position.x != null) {
  46315. this.position = args.position;
  46316. } else {
  46317. this.position = new Vector3(...args.position);
  46318. }
  46319. this.cameraPosition = (args.cameraPosition instanceof Array)
  46320. ? new Vector3().fromArray(args.cameraPosition) : args.cameraPosition;
  46321. this.cameraTarget = (args.cameraTarget instanceof Array)
  46322. ? new Vector3().fromArray(args.cameraTarget) : args.cameraTarget;
  46323. this.radius = args.radius;
  46324. this.view = args.view || null;
  46325. this.keepOpen = false;
  46326. this.descriptionVisible = false;
  46327. this.showDescription = true;
  46328. this.actions = args.actions || [];
  46329. this.isHighlighted = false;
  46330. this._visible = true;
  46331. this.__visible = true;
  46332. this._display = true;
  46333. this._expand = false;
  46334. this.collapseThreshold = [args.collapseThreshold, 100].find(e => e !== undefined);
  46335. this.children = [];
  46336. this.parent = null;
  46337. this.boundingBox = new Box3();
  46338. let iconClose = exports.resourcePath + '/icons/close.svg';
  46339. this.domElement = $(`
  46340. <div class="annotation" oncontextmenu="return false;">
  46341. <div class="annotation-titlebar">
  46342. <span class="annotation-label"></span>
  46343. </div>
  46344. <div class="annotation-description">
  46345. <span class="annotation-description-close">
  46346. <img src="${iconClose}" width="16px">
  46347. </span>
  46348. <span class="annotation-description-content">${this._description}</span>
  46349. </div>
  46350. </div>
  46351. `);
  46352. this.elTitlebar = this.domElement.find('.annotation-titlebar');
  46353. this.elTitle = this.elTitlebar.find('.annotation-label');
  46354. this.elTitle.append(this._title);
  46355. this.elDescription = this.domElement.find('.annotation-description');
  46356. this.elDescriptionClose = this.elDescription.find('.annotation-description-close');
  46357. // this.elDescriptionContent = this.elDescription.find(".annotation-description-content");
  46358. this.clickTitle = () => {
  46359. if(this.hasView()){
  46360. this.moveHere(this.scene.getActiveCamera());
  46361. }
  46362. this.dispatchEvent({type: 'click', target: this});
  46363. };
  46364. this.elTitle.click(this.clickTitle);
  46365. this.actions = this.actions.map(a => {
  46366. if (a instanceof Action) {
  46367. return a;
  46368. } else {
  46369. return new Action(a);
  46370. }
  46371. });
  46372. for (let action of this.actions) {
  46373. action.pairWith(this);
  46374. }
  46375. let actions = this.actions.filter(
  46376. a => a.showIn === undefined || a.showIn.includes('scene'));
  46377. for (let action of actions) {
  46378. let elButton = $(`<img src="${action.icon}" class="annotation-action-icon">`);
  46379. this.elTitlebar.append(elButton);
  46380. elButton.click(() => action.onclick({annotation: this}));
  46381. }
  46382. this.elDescriptionClose.hover(
  46383. e => this.elDescriptionClose.css('opacity', '1'),
  46384. e => this.elDescriptionClose.css('opacity', '0.5')
  46385. );
  46386. this.elDescriptionClose.click(e => this.setHighlighted(false));
  46387. // this.elDescriptionContent.html(this._description);
  46388. this.domElement.mouseenter(e => this.setHighlighted(true));
  46389. this.domElement.mouseleave(e => this.setHighlighted(false));
  46390. this.domElement.on('touchstart', e => {
  46391. this.setHighlighted(!this.isHighlighted);
  46392. });
  46393. this.display = false;
  46394. //this.display = true;
  46395. }
  46396. installHandles(viewer){
  46397. if(this.handles !== undefined){
  46398. return;
  46399. }
  46400. let domElement = $(`
  46401. <div style="position: absolute; left: 300; top: 200; pointer-events: none">
  46402. <svg width="300" height="600">
  46403. <line x1="0" y1="0" x2="1200" y2="200" style="stroke: black; stroke-width:2" />
  46404. <circle cx="50" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  46405. <circle cx="150" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  46406. </svg>
  46407. </div>
  46408. `);
  46409. let svg = domElement.find("svg")[0];
  46410. let elLine = domElement.find("line")[0];
  46411. let elStart = domElement.find("circle")[0];
  46412. let elEnd = domElement.find("circle")[1];
  46413. let setCoordinates = (start, end) => {
  46414. elStart.setAttribute("cx", `${start.x}`);
  46415. elStart.setAttribute("cy", `${start.y}`);
  46416. elEnd.setAttribute("cx", `${end.x}`);
  46417. elEnd.setAttribute("cy", `${end.y}`);
  46418. elLine.setAttribute("x1", start.x);
  46419. elLine.setAttribute("y1", start.y);
  46420. elLine.setAttribute("x2", end.x);
  46421. elLine.setAttribute("y2", end.y);
  46422. let box = svg.getBBox();
  46423. svg.setAttribute("width", `${box.width}`);
  46424. svg.setAttribute("height", `${box.height}`);
  46425. svg.setAttribute("viewBox", `${box.x} ${box.y} ${box.width} ${box.height}`);
  46426. let ya = start.y - end.y;
  46427. let xa = start.x - end.x;
  46428. if(ya > 0){
  46429. start.y = start.y - ya;
  46430. }
  46431. if(xa > 0){
  46432. start.x = start.x - xa;
  46433. }
  46434. domElement.css("left", `${start.x}px`);
  46435. domElement.css("top", `${start.y}px`);
  46436. };
  46437. $(viewer.renderArea).append(domElement);
  46438. let annotationStartPos = this.position.clone();
  46439. let annotationStartOffset = this.offset.clone();
  46440. $(this.domElement).draggable({
  46441. start: (event, ui) => {
  46442. annotationStartPos = this.position.clone();
  46443. annotationStartOffset = this.offset.clone();
  46444. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "none");
  46445. console.log($(this.domElement).find(".annotation-titlebar"));
  46446. },
  46447. stop: () => {
  46448. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "");
  46449. },
  46450. drag: (event, ui ) => {
  46451. let renderAreaWidth = viewer.renderer.getSize(new Vector2()).width;
  46452. //let renderAreaHeight = viewer.renderer.getSize().height;
  46453. let diff = {
  46454. x: ui.originalPosition.left - ui.position.left,
  46455. y: ui.originalPosition.top - ui.position.top
  46456. };
  46457. let nDiff = {
  46458. x: -(diff.x / renderAreaWidth) * 2,
  46459. y: (diff.y / renderAreaWidth) * 2
  46460. };
  46461. let camera = viewer.scene.getActiveCamera();
  46462. let oldScreenPos = new Vector3()
  46463. .addVectors(annotationStartPos, annotationStartOffset)
  46464. .project(camera);
  46465. let newScreenPos = oldScreenPos.clone();
  46466. newScreenPos.x += nDiff.x;
  46467. newScreenPos.y += nDiff.y;
  46468. let newPos = newScreenPos.clone();
  46469. newPos.unproject(camera);
  46470. let newOffset = new Vector3().subVectors(newPos, this.position);
  46471. this.offset.copy(newOffset);
  46472. }
  46473. });
  46474. let updateCallback = () => {
  46475. let position = this.position;
  46476. let scene = viewer.scene;
  46477. const renderAreaSize = viewer.renderer.getSize(new Vector2());
  46478. let renderAreaWidth = renderAreaSize.width;
  46479. let renderAreaHeight = renderAreaSize.height;
  46480. let start = this.position.clone();
  46481. let end = new Vector3().addVectors(this.position, this.offset);
  46482. let toScreen = (position) => {
  46483. let camera = scene.getActiveCamera();
  46484. let screenPos = new Vector3();
  46485. let worldView = new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  46486. let ndc = new Vector4(position.x, position.y, position.z, 1.0).applyMatrix4(worldView);
  46487. // limit w to small positive value, in case position is behind the camera
  46488. ndc.w = Math.max(ndc.w, 0.1);
  46489. ndc.divideScalar(ndc.w);
  46490. screenPos.copy(ndc);
  46491. screenPos.x = renderAreaWidth * (screenPos.x + 1) / 2;
  46492. screenPos.y = renderAreaHeight * (1 - (screenPos.y + 1) / 2);
  46493. return screenPos;
  46494. };
  46495. start = toScreen(start);
  46496. end = toScreen(end);
  46497. setCoordinates(start, end);
  46498. };
  46499. viewer.addEventListener("update", updateCallback);
  46500. this.handles = {
  46501. domElement: domElement,
  46502. setCoordinates: setCoordinates,
  46503. updateCallback: updateCallback
  46504. };
  46505. }
  46506. removeHandles(viewer){
  46507. if(this.handles === undefined){
  46508. return;
  46509. }
  46510. //$(viewer.renderArea).remove(this.handles.domElement);
  46511. this.handles.domElement.remove();
  46512. viewer.removeEventListener("update", this.handles.updateCallback);
  46513. delete this.handles;
  46514. }
  46515. get visible () {
  46516. return this._visible;
  46517. }
  46518. set visible (value) {
  46519. if (this._visible === value) {
  46520. return;
  46521. }
  46522. this._visible = value;
  46523. //this.traverse(node => {
  46524. // node.display = value;
  46525. //});
  46526. this.dispatchEvent({
  46527. type: 'visibility_changed',
  46528. annotation: this
  46529. });
  46530. }
  46531. get display () {
  46532. return this._display;
  46533. }
  46534. set display (display) {
  46535. if (this._display === display) {
  46536. return;
  46537. }
  46538. this._display = display;
  46539. if (display) {
  46540. // this.domElement.fadeIn(200);
  46541. this.domElement.show();
  46542. } else {
  46543. // this.domElement.fadeOut(200);
  46544. this.domElement.hide();
  46545. }
  46546. }
  46547. get expand () {
  46548. return this._expand;
  46549. }
  46550. set expand (expand) {
  46551. if (this._expand === expand) {
  46552. return;
  46553. }
  46554. if (expand) {
  46555. this.display = false;
  46556. } else {
  46557. this.display = true;
  46558. this.traverseDescendants(node => {
  46559. node.display = false;
  46560. });
  46561. }
  46562. this._expand = expand;
  46563. }
  46564. get title () {
  46565. return this._title;
  46566. }
  46567. set title (title) {
  46568. if (this._title === title) {
  46569. return;
  46570. }
  46571. this._title = title;
  46572. this.elTitle.empty();
  46573. this.elTitle.append(this._title);
  46574. this.dispatchEvent({
  46575. type: "annotation_changed",
  46576. annotation: this,
  46577. });
  46578. }
  46579. get description () {
  46580. return this._description;
  46581. }
  46582. set description (description) {
  46583. if (this._description === description) {
  46584. return;
  46585. }
  46586. this._description = description;
  46587. const elDescriptionContent = this.elDescription.find(".annotation-description-content");
  46588. elDescriptionContent.empty();
  46589. elDescriptionContent.append(this._description);
  46590. this.dispatchEvent({
  46591. type: "annotation_changed",
  46592. annotation: this,
  46593. });
  46594. }
  46595. add (annotation) {
  46596. if (!this.children.includes(annotation)) {
  46597. this.children.push(annotation);
  46598. annotation.parent = this;
  46599. let descendants = [];
  46600. annotation.traverse(a => { descendants.push(a); });
  46601. for (let descendant of descendants) {
  46602. let c = this;
  46603. while (c !== null) {
  46604. c.dispatchEvent({
  46605. 'type': 'annotation_added',
  46606. 'annotation': descendant
  46607. });
  46608. c = c.parent;
  46609. }
  46610. }
  46611. }
  46612. }
  46613. level () {
  46614. if (this.parent === null) {
  46615. return 0;
  46616. } else {
  46617. return this.parent.level() + 1;
  46618. }
  46619. }
  46620. hasChild(annotation) {
  46621. return this.children.includes(annotation);
  46622. }
  46623. remove (annotation) {
  46624. if (this.hasChild(annotation)) {
  46625. annotation.removeAllChildren();
  46626. annotation.dispose();
  46627. this.children = this.children.filter(e => e !== annotation);
  46628. annotation.parent = null;
  46629. }
  46630. }
  46631. removeAllChildren() {
  46632. this.children.forEach((child) => {
  46633. if (child.children.length > 0) {
  46634. child.removeAllChildren();
  46635. }
  46636. this.remove(child);
  46637. });
  46638. }
  46639. updateBounds () {
  46640. let box = new Box3();
  46641. if (this.position) {
  46642. box.expandByPoint(this.position);
  46643. }
  46644. for (let child of this.children) {
  46645. child.updateBounds();
  46646. box.union(child.boundingBox);
  46647. }
  46648. this.boundingBox.copy(box);
  46649. }
  46650. traverse (handler) {
  46651. let expand = handler(this);
  46652. if (expand === undefined || expand === true) {
  46653. for (let child of this.children) {
  46654. child.traverse(handler);
  46655. }
  46656. }
  46657. }
  46658. traverseDescendants (handler) {
  46659. for (let child of this.children) {
  46660. child.traverse(handler);
  46661. }
  46662. }
  46663. flatten () {
  46664. let annotations = [];
  46665. this.traverse(annotation => {
  46666. annotations.push(annotation);
  46667. });
  46668. return annotations;
  46669. }
  46670. descendants () {
  46671. let annotations = [];
  46672. this.traverse(annotation => {
  46673. if (annotation !== this) {
  46674. annotations.push(annotation);
  46675. }
  46676. });
  46677. return annotations;
  46678. }
  46679. setHighlighted (highlighted) {
  46680. if (highlighted) {
  46681. this.domElement.css('opacity', '0.8');
  46682. this.elTitlebar.css('box-shadow', '0 0 5px #fff');
  46683. this.domElement.css('z-index', '1000');
  46684. if (this._description) {
  46685. this.descriptionVisible = true;
  46686. this.elDescription.fadeIn(200);
  46687. this.elDescription.css('position', 'relative');
  46688. }
  46689. } else {
  46690. this.domElement.css('opacity', '0.5');
  46691. this.elTitlebar.css('box-shadow', '');
  46692. this.domElement.css('z-index', '100');
  46693. this.descriptionVisible = false;
  46694. this.elDescription.css('display', 'none');
  46695. }
  46696. this.isHighlighted = highlighted;
  46697. }
  46698. hasView () {
  46699. let hasPosTargetView = this.cameraTarget.x != null;
  46700. hasPosTargetView = hasPosTargetView && this.cameraPosition.x != null;
  46701. let hasRadiusView = this.radius !== undefined;
  46702. let hasView = hasPosTargetView || hasRadiusView;
  46703. return hasView;
  46704. };
  46705. moveHere (camera) {
  46706. if (!this.hasView()) {
  46707. return;
  46708. }
  46709. let view = this.scene.view;
  46710. let animationDuration = 500;
  46711. let easing = TWEEN.Easing.Quartic.Out;
  46712. let endTarget;
  46713. if (this.cameraTarget) {
  46714. endTarget = this.cameraTarget;
  46715. } else if (this.position) {
  46716. endTarget = this.position;
  46717. } else {
  46718. endTarget = this.boundingBox.getCenter(new Vector3());
  46719. }
  46720. if (this.cameraPosition) {
  46721. let endPosition = this.cameraPosition;
  46722. Utils.moveTo(this.scene, endPosition, endTarget);
  46723. } else if (this.radius) {
  46724. let direction = view.direction;
  46725. let endPosition = endTarget.clone().add(direction.multiplyScalar(-this.radius));
  46726. let startRadius = view.radius;
  46727. let endRadius = this.radius;
  46728. { // animate camera position
  46729. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  46730. tween.easing(easing);
  46731. tween.start();
  46732. }
  46733. { // animate radius
  46734. let t = {x: 0};
  46735. let tween = new TWEEN.Tween(t)
  46736. .to({x: 1}, animationDuration)
  46737. .onUpdate(function () {
  46738. view.radius = this.x * endRadius + (1 - this.x) * startRadius;
  46739. });
  46740. tween.easing(easing);
  46741. tween.start();
  46742. }
  46743. }
  46744. };
  46745. dispose () {
  46746. if (this.domElement.parentElement) {
  46747. this.domElement.parentElement.removeChild(this.domElement);
  46748. }
  46749. };
  46750. toString () {
  46751. return 'Annotation: ' + this._title;
  46752. }
  46753. };
  46754. class Scene$1 extends EventDispatcher$1{//base
  46755. constructor(){
  46756. super();
  46757. this.annotations = new Annotation();
  46758. this.scene = new Scene();
  46759. this.sceneBG = new Scene();
  46760. this.scenePointCloud = new Scene();
  46761. this.cameraP = new PerspectiveCamera(this.fov, 1, 0.1, 1000*1000);
  46762. this.cameraO = new OrthographicCamera(-1, 1, 1, -1, 0.1, 1000*1000);
  46763. this.cameraVR = new PerspectiveCamera();
  46764. this.cameraBG = new Camera();
  46765. this.cameraScreenSpace = new OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
  46766. this.cameraMode = CameraMode.PERSPECTIVE;
  46767. this.overrideCamera = null;
  46768. this.pointclouds = [];
  46769. this.measurements = [];
  46770. this.profiles = [];
  46771. this.volumes = [];
  46772. this.polygonClipVolumes = [];
  46773. this.cameraAnimations = [];
  46774. this.orientedImages = [];
  46775. this.images360 = [];
  46776. this.geopackages = [];
  46777. this.fpControls = null;
  46778. this.orbitControls = null;
  46779. this.earthControls = null;
  46780. this.geoControls = null;
  46781. this.deviceControls = null;
  46782. this.inputHandler = null;
  46783. this.view = new ExtendView();
  46784. this.directionalLight = null;
  46785. this.initialize();
  46786. }
  46787. estimateHeightAt (position) {
  46788. let height = null;
  46789. let fromSpacing = Infinity;
  46790. for (let pointcloud of this.pointclouds) {
  46791. if (pointcloud.root.geometryNode === undefined) {
  46792. continue;
  46793. }
  46794. let pHeight = null;
  46795. let pFromSpacing = Infinity;
  46796. let lpos = position.clone().sub(pointcloud.position);
  46797. lpos.z = 0;
  46798. let ray = new Ray(lpos, new Vector3(0, 0, 1));
  46799. let stack = [pointcloud.root];
  46800. while (stack.length > 0) {
  46801. let node = stack.pop();
  46802. let box = node.getBoundingBox();
  46803. let inside = ray.intersectBox(box);
  46804. if (!inside) {
  46805. continue;
  46806. }
  46807. let h = node.geometryNode.mean.z +
  46808. pointcloud.position.z +
  46809. node.geometryNode.boundingBox.min.z;
  46810. if (node.geometryNode.spacing <= pFromSpacing) {
  46811. pHeight = h;
  46812. pFromSpacing = node.geometryNode.spacing;
  46813. }
  46814. for (let index of Object.keys(node.children)) {
  46815. let child = node.children[index];
  46816. if (child.geometryNode) {
  46817. stack.push(node.children[index]);
  46818. }
  46819. }
  46820. }
  46821. if (height === null || pFromSpacing < fromSpacing) {
  46822. height = pHeight;
  46823. fromSpacing = pFromSpacing;
  46824. }
  46825. }
  46826. return height;
  46827. }
  46828. getBoundingBox(pointclouds = this.pointclouds){
  46829. let box = new Box3();
  46830. this.scenePointCloud.updateMatrixWorld(true);
  46831. this.referenceFrame.updateMatrixWorld(true);
  46832. for (let pointcloud of pointclouds) {
  46833. pointcloud.updateMatrixWorld(true);
  46834. let pointcloudBox = pointcloud.pcoGeometry.tightBoundingBox ? pointcloud.pcoGeometry.tightBoundingBox : pointcloud.boundingBox;
  46835. let boxWorld = Utils.computeTransformedBoundingBox(pointcloudBox, pointcloud.matrixWorld);
  46836. box.union(boxWorld);
  46837. }
  46838. return box;
  46839. }
  46840. addPointCloud (pointcloud) {
  46841. this.pointclouds.push(pointcloud);
  46842. this.scenePointCloud.add(pointcloud);
  46843. this.dispatchEvent({
  46844. type: 'pointcloud_added',
  46845. pointcloud: pointcloud
  46846. });
  46847. }
  46848. addVolume (volume) {
  46849. this.volumes.push(volume);
  46850. this.dispatchEvent({
  46851. 'type': 'volume_added',
  46852. 'scene': this,
  46853. 'volume': volume
  46854. });
  46855. viewer.dispatchEvent('content_changed');
  46856. }
  46857. addOrientedImages(images){
  46858. this.orientedImages.push(images);
  46859. this.scene.add(images.node);
  46860. this.dispatchEvent({
  46861. 'type': 'oriented_images_added',
  46862. 'scene': this,
  46863. 'images': images
  46864. });
  46865. };
  46866. removeOrientedImages(images){
  46867. let index = this.orientedImages.indexOf(images);
  46868. if (index > -1) {
  46869. this.orientedImages.splice(index, 1);
  46870. this.dispatchEvent({
  46871. 'type': 'oriented_images_removed',
  46872. 'scene': this,
  46873. 'images': images
  46874. });
  46875. }
  46876. };
  46877. add360Images(images){
  46878. this.images360.push(images);
  46879. this.scene.add(images.node);
  46880. this.dispatchEvent({
  46881. 'type': '360_images_added',
  46882. 'scene': this,
  46883. 'images': images
  46884. });
  46885. }
  46886. remove360Images(images){
  46887. let index = this.images360.indexOf(images);
  46888. if (index > -1) {
  46889. this.images360.splice(index, 1);
  46890. this.dispatchEvent({
  46891. 'type': '360_images_removed',
  46892. 'scene': this,
  46893. 'images': images
  46894. });
  46895. }
  46896. }
  46897. addGeopackage(geopackage){
  46898. this.geopackages.push(geopackage);
  46899. this.scene.add(geopackage.node);
  46900. this.dispatchEvent({
  46901. 'type': 'geopackage_added',
  46902. 'scene': this,
  46903. 'geopackage': geopackage
  46904. });
  46905. };
  46906. removeGeopackage(geopackage){
  46907. let index = this.geopackages.indexOf(geopackage);
  46908. if (index > -1) {
  46909. this.geopackages.splice(index, 1);
  46910. this.dispatchEvent({
  46911. 'type': 'geopackage_removed',
  46912. 'scene': this,
  46913. 'geopackage': geopackage
  46914. });
  46915. }
  46916. };
  46917. removeVolume (volume) {
  46918. let index = this.volumes.indexOf(volume);
  46919. if (index > -1) {
  46920. this.volumes.splice(index, 1);
  46921. this.dispatchEvent({
  46922. 'type': 'volume_removed',
  46923. 'scene': this,
  46924. 'volume': volume
  46925. });
  46926. }
  46927. viewer.dispatchEvent('content_changed');
  46928. };
  46929. addCameraAnimation(animation) {
  46930. this.cameraAnimations.push(animation);
  46931. this.dispatchEvent({
  46932. 'type': 'camera_animation_added',
  46933. 'scene': this,
  46934. 'animation': animation
  46935. });
  46936. };
  46937. removeCameraAnimation(animation){
  46938. let index = this.cameraAnimations.indexOf(volume);
  46939. if (index > -1) {
  46940. this.cameraAnimations.splice(index, 1);
  46941. this.dispatchEvent({
  46942. 'type': 'camera_animation_removed',
  46943. 'scene': this,
  46944. 'animation': animation
  46945. });
  46946. }
  46947. };
  46948. addPolygonClipVolume(volume){
  46949. this.polygonClipVolumes.push(volume);
  46950. this.dispatchEvent({
  46951. "type": "polygon_clip_volume_added",
  46952. "scene": this,
  46953. "volume": volume
  46954. });
  46955. };
  46956. removePolygonClipVolume(volume){
  46957. let index = this.polygonClipVolumes.indexOf(volume);
  46958. if (index > -1) {
  46959. this.polygonClipVolumes.splice(index, 1);
  46960. this.dispatchEvent({
  46961. "type": "polygon_clip_volume_removed",
  46962. "scene": this,
  46963. "volume": volume
  46964. });
  46965. }
  46966. };
  46967. addMeasurement(measurement){
  46968. measurement.lengthUnit = this.lengthUnit;
  46969. measurement.lengthUnitDisplay = this.lengthUnitDisplay;
  46970. this.measurements.push(measurement);
  46971. this.dispatchEvent({
  46972. 'type': 'measurement_added',
  46973. 'scene': this,
  46974. 'measurement': measurement
  46975. });
  46976. viewer.dispatchEvent('content_changed');
  46977. };
  46978. removeMeasurement (measurement) {
  46979. let index = this.measurements.indexOf(measurement);
  46980. if (index > -1) {
  46981. this.measurements.splice(index, 1);
  46982. this.dispatchEvent({
  46983. 'type': 'measurement_removed',
  46984. 'scene': this,
  46985. 'measurement': measurement
  46986. });
  46987. viewer.dispatchEvent('content_changed');
  46988. }
  46989. }
  46990. addProfile (profile) {
  46991. this.profiles.push(profile);
  46992. this.dispatchEvent({
  46993. 'type': 'profile_added',
  46994. 'scene': this,
  46995. 'profile': profile
  46996. });
  46997. }
  46998. removeProfile (profile) {
  46999. let index = this.profiles.indexOf(profile);
  47000. if (index > -1) {
  47001. this.profiles.splice(index, 1);
  47002. this.dispatchEvent({
  47003. 'type': 'profile_removed',
  47004. 'scene': this,
  47005. 'profile': profile
  47006. });
  47007. }
  47008. }
  47009. removeAllMeasurements () {
  47010. while (this.measurements.length > 0) {
  47011. this.removeMeasurement(this.measurements[0]);
  47012. }
  47013. while (this.profiles.length > 0) {
  47014. this.removeProfile(this.profiles[0]);
  47015. }
  47016. while (this.volumes.length > 0) {
  47017. this.removeVolume(this.volumes[0]);
  47018. }
  47019. }
  47020. removeAllClipVolumes(){
  47021. let clipVolumes = this.volumes.filter(volume => volume.clip === true);
  47022. for(let clipVolume of clipVolumes){
  47023. this.removeVolume(clipVolume);
  47024. }
  47025. while(this.polygonClipVolumes.length > 0){
  47026. this.removePolygonClipVolume(this.polygonClipVolumes[0]);
  47027. }
  47028. }
  47029. getActiveCamera() {
  47030. if(this.overrideCamera){
  47031. return this.overrideCamera;
  47032. }
  47033. if(this.cameraMode === CameraMode.PERSPECTIVE){
  47034. return this.cameraP;
  47035. }else if(this.cameraMode === CameraMode.ORTHOGRAPHIC){
  47036. return this.cameraO;
  47037. }else if(this.cameraMode === CameraMode.VR){
  47038. return this.cameraVR;
  47039. }
  47040. return null;
  47041. }
  47042. initialize(){
  47043. this.referenceFrame = new Object3D();
  47044. this.referenceFrame.matrixAutoUpdate = false;
  47045. this.scenePointCloud.add(this.referenceFrame);
  47046. this.cameraP.up.set(0, 0, 1);
  47047. this.cameraP.position.set(1000, 1000, 1000);
  47048. this.cameraO.up.set(0, 0, 1);
  47049. this.cameraO.position.set(1000, 1000, 1000);
  47050. //this.camera.rotation.y = -Math.PI / 4;
  47051. //this.camera.rotation.x = -Math.PI / 6;
  47052. this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0));
  47053. this.directionalLight = new DirectionalLight( 0xffffff, 0.5 );
  47054. this.directionalLight.position.set( 10, 10, 10 );
  47055. this.directionalLight.lookAt( new Vector3(0, 0, 0));
  47056. this.scenePointCloud.add( this.directionalLight );
  47057. let light = new AmbientLight( 0x555555 ); // soft white light
  47058. this.scenePointCloud.add( light );
  47059. { // background
  47060. let texture = Utils.createBackgroundTexture(512, 512);
  47061. texture.minFilter = texture.magFilter = NearestFilter;
  47062. texture.minFilter = texture.magFilter = LinearFilter;
  47063. let bg = new Mesh(
  47064. new PlaneBufferGeometry(2, 2, 1),
  47065. new MeshBasicMaterial({
  47066. map: texture
  47067. })
  47068. );
  47069. bg.material.depthTest = false;
  47070. bg.material.depthWrite = false;
  47071. this.sceneBG.add(bg);
  47072. }
  47073. // { // lights
  47074. // {
  47075. // let light = new THREE.DirectionalLight(0xffffff);
  47076. // light.position.set(10, 10, 1);
  47077. // light.target.position.set(0, 0, 0);
  47078. // this.scene.add(light);
  47079. // }
  47080. // {
  47081. // let light = new THREE.DirectionalLight(0xffffff);
  47082. // light.position.set(-10, 10, 1);
  47083. // light.target.position.set(0, 0, 0);
  47084. // this.scene.add(light);
  47085. // }
  47086. // {
  47087. // let light = new THREE.DirectionalLight(0xffffff);
  47088. // light.position.set(0, -10, 20);
  47089. // light.target.position.set(0, 0, 0);
  47090. // this.scene.add(light);
  47091. // }
  47092. // }
  47093. }
  47094. addAnnotation(position, args = {}){
  47095. if(position instanceof Array){
  47096. args.position = new Vector3().fromArray(position);
  47097. } else if (position.x != null) {
  47098. args.position = position;
  47099. }
  47100. let annotation = new Annotation(args);
  47101. this.annotations.add(annotation);
  47102. return annotation;
  47103. }
  47104. getAnnotations () {
  47105. return this.annotations;
  47106. };
  47107. removeAnnotation(annotationToRemove) {
  47108. this.annotations.remove(annotationToRemove);
  47109. }
  47110. };
  47111. class ExtendScene extends Scene$1{
  47112. constructor(){
  47113. super();
  47114. delete this.sceneBG;
  47115. this.cameraP = new PerspectiveCamera(this.fov, 1, Potree.config.view.near, Potree.config.view.near);
  47116. this.cameraO = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar);
  47117. this.cameraP.limitFar = true;//add
  47118. this.initializeExtend();
  47119. //-------------
  47120. this.axisArrow = new Axis();
  47121. this.scene.add(this.axisArrow);
  47122. if(!Potree.settings.isDebug && !Potree.settings.showAxis)this.axisArrow.visible = false;
  47123. Potree.Utils.setObjectLayers(this.axisArrow, 'bothMapAndScene' );
  47124. this.tags = new Object3D;
  47125. this.scene.add(this.tags);
  47126. }
  47127. estimateHeightAt (position) {
  47128. let height = null;
  47129. let fromSpacing = Infinity;
  47130. for (let pointcloud of this.pointclouds) {
  47131. if (pointcloud.root.geometryNode === undefined) {
  47132. continue;
  47133. }
  47134. let pHeight = null;
  47135. let pFromSpacing = Infinity;
  47136. let lpos = position.clone().sub(pointcloud.position);
  47137. lpos.z = 0;
  47138. let ray = new Ray(lpos, new Vector3(0, 0, 1));
  47139. let stack = [pointcloud.root];
  47140. while (stack.length > 0) {
  47141. let node = stack.pop();
  47142. let box = node.getBoundingBox();
  47143. let inside = ray.intersectBox(box);
  47144. if (!inside) {
  47145. continue;
  47146. }
  47147. let h = node.geometryNode.mean.z +
  47148. pointcloud.position.z +
  47149. node.geometryNode.boundingBox.min.z;
  47150. if (node.geometryNode.spacing <= pFromSpacing) {
  47151. pHeight = h;
  47152. pFromSpacing = node.geometryNode.spacing;
  47153. }
  47154. for (let index of Object.keys(node.children)) {
  47155. let child = node.children[index];
  47156. if (child.geometryNode) {
  47157. stack.push(node.children[index]);
  47158. }
  47159. }
  47160. }
  47161. if (height === null || pFromSpacing < fromSpacing) {
  47162. height = pHeight;
  47163. fromSpacing = pFromSpacing;
  47164. }
  47165. }
  47166. return height;
  47167. }
  47168. //add:
  47169. removePointCloud (pointcloud) {
  47170. let index = this.pointclouds.indexOf(pointcloud);
  47171. if(index == -1)return
  47172. this.pointclouds.splice(index, 1);
  47173. this.scenePointCloud.remove(pointcloud);
  47174. pointcloud.panos.forEach(pano=>{
  47175. pano.dispose();
  47176. });
  47177. }
  47178. removeCameraAnimation(animation){
  47179. let index = this.cameraAnimations.indexOf(animation);
  47180. if (index > -1) {
  47181. this.cameraAnimations.splice(index, 1);
  47182. this.dispatchEvent({
  47183. 'type': 'camera_animation_removed',
  47184. 'scene': this,
  47185. 'animation': animation
  47186. });
  47187. }
  47188. };
  47189. getActiveCamera() {
  47190. return viewer.mainViewport.camera
  47191. }
  47192. initialize(){//不用旧的 因为还没创建完变量
  47193. }
  47194. initializeExtend(){//add 新的initialize
  47195. this.referenceFrame = new Object3D();
  47196. this.referenceFrame.matrixAutoUpdate = false;
  47197. this.scenePointCloud.add(this.referenceFrame);
  47198. if(window.axisYup){
  47199. }else {
  47200. this.cameraP.up.set(0, 0, 1);
  47201. this.cameraO.up.set(0, 0, 1);
  47202. }
  47203. this.cameraP.position.set(1000, 1000, 1000);
  47204. this.cameraO.position.set(1000, 1000, 1000);
  47205. //this.camera.rotation.y = -Math.PI / 4;
  47206. //this.camera.rotation.x = -Math.PI / 6;
  47207. this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0));
  47208. this.directionalLight = new DirectionalLight( 0xffffff, 0.5 );
  47209. this.directionalLight.position.set( 10, 10, 10 );
  47210. this.directionalLight.lookAt( new Vector3(0, 0, 0));
  47211. this.scenePointCloud.add( this.directionalLight );
  47212. let light = new AmbientLight( 0x555555 ); // soft white light
  47213. this.scenePointCloud.add( light );
  47214. //add:------给空间模型的box 或其他obj------
  47215. let light2 = new AmbientLight( 16777215, 1 );
  47216. Potree.Utils.setObjectLayers(light2, 'light'/* 'bothMapAndScene' */);
  47217. this.scene.add(light2);
  47218. let light3 = new DirectionalLight( 16777215, 1);
  47219. light3.position.set( 10, 10, 10 );
  47220. light3.lookAt( new Vector3(0, 0, 0));
  47221. Potree.Utils.setObjectLayers(light3, 'light');
  47222. this.scene.add(light3);
  47223. //--------------------------------------------
  47224. { // background
  47225. let texture = Utils.createBackgroundTexture(512, 512);
  47226. texture.minFilter = texture.magFilter = NearestFilter;
  47227. texture.minFilter = texture.magFilter = LinearFilter;
  47228. let bg = new Mesh(
  47229. new PlaneBufferGeometry(2, 2, 1),
  47230. new MeshBasicMaterial({
  47231. map: texture
  47232. })
  47233. );
  47234. bg.material.depthTest = false;
  47235. bg.material.depthWrite = false;
  47236. bg.name = 'bg';
  47237. //this.sceneBG.add(bg);
  47238. this.scene.add(bg);
  47239. bg.layers.set(Potree.config.renderLayers.bg);
  47240. }
  47241. { // background color
  47242. let bg2 = new Mesh(
  47243. new PlaneBufferGeometry(2, 2, 1),
  47244. new MeshBasicMaterial({
  47245. transparent : true
  47246. })
  47247. );
  47248. bg2.material.depthTest = false;
  47249. bg2.material.depthWrite = false;
  47250. bg2.name = 'bg2';
  47251. this.scene.add(bg2);
  47252. bg2.layers.set(Potree.config.renderLayers.bg2);
  47253. this.bg2 = bg2;
  47254. }
  47255. // { // lights
  47256. // {
  47257. // let light = new THREE.DirectionalLight(0xffffff);
  47258. // light.position.set(10, 10, 1);
  47259. // light.target.position.set(0, 0, 0);
  47260. // this.scene.add(light);
  47261. // }
  47262. // {
  47263. // let light = new THREE.DirectionalLight(0xffffff);
  47264. // light.position.set(-10, 10, 1);
  47265. // light.target.position.set(0, 0, 0);
  47266. // this.scene.add(light);
  47267. // }
  47268. // {
  47269. // let light = new THREE.DirectionalLight(0xffffff);
  47270. // light.position.set(0, -10, 20);
  47271. // light.target.position.set(0, 0, 0);
  47272. // this.scene.add(light);
  47273. // }
  47274. // }
  47275. }
  47276. };
  47277. KeyCodes.BACKSPACE = 8;
  47278. //注意,这时候Potree.js中export的内容还不在Potree变量中
  47279. var texLoader$1 = new TextureLoader();
  47280. {//defines:
  47281. Potree.defines = {};
  47282. Potree.defines.Buttons = {// MouseEvent.buttons
  47283. //buttons,设置按下了鼠标哪些键,是一个3个比特位的二进制值,默认为0。1表示按下主键(通常是左键),2表示按下次要键(通常是右键),4表示按下辅助键(通常是中间的键)。
  47284. NONE:0,//add
  47285. LEFT: 0b0001,
  47286. RIGHT: 0b0010,
  47287. MIDDLE: 0b0100
  47288. };
  47289. /* 如果访问的是button, 用THREE.MOUSE来判断:
  47290. button,设置按下了哪一个鼠标按键,默认为0。-1表示没有按键,0表示按下主键(通常是左键),1表示按下辅助键(通常是中间的键),2表示按下次要键(通常是右键)
  47291. */
  47292. Potree.browser = browser;
  47293. /////////// add //////////////////////////////////
  47294. Potree.defines.GLCubeFaces = {
  47295. GL_TEXTURE_CUBE_MAP_POSITIVE_X: 0,
  47296. GL_TEXTURE_CUBE_MAP_NEGATIVE_X: 1,
  47297. GL_TEXTURE_CUBE_MAP_POSITIVE_Y: 2,
  47298. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: 3,
  47299. GL_TEXTURE_CUBE_MAP_POSITIVE_Z: 4,
  47300. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: 5
  47301. };
  47302. Potree.defines.PanoSizeClass = {
  47303. BASE: 1,
  47304. STANDARD: 2,
  47305. HIGH: 3,
  47306. ULTRAHIGH: 4
  47307. };
  47308. Potree.defines.PanoRendererEvents = {
  47309. PanoRenderComplete: "panorama.render.complete",
  47310. TileRenderFailure: "panorama.tile.render.failed",
  47311. TileRenderSuccess: "panorama.tile.render.success",
  47312. TileUploadAttempted: "panorama.tile.upload.attempted",
  47313. UploadAttemptedForAllTiles: "panorama.upload.attempted.all.tiles",
  47314. ZoomLevelRenderStarted: "panorama.zoom.render.started"
  47315. };
  47316. Potree.defines.SceneRendererEvents = {
  47317. ContextCreated: "scene-renderer-context-created",
  47318. AfterRender: "after-render",
  47319. MemoryUsageUpdated: "scene-renderer-memory-usage-updated"
  47320. };
  47321. Potree.defines.TileDownloaderEvents = {
  47322. TileDownloadSuccess: "tiledownloader.download.success",
  47323. TileDownloadFailure: "tiledownloader.download.failure",
  47324. PanoDownloadComplete: "tiledownloader.pano.download.complete"
  47325. };
  47326. Potree.defines.Vectors = {
  47327. UP: new Vector3(0,1,0),
  47328. DOWN: new Vector3(0,-1,0),
  47329. LEFT: new Vector3(-1,0,0),
  47330. RIGHT: new Vector3(1,0,0),
  47331. FORWARD: new Vector3(0,0,-1),
  47332. BACK: new Vector3(0,0,1)
  47333. };
  47334. /* var Vectors2 = {}
  47335. for(var i in Vectors){
  47336. Vectors2[i] = math.convertVector.YupToZup(Vectors[i])
  47337. }
  47338. */
  47339. Potree.defines.DownloadStatus = Object.freeze({
  47340. None: 0,
  47341. Queued: 1,
  47342. ForceQueued: 2,
  47343. Downloading: 3,
  47344. Downloaded: 4,
  47345. DownloadFailed: 5
  47346. });
  47347. Potree.defines.ModelManagerEvents = {
  47348. ModelAdded: "model-added",
  47349. ActiveModelChanged: "active-model-changed"
  47350. };
  47351. Potree.defines.PanoramaEvents = {
  47352. Enter: 'panorama.enter',
  47353. Exit: 'panorama.exit',
  47354. LoadComplete: "panorama.load.complete",
  47355. LoadFailed: "panorama.load.failed",
  47356. TileLoaded: "panorama.tile.loaded",
  47357. VideoRendered: "panorama.video.rendered"
  47358. };
  47359. ClipTask.SHOW_INSIDE_Big = 4;
  47360. }
  47361. {//Features
  47362. let gl_;
  47363. Features.EXT_DEPTH = {
  47364. isSupported: function (gl) {
  47365. gl = gl || gl_;
  47366. gl_ = gl;
  47367. if(browser.detectIOS()){
  47368. let {major,minor,patch} = browser.iosVersion();
  47369. //console.warn('iosVersion',major,minor,patch)
  47370. if(major == 15 && minor == 4 && patch == 1){
  47371. console.warn('检测到是ios15.4.1, 关闭EXT_frag_depth');//该版本ext_depth有问题,导致clear错乱。没有解决办法先关闭。
  47372. return false
  47373. }
  47374. }
  47375. return (typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext) || gl.getExtension('EXT_frag_depth'); //shader中的GL_EXT_frag_depth需要判断一下detectIOS吗。。
  47376. }
  47377. };
  47378. }
  47379. Utils.loadSkybox = function(path, oldSky ) {
  47380. let camera, scene, parent , cameraOrtho;
  47381. if(!oldSky){
  47382. parent = new Object3D("skybox_root");
  47383. camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
  47384. cameraOrtho = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar);
  47385. if(!window.axisYup) camera.up.set(0, 0, 1);//add
  47386. scene = new Scene();
  47387. let skyboxBgWidth = Potree.config.skyboxBgWidth;
  47388. let skyGeometry = new BoxBufferGeometry(skyboxBgWidth,skyboxBgWidth,skyboxBgWidth);
  47389. let skybox = new Mesh(skyGeometry, new ShaderMaterial({
  47390. vertexShader: Shaders['skybox.vs'],
  47391. fragmentShader: Shaders['skybox.fs'],
  47392. side: BackSide,
  47393. uniforms:{
  47394. tDiffuse: {
  47395. type: "t",
  47396. value: null
  47397. },
  47398. matrix:{
  47399. type: "m4",
  47400. value: new Matrix4
  47401. }
  47402. },
  47403. depthTest:false,
  47404. depthWrite:false
  47405. }) );
  47406. scene.add(skybox);
  47407. scene.traverse(n => n.frustumCulled = false);
  47408. // z up
  47409. //scene.rotation.x = Math.PI / 2;
  47410. parent.children.push(camera);
  47411. camera.parent = parent;
  47412. }else {
  47413. camera = oldSky.camera,
  47414. scene = oldSky.scene;
  47415. parent = oldSky.parent;
  47416. cameraOrtho = oldSky.cameraOrtho;
  47417. }
  47418. let texture = texLoader$1.load( path, ()=>{
  47419. console.log('loadSkybox成功',path);
  47420. texture.wrapS = RepeatWrapping;
  47421. texture.flipY = false;
  47422. texture.magFilter = LinearFilter;
  47423. texture.minFilter = LinearFilter;
  47424. scene.children[0].material.uniforms.tDiffuse.value = texture;
  47425. viewer.dispatchEvent('content_changed');
  47426. },null,(e)=>{//error
  47427. console.error('loadSkybox失败',path);
  47428. });
  47429. return {camera, scene, parent, cameraOrtho};
  47430. };
  47431. Utils.getMousePointCloudIntersection = function(viewport, mouse, pointer, camera, viewer, pointclouds, pickParams = {} ) {
  47432. //getIntersectByDepthTex
  47433. /* let result = viewer.edlRenderer.depthTexSampler.sample(viewport, mouse)//add
  47434. if(result != 'unsupport')return result
  47435. */
  47436. if(!pointclouds || pointclouds.length == 0)return
  47437. //console.log('getMousePointCloudIntersection')
  47438. let renderer = viewer.renderer;
  47439. if(viewport){ //转换到类似整个画面时
  47440. /*let mouseInViewport = Utils.convertNDCToScreenPosition(pointer, null, viewport.resolution.x, viewport.resolution.y)
  47441. pickParams.x = mouseInViewport.x //mouse.x / viewport.width;
  47442. pickParams.y = mouseInViewport.y //renderer.domElement.clientHeight - mouse.y / viewport.height; */
  47443. pickParams.x = mouse.x;
  47444. pickParams.y = viewport.resolution.y - mouse.y;
  47445. }else {
  47446. pickParams.x = mouse.x;
  47447. pickParams.y = renderer.domElement.clientHeight - mouse.y;
  47448. }
  47449. //console.log('getMousePointCloudIntersection')
  47450. /* if(!raycaster){
  47451. raycaster = new THREE.Raycaster();
  47452. raycaster.setFromCamera(pointer, camera);
  47453. } */
  47454. let raycaster = new Raycaster();
  47455. raycaster.setFromCamera(pointer, camera);
  47456. let ray = raycaster.ray;
  47457. let selectedPointcloud = null;
  47458. let closestDistance = Infinity;
  47459. let closestIntersection = null;
  47460. let closestPoint = null;
  47461. //-----------add--------------------
  47462. let old_clipBoxes_in = new Map();
  47463. let old_clipBoxes_out = new Map();
  47464. let old_bigClipInBox = new Map();
  47465. let old_highlightBoxes = new Map();
  47466. //bigClipInBox 最好也写下
  47467. let density;
  47468. let sizeType;
  47469. let size = new Map();
  47470. let visiMap = new Map();
  47471. let needsUpdate = false;
  47472. if(pickParams.measuring || Potree.settings.displayMode == 'showPanos') { //(无深度图) 测量或全景模式提高精准度,因为漫游的
  47473. density = Potree.settings.pointDensity;
  47474. Potree.settings.pointDensity = 'magnifier';
  47475. pointclouds.forEach(e=>{//因为全景模式的pointSizeType是fixed所以要还原下
  47476. visiMap.set(e,e.visible);
  47477. e.visible = Potree.Utils.getObjVisiByReason(e, 'datasetSelection'); //先将隐藏的点云显示
  47478. if(!e.visible)return
  47479. size.set(e, e.temp.pointSize);
  47480. sizeType = e.material.pointSizeType;
  47481. e.material.pointSizeType = Potree.config.material.pointSizeType;
  47482. e.changePointSize(Potree.config.material.realPointSize*2, true);//更改点云大小到能铺满为止,否则容易识别不到
  47483. });
  47484. needsUpdate = true;
  47485. }else {
  47486. if(viewer.viewports.filter(e=>!e.noPointcloud && e.active).length>1 || pickParams.cameraChanged){//在pick时相机和渲染时不一样的话
  47487. viewport.beforeRender && viewport.beforeRender();
  47488. needsUpdate = true; //不updatePointClouds的话hover久了会不准 因node是错的
  47489. //但依旧需要camera真的移动到那个位置才能加载出点云
  47490. }
  47491. }
  47492. if(!pickParams.pickClipped){// 无视clipBoxes
  47493. for(let pointcloud of pointclouds){
  47494. old_clipBoxes_in.set(pointcloud, pointcloud.clipBoxes_in);
  47495. old_clipBoxes_out.set(pointcloud, pointcloud.clipBoxes_in);
  47496. old_bigClipInBox.set(pointcloud, pointcloud.bigClipInBox);
  47497. old_highlightBoxes.set(pointcloud, pointcloud.highlightBoxes);
  47498. pointcloud.material.setClipBoxes(null, [],[],[]);
  47499. }
  47500. needsUpdate = true;
  47501. }
  47502. if(needsUpdate){
  47503. Potree.updatePointClouds(pointclouds, camera, viewport.resolution ); //最好只更新pick的范围的resolution
  47504. }
  47505. //------------------------------------------------
  47506. let allPointclouds = [];
  47507. for(let pointcloud of pointclouds){
  47508. let point = pointcloud.pick(viewer, viewport, camera, ray, pickParams );
  47509. if(!point){
  47510. continue;
  47511. }
  47512. allPointclouds.push(pointcloud);
  47513. let distance = camera.position.distanceTo(point.position);
  47514. if (distance < closestDistance) {
  47515. closestDistance = distance;
  47516. selectedPointcloud = pointcloud;
  47517. closestIntersection = point.position;
  47518. closestPoint = point;
  47519. }
  47520. }
  47521. //恢复
  47522. if(pickParams.measuring || Potree.settings.displayMode == 'showPanos'){
  47523. Potree.settings.pointDensity = density;
  47524. pointclouds.forEach(e=>{
  47525. if(e.visible){
  47526. e.material.pointSizeType = sizeType;
  47527. e.changePointSize(size.get(e));
  47528. }
  47529. e.visible = visiMap.get(e);
  47530. });
  47531. }else {
  47532. /* if(viewer.viewports.filter(e=>!e.noPointcloud).length>1){
  47533. viewport.afterRender && viewport.afterRender()
  47534. } */
  47535. }
  47536. if(!pickParams.pickClipped){//add
  47537. for(let pointcloud of pointclouds){
  47538. pointcloud.material.setClipBoxes(old_bigClipInBox.get(pointcloud), old_clipBoxes_in.get(pointcloud), old_clipBoxes_out.get(pointcloud), old_highlightBoxes.get(pointcloud));
  47539. }
  47540. }
  47541. if (selectedPointcloud) {
  47542. return {
  47543. location: closestIntersection,
  47544. distance: closestDistance,
  47545. pointcloud: selectedPointcloud,
  47546. point: closestPoint,
  47547. pointclouds: allPointclouds, //add
  47548. normal: new Vector3().fromArray(closestPoint.normal )//add
  47549. };
  47550. } else {
  47551. return null;
  47552. }
  47553. };
  47554. Utils.pixelsArrayToDataUrl = function(pixels, width, height, compressRatio = 0.7) {
  47555. let canvas = document.createElement('canvas');
  47556. canvas.width = width;
  47557. canvas.height = height;
  47558. let context = canvas.getContext('2d');
  47559. pixels = new pixels.constructor(pixels);
  47560. /* for (let i = 0; i < pixels.length; i++) {
  47561. pixels[i * 4 + 3] = 255;
  47562. } */
  47563. // flip vertically
  47564. let bytesPerLine = width * 4;
  47565. for(let i = 0; i < parseInt(height / 2); i++){
  47566. let j = height - i - 1;
  47567. let lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine);
  47568. let lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine);
  47569. pixels.set(lineJ, i * bytesPerLine);
  47570. pixels.set(lineI, j * bytesPerLine);
  47571. }
  47572. let imageData = context.createImageData(width, height);
  47573. imageData.data.set(pixels);
  47574. context.putImageData(imageData, 0, 0);
  47575. let dataURL = canvas.toDataURL(compressRatio);
  47576. return dataURL;
  47577. };
  47578. Utils.renderTargetToDataUrl = function(renderTarget, width, height, renderer, compressRatio = 0.7){
  47579. let pixelCount = width * height;
  47580. let buffer = new Uint8Array(4 * pixelCount);
  47581. renderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, buffer);
  47582. var dataUrl = Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio);
  47583. return dataUrl
  47584. };
  47585. Utils.mouseToRay = function(pointer, camera ){
  47586. let vector = new Vector3(pointer.x, pointer.y, 1);
  47587. let origin = new Vector3(pointer.x, pointer.y, -1); //不能用camera.position,在orbitCamera时不准
  47588. vector.unproject(camera);
  47589. origin.unproject(camera);
  47590. let direction = new Vector3().subVectors(vector, origin).normalize();
  47591. let ray = new Ray(origin, direction);
  47592. return ray;
  47593. };
  47594. Utils.getPos2d = function(point, viewport , dom ){//获取一个三维坐标对应屏幕中的二维坐标
  47595. var pos;
  47596. if(math.closeTo(viewport.camera.position, point, 1e-5) ){ //和相机位置重合时显示会四处飘,看是要改成一直显示中间还是隐藏?
  47597. pos = new Vector3(0,0,1.5); //1.5是为了不可见
  47598. }else {
  47599. 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);
  47600. }
  47601. var x,y,left,top;
  47602. x = (pos.x + 1) / 2 * dom.clientWidth * viewport.width;
  47603. y = (1 - (pos.y + 1) / 2) * dom.clientHeight * viewport.height;
  47604. left = viewport.left * dom.clientWidth;
  47605. top = (1- viewport.bottom - viewport.height) * dom.clientHeight;
  47606. var inSight = pos.x <= 1 && pos.x >= -1 //是否在屏幕中
  47607. && pos.x <= 1 && pos.y >= -1;
  47608. return {
  47609. pos: new Vector2(left+x,top+y) ,// 屏幕像素坐标
  47610. vector: pos, //(范围 -1 ~ 1)
  47611. trueSide : pos.z<1, //trueSide为false时,即使在屏幕范围内可见,也是反方向的另一个不可以被渲染的点 参见Tag.update
  47612. inSight : inSight, //在屏幕范围内可见,
  47613. posInViewport: new Vector2(x,y)
  47614. };
  47615. };
  47616. Utils.screenPass = new function () {
  47617. this.screenScene = new Scene();
  47618. this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1));
  47619. this.screenQuad.material.depthTest = true;
  47620. this.screenQuad.material.depthWrite = true;
  47621. this.screenQuad.material.transparent = true;
  47622. this.screenScene.add(this.screenQuad);
  47623. this.camera = new Camera();
  47624. this.render = function (renderer, material, target, composer) {
  47625. this.screenQuad.material = material;
  47626. if (typeof target === 'undefined') {
  47627. (composer || renderer).render(this.screenScene, this.camera);
  47628. } else {
  47629. let oldTarget = renderer.getRenderTarget();
  47630. renderer.setRenderTarget(target);
  47631. //renderer.clear(); //有时候不能clear,如renderBG后再
  47632. (composer || renderer).render(this.screenScene, this.camera);
  47633. renderer.setRenderTarget(oldTarget);
  47634. }
  47635. };
  47636. }();
  47637. //add
  47638. Utils.computePointcloudsBound = function(pointclouds){
  47639. var boundingBox = new Box3();
  47640. pointclouds.forEach(pointcloud=>{
  47641. pointcloud.updateBound();
  47642. boundingBox.union(pointcloud.bound2);
  47643. });
  47644. var boundSize = boundingBox.getSize(new Vector3);
  47645. var center = boundingBox.getCenter(new Vector3);
  47646. return {boundSize, center, boundingBox}
  47647. };
  47648. Utils.convertScreenPositionToNDC = function(pointer, mouse, width, height) {
  47649. return pointer = pointer || new Vector2,
  47650. pointer.x = mouse.x / width * 2 - 1,
  47651. pointer.y = 2 * -(mouse.y / height) + 1,
  47652. pointer
  47653. };
  47654. Utils.convertNDCToScreenPosition = function(pointer, mouse, width, height) {
  47655. return mouse = mouse || new Vector2,
  47656. mouse.x = Math.round((pointer.x + 1 ) / 2 * width),
  47657. mouse.y = Math.round(-(pointer.y - 1 ) / 2 * height),
  47658. mouse
  47659. };
  47660. Utils.getOrthoCameraMoveVec = function(pointerDelta, camera ){//获取当camera为Ortho型时 屏幕点1 到 屏幕点2 的三维距离
  47661. let cameraViewWidth = camera.right / camera.zoom;
  47662. let cameraViewHeight = camera.top / camera.zoom;
  47663. let moveVec = new Vector3;
  47664. moveVec.set( pointerDelta.x * cameraViewWidth , pointerDelta.y * cameraViewHeight , 0).applyQuaternion(camera.quaternion);
  47665. return moveVec
  47666. };
  47667. Utils.VectorFactory = {
  47668. fromArray : function(t) {
  47669. if (t) {
  47670. if (t.length < 2 || t.length > 3)
  47671. console.error("Wrong number of ordinates for a point!");
  47672. return 3 === t.length ? (new Vector3).fromArray(t) : (new Vector2).fromArray(t)
  47673. }
  47674. },
  47675. fromArray3 : function(t) {
  47676. if (t) {
  47677. if (3 !== t.length)
  47678. console.error("Wrong number of ordinates for a point!");
  47679. return (new Vector3).fromArray(t)
  47680. }
  47681. },
  47682. fromArray2 : function(t) {
  47683. if (t) {
  47684. if (2 !== t.length)
  47685. console.error("Wrong number of ordinates for a point!");
  47686. return (new Vector2).fromArray(t)
  47687. }
  47688. },
  47689. toString : function(t) {
  47690. return t.x.toFixed(8) + "," + t.y.toFixed(8) + "," + t.z.toFixed(3)
  47691. }
  47692. };
  47693. Utils.QuaternionFactory = {
  47694. rot90 : (new Quaternion).setFromAxisAngle(new Vector3(0,0,1), MathUtils.degToRad(-90)),
  47695. fromArray : function(t) {
  47696. if (t) {
  47697. if (4 !== t.length)
  47698. console.error("Wrong number of ordinates for a quaternion!");
  47699. return new Quaternion(t[1],t[2],t[3],t[0]).multiply(this.rot90)
  47700. }
  47701. }
  47702. ,
  47703. toArray : function(t) {
  47704. if (t) {
  47705. var e = t.clone().multiply(a).toArray();
  47706. return [e[3], e[0], e[1], e[2]]
  47707. }
  47708. }
  47709. ,
  47710. fromLonLat : function(t) {
  47711. if (t)
  47712. return (new Quaternion).setFromEuler(new Euler(t.lon,t.lat,0))
  47713. }
  47714. ,
  47715. toLonLat : function(t) {
  47716. if (t) {
  47717. var e = (new Euler).setFromQuaternion(t);
  47718. return {
  47719. lon: e.x,
  47720. lat: e.y
  47721. }
  47722. }
  47723. }
  47724. };
  47725. Utils.datasetPosTransform = function(o={}){
  47726. let pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e=>e.dataset_id == o.datasetId);
  47727. let tranMatrix;
  47728. if(pointcloud){
  47729. if(Potree.settings.editType == 'merge'){
  47730. tranMatrix = o.fromDataset ? pointcloud.matrixWorld : new Matrix4().copy(pointcloud.matrixWorld).invert();
  47731. }else {
  47732. tranMatrix = o.fromDataset ? pointcloud.transformMatrix : pointcloud.transformInvMatrix;
  47733. }
  47734. }else {
  47735. if(Potree.settings.intersectOnObjs){
  47736. let object = o.object || viewer.objs.children.find(e=>e.dataset_id == o.datasetId);
  47737. if(object){
  47738. tranMatrix = o.fromDataset ? object.matrixWorld : new Matrix4().copy(object.matrixWorld).invert();
  47739. }
  47740. }
  47741. }
  47742. if(tranMatrix){
  47743. return (new Vector3).copy(o.position).applyMatrix4(tranMatrix)
  47744. }else {
  47745. if(o.datasetId != void 0){
  47746. console.error(`datasetPosTransform找不到datasetId为${o.datasetId}的数据集或模型,请检查数据, 模型未创建或删除`);
  47747. //很可能是旧的热点,需要删除
  47748. }
  47749. }
  47750. };
  47751. Utils.datasetRotTransform = function(o={}){
  47752. let pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e=>e.dataset_id == o.datasetId);
  47753. if(pointcloud){
  47754. var matrix, newMatrix, result;
  47755. if(o.rotation){
  47756. matrix = new Matrix4().makeRotationFromEuler(o.rotation);
  47757. }else if(o.quaternion){
  47758. matrix = new Matrix4().makeRotationFromQuaternion(o.quaternion);
  47759. }else if(o.matrix){
  47760. matrix = o.matrix.clone();
  47761. }else {
  47762. return
  47763. }
  47764. let rotateMatrix = o.fromDataset ? pointcloud.rotateMatrix : pointcloud.rotateInvMatrix;
  47765. newMatrix = new Matrix4().multiplyMatrices(rotateMatrix, matrix );
  47766. if(o.getRotation){
  47767. result = new Euler().setFromRotationMatrix(newMatrix);
  47768. }else if(o.getQuaternion){
  47769. result = new Quaternion().setFromRotationMatrix(newMatrix);
  47770. }else if(o.getMatrix){
  47771. result = newMatrix;
  47772. }
  47773. return result
  47774. }
  47775. };
  47776. Utils.isInsideFrustum = function(bounding, camera){// bounding是否在视野范围内有可见部分(视野就是一个锥状box)
  47777. let frustumMatrix = new Matrix4;
  47778. frustumMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  47779. let frustum = new Frustum();
  47780. frustum.setFromProjectionMatrix(frustumMatrix);
  47781. if(bounding instanceof Sphere){
  47782. return frustum.intersectsSphere(bounding)
  47783. }else {
  47784. return frustum.intersectsBox(bounding)
  47785. }
  47786. };
  47787. Utils.isIntersectBox = function(object, boxMatrix){//object是否有在box中的部分。 object可以是点或者bounding, box原为1*1*1,但可能形变
  47788. //let frustum = new THREE.Frustum();
  47789. //frustum.setFromProjectionMatrix(boxMatrixInverse) --错
  47790. let px = new Vector3(+0.5, 0, 0).applyMatrix4(boxMatrix);
  47791. let nx = new Vector3(-0.5, 0, 0).applyMatrix4(boxMatrix);
  47792. let py = new Vector3(0, +0.5, 0).applyMatrix4(boxMatrix);
  47793. let ny = new Vector3(0, -0.5, 0).applyMatrix4(boxMatrix);
  47794. let pz = new Vector3(0, 0, +0.5).applyMatrix4(boxMatrix);
  47795. let nz = new Vector3(0, 0, -0.5).applyMatrix4(boxMatrix);
  47796. let pxN = new Vector3().subVectors(nx, px).normalize();
  47797. let nxN = pxN.clone().multiplyScalar(-1);
  47798. let pyN = new Vector3().subVectors(ny, py).normalize();
  47799. let nyN = pyN.clone().multiplyScalar(-1);
  47800. let pzN = new Vector3().subVectors(nz, pz).normalize();
  47801. let nzN = pzN.clone().multiplyScalar(-1);
  47802. let pxPlane = new Plane().setFromNormalAndCoplanarPoint(pxN, px);
  47803. let nxPlane = new Plane().setFromNormalAndCoplanarPoint(nxN, nx);
  47804. let pyPlane = new Plane().setFromNormalAndCoplanarPoint(pyN, py);
  47805. let nyPlane = new Plane().setFromNormalAndCoplanarPoint(nyN, ny);
  47806. let pzPlane = new Plane().setFromNormalAndCoplanarPoint(pzN, pz);
  47807. let nzPlane = new Plane().setFromNormalAndCoplanarPoint(nzN, nz);
  47808. let frustum = new Frustum(pxPlane, nxPlane, pyPlane, nyPlane, pzPlane, nzPlane);
  47809. if(object instanceof Box3){
  47810. var boxBound = new Box3(
  47811. new Vector3(-0.5,-0.5,-0.5), new Vector3(0.5,0.5,0.5),
  47812. ).applyMatrix4(boxMatrix); //large boundingbox
  47813. if(!object.intersectsBox(boxBound))return
  47814. return frustum.intersectsBox(object) //根据该函数, 若存在某个plane在box上的对应点都在plane背面,则不相交. 可得知在box构成的frustum倾斜时不准确,不相交也判断为相交,甚至不如bound相交准确。所以前面加步骤排除下,但仍不完全准确。(可在裁剪中将box放置到数据集上方旋转下校验)
  47815. }else if(object instanceof Array){//点合集, 只能粗略计算下
  47816. let sphere = new Sphere();
  47817. sphere.setFromPoints(object);
  47818. return this.isIntersectBox(sphere, boxMatrix)
  47819. }else if(object instanceof Sphere){
  47820. return frustum.intersectsSphere(object)
  47821. }else if(object instanceof Vector3){
  47822. return frustum.containsPoint(object)
  47823. }else if(object instanceof Matrix4){//第一个参数如果和第二个参数一样都是box的worldMatrix
  47824. }
  47825. /* containsPoint: ƒ containsPoint( point )
  47826. intersectsBox: ƒ intersectsBox( box )
  47827. intersectsObject: ƒ intersectsObject( object )//geo
  47828. intersectsSphere: ƒ intersectsSphere( sphere )
  47829. intersectsSprite: ƒ intersectsSprite( sprite )
  47830. */
  47831. };
  47832. Utils.getIntersect = function (camera, meshes, pointer, raycaster) {
  47833. //获取鼠标和meshes交点
  47834. if(!raycaster){//getMouseIntersect
  47835. camera.updateMatrixWorld();
  47836. raycaster = new Raycaster();
  47837. var origin = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  47838. end = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  47839. var dir = end.sub(origin).normalize();
  47840. raycaster.set(origin, dir);
  47841. }
  47842. meshes.forEach(e=>{
  47843. raycaster.layers.enable(math.getBaseLog(2,e.layers.mask));
  47844. });
  47845. var n = raycaster.intersectObjects(meshes);
  47846. if (0 === n.length) return null
  47847. return n[0]
  47848. };
  47849. Utils.addOrRemoveDefine = function(material, defineName, type, value=''){
  47850. let defines = material.defines;
  47851. if(type == 'add'){
  47852. if(defines[defineName] != void 0 && defines[defineName] == value)return
  47853. defines[defineName] = value;
  47854. }else {
  47855. if(defines[defineName] != void 0)return;
  47856. delete defines[defineName];
  47857. }
  47858. material.needsUpdate = true;
  47859. };
  47860. Utils.makeTexDontResize = function(map){//避免贴图因非2的次方而缩小。小心使用
  47861. if(!map || !map.image){
  47862. return console.log('!map || !map.image', map, map&&map.image)
  47863. }
  47864. if(MathUtils.isPowerOfTwo(map.image.width ) && MathUtils.isPowerOfTwo(map.image.height ))return
  47865. map.wrapS = map.wrapT = ClampToEdgeWrapping; //原默认 RepeatWrapping
  47866. map.minFilter = LinearFilter; // or THREE.NearestFilter 原默认 LinearMipmapLinearFilter
  47867. map.generateMipmaps = false;
  47868. map.needsUpdate = true;
  47869. };
  47870. Utils.updateVisible = function(object, reason, ifShow, level=0, type){//当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  47871. if(!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  47872. if(!object.visibleReasons) object.visibleReasons = []; //在同级时,优先可见
  47873. var update = function(){
  47874. //先按从高到低的level排列
  47875. object.unvisibleReasons = object.unvisibleReasons.sort((a,b)=>b.level-a.level);
  47876. object.visibleReasons = object.visibleReasons.sort((a,b)=>b.level-a.level);
  47877. var maxVisiLevel = object.visibleReasons[0] ? object.visibleReasons[0].level : -1;
  47878. var maxunVisiLevel = object.unvisibleReasons[0] ? object.unvisibleReasons[0].level : -1;
  47879. var shouldVisi = maxVisiLevel >= maxunVisiLevel;
  47880. var visiBefore = object.visible;
  47881. if(visiBefore != shouldVisi){
  47882. object.visible = shouldVisi;
  47883. object.dispatchEvent({
  47884. type: 'isVisible',
  47885. visible: shouldVisi,
  47886. reason,
  47887. });
  47888. }
  47889. };
  47890. if(ifShow){
  47891. var index = object.unvisibleReasons.findIndex(e=>e.reason == reason);
  47892. if(index > -1){
  47893. type = 'cancel';
  47894. object.unvisibleReasons.splice(index, 1);
  47895. }
  47896. if(type == 'add' ){
  47897. if(!object.visibleReasons.some(e=>e.reason == reason)){
  47898. object.visibleReasons.push({reason,level});
  47899. }
  47900. }
  47901. }else {
  47902. var index = object.visibleReasons.findIndex(e=>e.reason == reason);
  47903. if(index > -1){
  47904. type = 'cancel';
  47905. object.visibleReasons.splice(index, 1);
  47906. }
  47907. if(type != 'cancel' ){
  47908. if(!object.unvisibleReasons.some(e=>e.reason == reason)){
  47909. object.unvisibleReasons.push({reason,level});
  47910. }
  47911. }
  47912. }
  47913. update();
  47914. };
  47915. /*
  47916. 复杂案例: 如果物体默认隐藏, 当符合任何一个其他条件时可见,则可:
  47917. Potree.Utils.updateVisible(this, "default", false, 0 ) //默认隐藏
  47918. Potree.Utils.updateVisible(this, 条件名, ifShow, 1, ifShow?'add':'cancel' ) //其他的条件
  47919. */
  47920. Utils.getObjVisiByReason = function(object,reason){//获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  47921. if(object.visible)return true
  47922. else {
  47923. return !object.unvisibleReasons || !object.unvisibleReasons.some(e=>e.reason == reason)
  47924. }
  47925. };
  47926. Utils.setCameraLayers = function(camera, enableLayers, extraEnableLayers=[]){//add
  47927. camera.layers.disableAll();
  47928. enableLayers.concat(extraEnableLayers).forEach(e=>{
  47929. let layer = Potree.config.renderLayers[e];
  47930. if(layer == void 0){
  47931. console.error('setCameraLayer没找到layer!');
  47932. return
  47933. }
  47934. camera.layers.enable(layer);
  47935. });
  47936. };
  47937. Utils.setObjectLayers = function(object, layerName){//add
  47938. let layer = Potree.config.renderLayers[layerName];
  47939. if(layer == void 0){
  47940. console.error('setCameraLayer没找到layer!');
  47941. return
  47942. }
  47943. object.traverse(e=>{
  47944. e.layers.set(layer);
  47945. });
  47946. };
  47947. BinaryLoader.prototype.load = function(node, callback){//解析点云
  47948. if (node.loaded) {
  47949. return;
  47950. }
  47951. let url = node.getURL();
  47952. if (this.version.equalOrHigher('1.4')) {
  47953. url += '.bin';
  47954. }
  47955. url += '?m='+node.pcoGeometry.timeStamp; //add
  47956. let xhr = XHRFactory.createXMLHttpRequest();
  47957. xhr.open('GET', url, true);
  47958. xhr.responseType = 'arraybuffer';
  47959. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  47960. xhr.onreadystatechange = () => {
  47961. if (xhr.readyState === 4) {
  47962. if((xhr.status === 200 || xhr.status === 0) && xhr.response !== null){
  47963. let buffer = xhr.response;
  47964. this.parse(node, buffer, callback);
  47965. } else {
  47966. //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  47967. throw new Error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  47968. }
  47969. }
  47970. };
  47971. try {
  47972. xhr.send(null);
  47973. } catch (e) {
  47974. console.log('fehler beim laden der punktwolke: ' + e);
  47975. }
  47976. };
  47977. PointAttribute.RGBA_PACKED = new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_INT8, 4);
  47978. PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED;
  47979. PointAttribute.INTENSITY = new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  47980. PointAttribute.CLASSIFICATION = new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  47981. PointAttribute.GPS_TIME = new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1);
  47982. ProfileWindow.prototype.initTHREE = function(){
  47983. this.renderer = new WebGLRenderer({alpha: true, premultipliedAlpha: false});
  47984. this.renderer.setClearColor(0x000000, 0);
  47985. this.renderer.setSize(10, 10);
  47986. this.renderer.autoClear = false;
  47987. this.renderArea.append($(this.renderer.domElement));
  47988. this.renderer.domElement.tabIndex = '2222';
  47989. $(this.renderer.domElement).css('width', '100%');
  47990. $(this.renderer.domElement).css('height', '100%');
  47991. {
  47992. let gl = this.renderer.getContext();
  47993. if(gl.createVertexArray == null){
  47994. let extVAO = gl.getExtension('OES_vertex_array_object');
  47995. if(!extVAO){
  47996. throw new Error("OES_vertex_array_object extension not supported");
  47997. }
  47998. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  47999. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  48000. }
  48001. }
  48002. this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000);
  48003. this.camera.up.set(0, 0, 1);
  48004. this.camera.rotation.order = "ZXY";
  48005. this.camera.rotation.x = Math.PI / 2.0;
  48006. this.scene = new Scene();
  48007. this.profileScene = new Scene();
  48008. let sg = new SphereGeometry(1, 16, 16);
  48009. let sm = new MeshNormalMaterial();
  48010. this.pickSphere = new Mesh(sg, sm);
  48011. this.scene.add(this.pickSphere);
  48012. this.viewerPickSphere = new Mesh(sg, sm);
  48013. };
  48014. //Potree_update_visibility
  48015. Potree.updatePointClouds = function(pointclouds,camera, areaSize ){
  48016. viewer.addTimeMark('updateClouds','start');
  48017. for (let pointcloud of pointclouds) {
  48018. let start = performance.now();
  48019. for (let profileRequest of pointcloud.profileRequests) {
  48020. profileRequest.update();
  48021. let duration = performance.now() - start;
  48022. if(duration > 5){
  48023. break;
  48024. }
  48025. }
  48026. let duration = performance.now() - start;
  48027. }
  48028. let result = Potree.updateVisibility(pointclouds, camera, areaSize );
  48029. for (let pointcloud of pointclouds) {
  48030. //pointcloud.updateMaterial(pointcloud.material, pointcloud.visibleNodes, camera, renderer);//转移到渲染时
  48031. pointcloud.updateVisibleBounds();
  48032. }
  48033. Potree.lru.freeMemory();//即Potree.lru 能看到所有在加载的node
  48034. viewer.addTimeMark('updateClouds','end');
  48035. return result;
  48036. };
  48037. Potree.updateVisibilityStructures = function(pointclouds, camera, areaSize) {
  48038. let frustums = {};
  48039. let camObjPositions = {};
  48040. let camObjDirs = {}; //add
  48041. let priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });//二叉堆。
  48042. viewer.addTimeMark('visiStructure','start');
  48043. //camera.updateMatrixWorld();
  48044. let viewI = camera.matrixWorldInverse;
  48045. let proj = camera.projectionMatrix;
  48046. let view = camera.matrixWorld;
  48047. let projViewI = new Matrix4().multiply(proj).multiply(viewI);
  48048. /* let list = pointclouds // stopWhenAllUsed = !viewer.lastFrameChanged
  48049. let min = 5, max = Math.max(20 , Math.round(list.length / 10 ))
  48050. let result = Common.batchHandling.getSlice('pcGetFrustum', list, { min,max, durBound1: 3, durBound2: 10} ) //iphonex稳定后大概在7-10。
  48051. */
  48052. for (let i = 0; i < pointclouds.length; i++) {
  48053. let pointcloud = pointclouds[i];
  48054. if (!pointcloud.initialized()) {
  48055. continue;
  48056. }
  48057. /* let info = history.get(pointcloud)
  48058. if() */
  48059. pointcloud.numVisibleNodes = 0;
  48060. pointcloud.numVisiblePoints = 0;
  48061. pointcloud.deepestVisibleLevel = 0;
  48062. pointcloud.visibleNodes = [];
  48063. pointcloud.visibleGeometry = [];
  48064. // 因漫游模式而隐藏的话 依旧需要加入visibleNodes,因为pick需要
  48065. /* if (pointcloud.visible && pointcloud.root !== null) {
  48066. priorityQueue.push({pointcloud: i, node: pointcloud.root, weight: Number.MAX_VALUE});
  48067. } */
  48068. if (pointcloud.visible || !pointcloud.hasDepthTex && pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode' && pointcloud.root !== null) {//改 visible ->
  48069. priorityQueue.push({pointcloud: i, node: pointcloud.root, weight: Number.MAX_VALUE});
  48070. }else {
  48071. continue
  48072. }
  48073. // frustum in object space
  48074. let frustum = new Frustum();
  48075. let world = pointcloud.matrixWorld;
  48076. // use close near plane for frustum intersection
  48077. /* let frustumCam = camera.clone();
  48078. frustumCam.zoom = camera.zoom //add
  48079. frustumCam.near = Math.min(camera.near, 0.1);
  48080. frustumCam.updateProjectionMatrix(); */ //----没用到frustumCam,删了
  48081. let fm = new Matrix4().multiply(projViewI).multiply(world);
  48082. frustum.setFromProjectionMatrix(fm);
  48083. frustums[i] = frustum; //frustums.push(frustum);
  48084. // camera position in object space
  48085. let worldI = pointcloud.matrixWorldInverse;
  48086. let camMatrixObject = new Matrix4().multiply(worldI).multiply(view);//假设点云无变换的话,相机相对于点云的变换矩阵
  48087. let camObjPos = new Vector3().setFromMatrixPosition(camMatrixObject);
  48088. camObjPositions[i] = camObjPos;//camObjPositions.push(camObjPos);
  48089. let quaternion = new Quaternion().setFromRotationMatrix(camMatrixObject);
  48090. let camDir = (new Vector3(0,0,-1)).applyQuaternion(quaternion);
  48091. camObjDirs[i] = camDir;
  48092. // hide all previously visible nodes
  48093. // if(pointcloud.root instanceof PointCloudOctreeNode){
  48094. // pointcloud.hideDescendants(pointcloud.root.sceneNode);
  48095. // }
  48096. if (pointcloud.root.isTreeNode()) {
  48097. pointcloud.hideDescendants(pointcloud.root.sceneNode);
  48098. }
  48099. for (let j = 0; j < pointcloud.boundingBoxNodes.length; j++) {
  48100. pointcloud.boundingBoxNodes[j].visible = false;
  48101. }
  48102. }
  48103. viewer.addTimeMark('visiStructure','end');
  48104. return {
  48105. 'frustums': frustums,
  48106. 'camObjPositions': camObjPositions,
  48107. 'priorityQueue': priorityQueue,
  48108. camObjDirs
  48109. };
  48110. };
  48111. Potree.updateVisibility = function(pointclouds, camera, areaSize){
  48112. let numVisibleNodes = 0;
  48113. let numVisiblePoints = 0;
  48114. let numVisiblePointsInPointclouds = new Map(pointclouds.map(pc => [pc, 0]));
  48115. let visibleNodes = [];
  48116. let visibleGeometry = [];
  48117. let unloadedGeometry = [];
  48118. let lowestSpacing = Infinity;
  48119. // calculate object space frustum and cam pos and setup priority queue
  48120. let s = Potree.updateVisibilityStructures(pointclouds, camera, areaSize);//得到相机可见范围
  48121. let frustums = s.frustums;
  48122. let camObjPositions = s.camObjPositions;
  48123. let priorityQueue = s.priorityQueue;
  48124. let camObjDirs = s.camObjDirs;
  48125. let loadedToGPUThisFrame = 0;
  48126. let domWidth = areaSize.x; //renderer.domElement.clientWidth;
  48127. let domHeight = areaSize.y;//renderer.domElement.clientHeight;
  48128. let fov = (camera.fov * Math.PI) / 180;
  48129. let slope = Math.tan(fov / 2);
  48130. let projFactor0 = (0.5 * domHeight) / slope ;
  48131. // check if pointcloud has been transformed
  48132. // some code will only be executed if changes have been detected
  48133. if(!Potree._pointcloudTransformVersion){
  48134. Potree._pointcloudTransformVersion = new Map();
  48135. }
  48136. let pointcloudTransformVersion = Potree._pointcloudTransformVersion;
  48137. for(let pointcloud of pointclouds){
  48138. if(pointcloud.hasDepthTex ? !pointcloud.visible : !Potree.Utils.getObjVisiByReason(pointcloud, 'datasetSelection')){//改 visible ->
  48139. continue;
  48140. }
  48141. //if(!pointcloud.visible) continue
  48142. pointcloud.updateMatrixWorld();
  48143. if(!pointcloudTransformVersion.has(pointcloud)){
  48144. pointcloudTransformVersion.set(pointcloud, {number: 0, transform: pointcloud.matrixWorld.clone()});
  48145. }else {
  48146. let version = pointcloudTransformVersion.get(pointcloud);
  48147. if(!version.transform.equals(pointcloud.matrixWorld)){
  48148. version.number++;
  48149. version.transform.copy(pointcloud.matrixWorld);
  48150. pointcloud.dispatchEvent({
  48151. type: "transformation_changed",
  48152. target: pointcloud
  48153. });
  48154. }
  48155. }
  48156. }
  48157. while (priorityQueue.size() > 0) {
  48158. let element = priorityQueue.pop(); //取出权重最大的一个
  48159. let node = element.node;
  48160. let parent = element.parent;
  48161. let pointcloud = pointclouds[element.pointcloud];
  48162. // { // restrict to certain nodes for debugging
  48163. // let allowedNodes = ["r", "r0", "r4"];
  48164. // if(!allowedNodes.includes(node.name)){
  48165. // continue;
  48166. // }
  48167. // }
  48168. let box = node.getBoundingBox();
  48169. let frustum = frustums[element.pointcloud];
  48170. let camObjPos = camObjPositions[element.pointcloud];
  48171. if(!frustum) continue //add
  48172. let camObjDir = camObjDirs[element.pointcloud];
  48173. let insideFrustum = frustum.intersectsBox(box);
  48174. let maxLevel = pointcloud.maxLevel == void 0 ? Infinity : pointcloud.maxLevel;
  48175. let level = node.getLevel();
  48176. let visible = insideFrustum;
  48177. visible = visible && !(numVisiblePoints + node.getNumPoints() > Potree.pointBudget);
  48178. visible = visible && !(numVisiblePointsInPointclouds.get(pointcloud) + node.getNumPoints() > pointcloud.pointBudget); // pointcloud.pointBudget一直是Infinity
  48179. visible = visible && level <= maxLevel; //< 改为 <=
  48180. //visible = visible || node.getLevel() <= 2;
  48181. let intersectBox = (clipBox)=>{
  48182. let pcWorldInverse = pointcloud.matrixWorld.clone().invert();
  48183. let toPCObject = pcWorldInverse.multiply(clipBox.box.matrixWorld); //box乘上点云逆矩阵
  48184. /* let px = new THREE.Vector3(+0.5, 0, 0).applyMatrix4(pcWorldInverse);
  48185. let nx = new THREE.Vector3(-0.5, 0, 0).applyMatrix4(pcWorldInverse);
  48186. let py = new THREE.Vector3(0, +0.5, 0).applyMatrix4(pcWorldInverse);
  48187. let ny = new THREE.Vector3(0, -0.5, 0).applyMatrix4(pcWorldInverse);
  48188. let pz = new THREE.Vector3(0, 0, +0.5).applyMatrix4(pcWorldInverse);
  48189. let nz = new THREE.Vector3(0, 0, -0.5).applyMatrix4(pcWorldInverse);
  48190. let pxN = new THREE.Vector3().subVectors(nx, px).normalize();
  48191. let nxN = pxN.clone().multiplyScalar(-1);
  48192. let pyN = new THREE.Vector3().subVectors(ny, py).normalize();
  48193. let nyN = pyN.clone().multiplyScalar(-1);
  48194. let pzN = new THREE.Vector3().subVectors(nz, pz).normalize();
  48195. let nzN = pzN.clone().multiplyScalar(-1);
  48196. let pxPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(pxN, px);
  48197. let nxPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(nxN, nx);
  48198. let pyPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(pyN, py);
  48199. let nyPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(nyN, ny);
  48200. let pzPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(pzN, pz);
  48201. let nzPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(nzN, nz);
  48202. //if(window.debugdraw !== undefined && window.debugdraw === true && node.name === "r60"){
  48203. // Potree.utils.debugPlane(viewer.scene.scene, pxPlane, 1, 0xFF0000);
  48204. // Potree.utils.debugPlane(viewer.scene.scene, nxPlane, 1, 0x990000);
  48205. // Potree.utils.debugPlane(viewer.scene.scene, pyPlane, 1, 0x00FF00);
  48206. // Potree.utils.debugPlane(viewer.scene.scene, nyPlane, 1, 0x009900);
  48207. // Potree.utils.debugPlane(viewer.scene.scene, pzPlane, 1, 0x0000FF);
  48208. // Potree.utils.debugPlane(viewer.scene.scene, nzPlane, 1, 0x000099);
  48209. // Potree.utils.debugBox(viewer.scene.scene, box, new THREE.Matrix4(), 0x00FF00);
  48210. // Potree.utils.debugBox(viewer.scene.scene, box, pointcloud.matrixWorld, 0xFF0000);
  48211. // Potree.utils.debugBox(viewer.scene.scene, clipBox.box.boundingBox, clipBox.box.matrixWorld, 0xFF0000);
  48212. // window.debugdraw = false;
  48213. //}
  48214. let frustum = new THREE.Frustum(pxPlane, nxPlane, pyPlane, nyPlane, pzPlane, nzPlane);
  48215. let intersects = frustum.intersectsBox(box); //node的bounding
  48216. return !!intersects */
  48217. return Potree.Utils.isIntersectBox(box, toPCObject)
  48218. };
  48219. //改 总共两种box : 可见和不可见(都是并集)
  48220. let clipBoxes_in = pointcloud.material.clipBoxes_in;
  48221. let clipBoxes_out = pointcloud.material.clipBoxes_out;
  48222. let bigClipInBox = pointcloud.material.bigClipInBox;
  48223. if(visible && bigClipInBox){//不在剪裁下载的框内
  48224. if(!intersectBox(bigClipInBox)){
  48225. visible = false;
  48226. }
  48227. }
  48228. if(visible && clipBoxes_in.length > 0){//当有可见box时,需要在任一可见box内才可见
  48229. let visi = false;
  48230. for(let i = 0, length=clipBoxes_in.length; i < length; i++){
  48231. if(intersectBox(clipBoxes_in[i])){
  48232. visi = true;
  48233. break;
  48234. }
  48235. }
  48236. if(!visi){
  48237. visible = false;
  48238. }
  48239. }
  48240. //outside不做处理。因为node必须完全在clipBox内才能完全隐藏,而这里的intersect只能识别出部分在clipBox内。因而只能说明不在任意一个box内绝对可见,没有意义,这里需要找出不可见的。
  48241. /* if(visible && clipBoxes_out.length > 0){ //当有不可见box时,不在所有不可见box内才可见
  48242. let visi = true;
  48243. for(let i = 0,length=clipBoxes_out.length; i < length; i++){
  48244. if(intersectBox(clipBoxes_out[i])){
  48245. visi = false;
  48246. break;
  48247. }
  48248. }
  48249. if(!visi){
  48250. visible = false
  48251. }
  48252. }
  48253. */
  48254. // visible = ["r", "r0", "r06", "r060"].includes(node.name);
  48255. // visible = ["r"].includes(node.name);
  48256. if (node.spacing) {
  48257. lowestSpacing = Math.min(lowestSpacing, node.spacing);
  48258. } else if (node.geometryNode && node.geometryNode.spacing) {
  48259. lowestSpacing = Math.min(lowestSpacing, node.geometryNode.spacing);
  48260. }
  48261. if (numVisiblePoints + node.getNumPoints() > Potree.pointBudget) {
  48262. break;
  48263. }
  48264. if (!visible) {
  48265. continue;
  48266. }
  48267. // TODO: not used, same as the declaration?
  48268. // numVisibleNodes++;
  48269. numVisiblePoints += node.getNumPoints();
  48270. let numVisiblePointsInPointcloud = numVisiblePointsInPointclouds.get(pointcloud);
  48271. numVisiblePointsInPointclouds.set(pointcloud, numVisiblePointsInPointcloud + node.getNumPoints());
  48272. pointcloud.numVisibleNodes++;
  48273. pointcloud.numVisiblePoints += node.getNumPoints();
  48274. if (node.isGeometryNode() && (!parent || parent.isTreeNode())) {
  48275. if (node.isLoaded() && loadedToGPUThisFrame < 2) {
  48276. node = pointcloud.toTreeNode(node, parent);
  48277. loadedToGPUThisFrame++;
  48278. } else {
  48279. //console.log('unloadedGeometry',node)
  48280. unloadedGeometry.push({pointcloud,node}); //加载点云。虽然还没加载,但也计入了visibleNodes,只是无children,numPoints=0
  48281. visibleGeometry.push(node);
  48282. }
  48283. }
  48284. if (node.isTreeNode()) {
  48285. Potree.lru.touch(node.geometryNode);//在缓存中计入点云
  48286. node.sceneNode.visible = true;
  48287. node.sceneNode.material = pointcloud.material;
  48288. visibleNodes.push(node);
  48289. pointcloud.visibleNodes.push(node);
  48290. if(node._transformVersion === undefined){
  48291. node._transformVersion = -1;
  48292. }
  48293. let transformVersion = pointcloudTransformVersion.get(pointcloud);
  48294. if(node._transformVersion !== transformVersion.number){
  48295. node.sceneNode.updateMatrix();
  48296. //node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  48297. node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  48298. node._transformVersion = transformVersion.number;
  48299. }
  48300. if (pointcloud.showBoundingBox && !node.boundingBoxNode && node.getBoundingBox) {
  48301. let colorHue = level / (maxLevel+1);
  48302. let s = 0.1 + level / (maxLevel+1);
  48303. let color = (new Color()).setHSL(colorHue, s, s);
  48304. let boxHelper = new Box3Helper$1(node.getBoundingBox(),color);
  48305. boxHelper.matrixAutoUpdate = false;
  48306. pointcloud.boundingBoxNodes.push(boxHelper);
  48307. node.boundingBoxNode = boxHelper;
  48308. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  48309. } else if (pointcloud.showBoundingBox) {
  48310. node.boundingBoxNode.visible = true;
  48311. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  48312. } else if (!pointcloud.showBoundingBox && node.boundingBoxNode) {
  48313. node.boundingBoxNode.visible = false;
  48314. }
  48315. // if(node.boundingBoxNode !== undefined && exports.debug.allowedNodes !== undefined){
  48316. // if(!exports.debug.allowedNodes.includes(node.name)){
  48317. // node.boundingBoxNode.visible = false;
  48318. // }
  48319. // }
  48320. }
  48321. // add child nodes to priorityQueue 由近及远、由大及小逐渐加载
  48322. let children = node.getChildren();
  48323. for (let i = 0; i < children.length; i++) {
  48324. let child = children[i];
  48325. let weight = 0;
  48326. if(camera.isPerspectiveCamera){
  48327. let sphere = child.getBoundingSphere();
  48328. let center = sphere.center;
  48329. let dd = sphere.center.distanceToSquared(camObjPos);
  48330. let addPow = 0.2;//viewer.mainViewport.view.isFlying() ? 0 : 0.5 //0-0.5,正常原本是0. 数字越大近处加载越快。但会造成远处加载慢甚至因pointBudge限制不加载。 isFlying:漫游时需要尽量加载一下远处的点云
  48331. //addPow *= window.devicePixelRatio //devicePixelRatio高的手机需要优先加载最近的高级点云,减少远处的中高级点云。
  48332. let distance = Math.pow(dd,0.5+addPow);//Math.sqrt(dd); //提高距离权重,为了提高近处加载速度。 某些场景近处加载慢优化明显,如SS-t-cqCAL6rJ5i
  48333. //let attenuateDis = 10;//add
  48334. let radius = sphere.radius;
  48335. let projFactor = projFactor0 / distance;
  48336. let screenPixelRadius = radius * projFactor;
  48337. /* if(distance > attenuateDis){
  48338. screenPixelRadius -= (distance - attenuateDis) * Math.sqrt(radius) * projFactor0 * 0.002
  48339. } */
  48340. //screenPixelRadius 和 domHeight 成正比,所以手机横屏后screenPixelRadius会变小。这是正常的,因为vhov不变,相同物体高度在横屏后高度变小,所需要的密度不需要那么高了。但hfov横屏后扩大,所以可见的node范围变大,又增加了一些可见node;只是总体的可见node还是减少了。
  48341. //使用hfov和domWidth计算结果相同。
  48342. if(screenPixelRadius < pointcloud.minimumNodePixelSize / Math.pow(dd,addPow)){ //理论上因手机像素小,更不容易堆叠铺满,minimumNodePixelSize应该除以window.deviceRatio 但会造成加载过多,而内存小
  48343. continue;
  48344. }
  48345. weight = screenPixelRadius;
  48346. if( !sphere.containsPoint(camObjPos) ){ //add 优先加载屏幕中央的点云(手机端缩小离远效果明显,不会那么稀疏)
  48347. let dir = new Vector3().subVectors(center, camObjPos).normalize();
  48348. let cos = 1+dir.dot(camObjDir); //0-2
  48349. weight *= cos/2;//Math.pow(cos,0.5) //幂越高,旁边的容易加载不到,出现缺块 如SS-t-7DUfWAUZ3V
  48350. }
  48351. if(distance - radius < 0){
  48352. weight = Number.MAX_VALUE;
  48353. }
  48354. //如果能得到每个方向上的密度,也就是node数量,密度大的远处少加载,因为被遮挡了显示也没有意义,就好了。
  48355. } else {
  48356. // TODO ortho visibility
  48357. //let bb = child.getBoundingBox();
  48358. let sphere = child.getBoundingSphere();
  48359. //let diagonal = bb.max.clone().sub(bb.min).length();
  48360. const reduce = 0; //0-0.5,正常原本是0.
  48361. if( sphere.radius * /* Math.pow( */camera.zoom/* ,1-reduce) */ < pointcloud.minimumNodePixelSize ){
  48362. continue;
  48363. }
  48364. let distance = sphere.center.distanceToSquared(camObjPos); //先加载中间然后四周
  48365. weight = sphere.radius / distance;
  48366. //weight = diagonal;
  48367. }
  48368. priorityQueue.push({pointcloud: element.pointcloud, node: child, parent: node, weight: weight}); //貌似好像二叉堆中子节点和父节点没什么关系,就只是为了方便排序层层遍历
  48369. }
  48370. //手机上像素点更小,所以远处感觉会更稀疏
  48371. }// end priority queue loop
  48372. { // update DEM 这是什么
  48373. let maxDEMLevel = 4;
  48374. let candidates = pointclouds.filter(p => (p.generateDEM && p.dem instanceof Potree.DEM));
  48375. for (let pointcloud of candidates) {
  48376. let updatingNodes = pointcloud.visibleNodes.filter(n => n.getLevel() <= maxDEMLevel);
  48377. pointcloud.dem.update(updatingNodes);
  48378. }
  48379. }
  48380. if(unloadedGeometry.length){//加载点云
  48381. /* for (let i = 0; i < Math.min(Potree.maxNodesLoading, unloadedGeometry.length); i++) {
  48382. unloadedGeometry[i].node.load(unloadedGeometry[i].pointcloud.pcoGeometry);
  48383. } */
  48384. let maxNodesLoading = Common$1.getBestCount('unloadedGeometry', viewer.lastFrameChanged?1:3, 6, 4, 15 /* , true */ );//dur在iphoneX中静止有7,pc是2 //!lastFrameChanged静止时加速下载
  48385. //THREE.Math.clamp(Math.round(9 - dur), 1, 6 )
  48386. //console.log('unloadedGeometry', unloadedGeometry.length)
  48387. //主要在手机端有效果。不改之前在展示的点云较多时前进会卡。
  48388. for (let i = 0; i < Math.min(maxNodesLoading, unloadedGeometry.length); i++) {
  48389. unloadedGeometry[i].node.load(unloadedGeometry[i].pointcloud.pcoGeometry);
  48390. }
  48391. if(!Potree.pointsLoading){
  48392. Potree.pointsLoading = true;
  48393. //console.log('startLoad')
  48394. viewer.dispatchEvent('startLoadPoints');
  48395. }
  48396. }else {
  48397. if(Potree.pointsLoading){
  48398. Potree.pointsLoading = false;
  48399. //console.log('load done!')
  48400. setTimeout(()=>{
  48401. Potree.pointsLoading || viewer.dispatchEvent('pointsLoaded');
  48402. },document.hidden ? 3000 : 50); //hidden时可能好几秒才更新一次,所以这个并不准
  48403. }
  48404. }
  48405. //add:
  48406. Potree.numVisiblePoints = numVisiblePoints;
  48407. return {
  48408. visibleNodes: visibleNodes,
  48409. numVisiblePoints: numVisiblePoints,
  48410. lowestSpacing: lowestSpacing
  48411. };
  48412. };
  48413. Potree.numVisiblePoints = 0;
  48414. /*
  48415. note:
  48416. 缓存中的点数 Potree.lru.numPoints 一般会 大于 每个点云显示点总数的numVisiblePoints
  48417. 当超出缓冲区最大点云数时,加载的点云节点会被dispose彻底消除;否则,隐藏的节点就会等待再次被使用显示
  48418. 由于加载按照由近及远、由大及小的顺序,要降低卡顿,就只需要降低Potree.pointBudget即可。但目前只设置了三个层次;另外提供maxLevel细节调节,能显示更均匀. 最好多一个调节pointBudge的滑动条
  48419. Potree.lru.numPoints
  48420. Potree.numVisiblePoints
  48421. viewer.scene.pointclouds[0].visibleNodes.length
  48422. */
  48423. {//HQSplatRenderer
  48424. let oldInit = HQSplatRenderer.prototype.init;
  48425. HQSplatRenderer.prototype.init = function(){
  48426. oldInit();
  48427. viewer.addEventListener('resize',this.resize.bind(this));
  48428. };
  48429. HQSplatRenderer.prototype.resize = function(e){
  48430. this.rtDepth.setSize(e.canvasWidth, e.canvasHeight);
  48431. this.rtAttribute.setSize(e.canvasWidth, e.canvasHeight);
  48432. };
  48433. HQSplatRenderer.prototype.clear = function(params={}){
  48434. this.init();
  48435. const {renderer, background} = this.viewer;
  48436. if(background === "skybox"){
  48437. renderer.setClearColor(0x000000, 0);
  48438. } else if (background === 'gradient') {
  48439. renderer.setClearColor(0x000000, 0);
  48440. } else if (background === 'black') {
  48441. renderer.setClearColor(0x000000, 1);
  48442. } else if (background === 'white') {
  48443. renderer.setClearColor(0xFFFFFF, 1);
  48444. } else {
  48445. renderer.setClearColor(0x000000, 0);
  48446. }
  48447. params.target || renderer.clear();
  48448. this.clearTargets(params);
  48449. };
  48450. HQSplatRenderer.prototype.render = function(params={}) {
  48451. this.init();
  48452. const viewer = this.viewer;
  48453. const camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  48454. const {width, height} = params.width ? params : this.viewer.renderer.getSize(new Vector2());
  48455. viewer.renderer.setRenderTarget(params.target||null);
  48456. viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  48457. //params.target || this.resize(width, height);
  48458. const visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible);
  48459. const originalMaterials = new Map();
  48460. for(let pointcloud of visiblePointClouds){
  48461. originalMaterials.set(pointcloud, pointcloud.material);
  48462. if(!this.attributeMaterials.has(pointcloud)){
  48463. let attributeMaterial = new ExtendPointCloudMaterial();
  48464. this.attributeMaterials.set(pointcloud, attributeMaterial);
  48465. }
  48466. if(!this.depthMaterials.has(pointcloud)){
  48467. let depthMaterial = new ExtendPointCloudMaterial();
  48468. depthMaterial.setDefine("depth_pass", "#define hq_depth_pass");
  48469. depthMaterial.setDefine("use_edl", "#define use_edl");
  48470. this.depthMaterials.set(pointcloud, depthMaterial);
  48471. }
  48472. }
  48473. { // DEPTH PASS
  48474. for (let pointcloud of visiblePointClouds) {
  48475. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  48476. let material = originalMaterials.get(pointcloud);
  48477. let depthMaterial = this.depthMaterials.get(pointcloud);
  48478. depthMaterial.size = material.size;
  48479. depthMaterial.minSize = material.minSize;
  48480. depthMaterial.maxSize = material.maxSize;
  48481. depthMaterial.pointSizeType = material.pointSizeType;
  48482. depthMaterial.visibleNodesTexture = material.visibleNodesTexture;
  48483. depthMaterial.weighted = false;
  48484. depthMaterial.screenWidth = width;
  48485. depthMaterial.shape = PointShape.CIRCLE;
  48486. depthMaterial.screenHeight = height;
  48487. depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  48488. depthMaterial.uniforms.octreeSize.value = octreeSize;
  48489. depthMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  48490. depthMaterial.classification = material.classification;
  48491. depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  48492. depthMaterial.classificationTexture.needsUpdate = true;
  48493. depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  48494. depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  48495. depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  48496. depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  48497. depthMaterial.clipTask = material.clipTask;
  48498. depthMaterial.clipMethod = material.clipMethod;
  48499. depthMaterial.setClipBoxes(material.clipBoxes);
  48500. depthMaterial.setClipPolygons(material.clipPolygons);
  48501. pointcloud.material = depthMaterial;
  48502. }
  48503. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, (params.rtEDL || this.rtDepth), {
  48504. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  48505. });
  48506. }
  48507. { // ATTRIBUTE PASS
  48508. for (let pointcloud of visiblePointClouds) {
  48509. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  48510. let material = originalMaterials.get(pointcloud);
  48511. let attributeMaterial = this.attributeMaterials.get(pointcloud);
  48512. attributeMaterial.size = material.size;
  48513. attributeMaterial.minSize = material.minSize;
  48514. attributeMaterial.maxSize = material.maxSize;
  48515. attributeMaterial.pointSizeType = material.pointSizeType;
  48516. attributeMaterial.activeAttributeName = material.activeAttributeName;
  48517. attributeMaterial.visibleNodesTexture = material.visibleNodesTexture;
  48518. attributeMaterial.weighted = true;
  48519. attributeMaterial.screenWidth = width;
  48520. attributeMaterial.screenHeight = height;
  48521. attributeMaterial.shape = PointShape.CIRCLE;
  48522. attributeMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  48523. attributeMaterial.uniforms.octreeSize.value = octreeSize;
  48524. attributeMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  48525. attributeMaterial.classification = material.classification;
  48526. attributeMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  48527. attributeMaterial.classificationTexture.needsUpdate = true;
  48528. attributeMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  48529. attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  48530. attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  48531. attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  48532. attributeMaterial.elevationGradientRepeat = material.elevationGradientRepeat;
  48533. attributeMaterial.elevationRange = material.elevationRange;
  48534. attributeMaterial.gradient = material.gradient;
  48535. attributeMaterial.matcap = material.matcap;
  48536. attributeMaterial.intensityRange = material.intensityRange;
  48537. attributeMaterial.intensityGamma = material.intensityGamma;
  48538. attributeMaterial.intensityContrast = material.intensityContrast;
  48539. attributeMaterial.intensityBrightness = material.intensityBrightness;
  48540. attributeMaterial.rgbGamma = material.rgbGamma;
  48541. attributeMaterial.rgbContrast = material.rgbContrast;
  48542. attributeMaterial.rgbBrightness = material.rgbBrightness;
  48543. attributeMaterial.weightRGB = material.weightRGB;
  48544. attributeMaterial.weightIntensity = material.weightIntensity;
  48545. attributeMaterial.weightElevation = material.weightElevation;
  48546. attributeMaterial.weightRGB = material.weightRGB;
  48547. attributeMaterial.weightClassification = material.weightClassification;
  48548. attributeMaterial.weightReturnNumber = material.weightReturnNumber;
  48549. attributeMaterial.weightSourceID = material.weightSourceID;
  48550. attributeMaterial.color = material.color;
  48551. attributeMaterial.clipTask = material.clipTask;
  48552. attributeMaterial.clipMethod = material.clipMethod;
  48553. attributeMaterial.setClipBoxes(material.clipBoxes);
  48554. attributeMaterial.setClipPolygons(material.clipPolygons);
  48555. pointcloud.material = attributeMaterial;
  48556. }
  48557. let gl = this.gl;
  48558. //viewer.renderer.setRenderTarget(null);
  48559. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, {
  48560. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  48561. //material: this.attributeMaterial,
  48562. blendFunc: [gl.SRC_ALPHA, gl.ONE],
  48563. //depthTest: false,
  48564. depthWrite: false
  48565. });
  48566. }
  48567. for(let [pointcloud, material] of originalMaterials){
  48568. pointcloud.material = material;
  48569. }
  48570. if(viewer.background === "skybox"){
  48571. viewer.renderer.setClearColor(0x000000, 0);
  48572. viewer.renderer.clear();
  48573. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  48574. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  48575. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  48576. viewer.skybox.parent.rotation.x = 0;
  48577. viewer.skybox.parent.updateMatrixWorld();
  48578. viewer.skybox.camera.updateProjectionMatrix();
  48579. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  48580. } else if (viewer.background === 'gradient') {
  48581. viewer.renderer.setClearColor(0x000000, 0);
  48582. viewer.renderer.clear();
  48583. viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  48584. } else if (viewer.background === 'black') {
  48585. viewer.renderer.setClearColor(0x000000, 1);
  48586. viewer.renderer.clear();
  48587. } else if (viewer.background === 'white') {
  48588. viewer.renderer.setClearColor(0xFFFFFF, 1);
  48589. viewer.renderer.clear();
  48590. } else {
  48591. viewer.renderer.setClearColor(0x000000, 0);
  48592. viewer.renderer.clear();
  48593. }
  48594. { // NORMALIZATION PASS
  48595. let normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial;
  48596. if(this.useEDL){
  48597. normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength;
  48598. normalizationMaterial.uniforms.radius.value = viewer.edlRadius;
  48599. normalizationMaterial.uniforms.screenWidth.value = width;
  48600. normalizationMaterial.uniforms.screenHeight.value = height;
  48601. normalizationMaterial.uniforms.uEDLMap.value = (params.rtEDL || this.rtDepth).texture;
  48602. }
  48603. normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture;
  48604. normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture;
  48605. Utils.screenPass.render(viewer.renderer, normalizationMaterial);
  48606. }
  48607. viewer.renderer.render(viewer.scene.scene, camera);
  48608. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  48609. viewer.renderer.render(viewer.scene.sceneOverlay, camera);// add 透明贴图层
  48610. viewer.renderer.clearDepth();
  48611. viewer.transformationTool.update();
  48612. if(!params.target){
  48613. //测量线
  48614. viewer.dispatchEvent({type: "render.pass.perspective_overlay",viewer: viewer, camera});
  48615. viewer.renderer.render(viewer.overlay, camera);//从 viewer.renderDefault搬过来,为了reticule不遮住测量线
  48616. }
  48617. viewer.renderer.render(viewer.controls.sceneControls, camera);
  48618. viewer.renderer.render(viewer.clippingTool.sceneVolume, camera);
  48619. viewer.renderer.render(viewer.transformationTool.scene, camera);
  48620. viewer.renderer.setViewport(width - viewer.navigationCube.width,
  48621. height - viewer.navigationCube.width,
  48622. viewer.navigationCube.width, viewer.navigationCube.width);
  48623. viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  48624. viewer.renderer.setViewport(0, 0, width, height);
  48625. viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  48626. viewer.renderer.setRenderTarget(null);
  48627. };
  48628. }
  48629. //PointCloudOctreeGeometry.js
  48630. PointCloudOctreeGeometryNode.prototype.loadHierachyThenPoints = function(pointcloud){
  48631. let node = this;
  48632. // load hierarchy
  48633. let callback = function (node, hbuffer) {
  48634. let tStart = performance.now();
  48635. let view = new DataView(hbuffer);
  48636. let stack = [];
  48637. let children = view.getUint8(0);
  48638. let numPoints = view.getUint32(1, true);
  48639. node.numPoints = numPoints;
  48640. stack.push({children: children, numPoints: numPoints, name: node.name});
  48641. let decoded = [];
  48642. let offset = 5;
  48643. while (stack.length > 0) {
  48644. let snode = stack.shift();
  48645. let mask = 1;
  48646. for (let i = 0; i < 8; i++) {
  48647. if ((snode.children & mask) !== 0) {
  48648. let childName = snode.name + i;
  48649. let childChildren = view.getUint8(offset);
  48650. let childNumPoints = view.getUint32(offset + 1, true);
  48651. stack.push({children: childChildren, numPoints: childNumPoints, name: childName});
  48652. decoded.push({children: childChildren, numPoints: childNumPoints, name: childName});
  48653. offset += 5;
  48654. }
  48655. mask = mask * 2;
  48656. }
  48657. if (offset === hbuffer.byteLength) {
  48658. break;
  48659. }
  48660. }
  48661. // console.log(decoded);
  48662. let nodes = {};
  48663. nodes[node.name] = node;
  48664. let pco = node.pcoGeometry;
  48665. let maxLevel_ = 0;
  48666. for (let i = 0; i < decoded.length; i++) {
  48667. let name = decoded[i].name;
  48668. let decodedNumPoints = decoded[i].numPoints;
  48669. let index = parseInt(name.charAt(name.length - 1));
  48670. let parentName = name.substring(0, name.length - 1);
  48671. let parentNode = nodes[parentName];
  48672. let level = name.length - 1;
  48673. maxLevel_ = Math.max(maxLevel_,level);//add
  48674. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  48675. let currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  48676. currentNode.level = level;
  48677. currentNode.numPoints = decodedNumPoints;
  48678. currentNode.hasChildren = decoded[i].children > 0;
  48679. currentNode.spacing = pco.spacing / Math.pow(2, level);
  48680. parentNode.addChild(currentNode);
  48681. nodes[name] = currentNode;
  48682. }
  48683. pco.dispatchEvent({type:'updateNodeMaxLevel',level:maxLevel_});//add
  48684. let duration = performance.now() - tStart;
  48685. if(duration > 5){
  48686. /* let msg = `duration: ${duration}ms, numNodes: ${decoded.length}`;
  48687. console.log(msg); */
  48688. }
  48689. node.loadPoints();
  48690. };
  48691. if ((node.level % node.pcoGeometry.hierarchyStepSize) === 0) {
  48692. // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc";
  48693. let hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc';
  48694. hurl += '?m='+node.pcoGeometry.timeStamp; //add
  48695. let xhr = XHRFactory.createXMLHttpRequest();
  48696. xhr.open('GET', hurl, true);
  48697. xhr.responseType = 'arraybuffer';
  48698. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  48699. xhr.onreadystatechange = () => {
  48700. if (xhr.readyState === 4) {
  48701. if (xhr.status === 200 || xhr.status === 0) {
  48702. let hbuffer = xhr.response;
  48703. callback(node, hbuffer);
  48704. } else {
  48705. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl);
  48706. Potree.numNodesLoading--;
  48707. }
  48708. }
  48709. };
  48710. try {
  48711. xhr.send(null);
  48712. } catch (e) {
  48713. console.log('fehler beim laden der punktwolke: ' + e);
  48714. }
  48715. }
  48716. };
  48717. PointCloudOctreeGeometryNode.prototype.loadPoints = function(){
  48718. let name = this.name;
  48719. this.pcoGeometry.loader.load(this, ()=>{//callback
  48720. viewer.dispatchEvent('pointcloud_changed');
  48721. //console.log('loadPoints success ', name)
  48722. });
  48723. };
  48724. //加载点云成功->准备渲染画面->更新点云可见性updateVisibility->请求加载新的点云
  48725. PointCloudOctreeGeometryNode.prototype.traverse = function(t, e){//add from navvis 25.js
  48726. void 0 === e && (e = !0);
  48727. for (var n, i = e ? [this] : []; void 0 !== (n = i.pop()); ) {
  48728. t(n);
  48729. for (var o = 0, r = n.children; o < r.length; o++) {
  48730. var a = r[o];
  48731. null !== a && i.push(a);
  48732. }
  48733. }
  48734. };
  48735. Object.assign( PointCloudOctreeGeometry.prototype, EventDispatcher.prototype );
  48736. LRU.prototype.freeMemory = function(){
  48737. if (this.elements <= 1) {
  48738. return;
  48739. }
  48740. let memoryRatio = browser.isMobile() ? 2 : 5;
  48741. //改成navvis的,使用pointBudget,否则四屏点云闪烁。 (似乎要比updateVisiblede的node时限制要宽些,作为缓存继续存着。否则会闪烁)
  48742. let max = MathUtils.clamp( viewer.viewports.length * memoryRatio * Potree.pointBudget, 1e6, 40e6);
  48743. for (; this.numPoints > max; ) {
  48744. var node = this.getLRUItem();
  48745. node && this.disposeDescendants(node); //this.disposeSubtree(node)
  48746. }
  48747. };
  48748. /*
  48749. LRU.prototype.disposeSubtree = function(t) {//add from navvis 25.js 和原来的disposeDescendants功能一样
  48750. var e = [t];
  48751. t.traverse((function(t) {
  48752. t.loaded && e.push(t)
  48753. }));
  48754. for (var n = 0, i = e; n < i.length; n++) {
  48755. var o = i[n];
  48756. o.dispose(),
  48757. this.remove(o)
  48758. }
  48759. }*/
  48760. VolumeTool.prototype.update = function(){};
  48761. VolumeTool.prototype.startInsertion = function(args = {}){
  48762. let volume;
  48763. if(args.type){
  48764. volume = new args.type();
  48765. }else {
  48766. volume = new Potree.BoxVolume(Object.assign(args,{clip:true}) );
  48767. }
  48768. volume.highlight = true;
  48769. volume.name = args.name || 'Volume-'+args.clipTask;
  48770. volume.isNew = true;
  48771. viewer.transformObject(null);//先清空
  48772. //console.log('startInsertion',volume.uuid)
  48773. let oldVisiBoxes;
  48774. if(args.clipTask == Potree.ClipTask.SHOW_INSIDE){ //如果是显示类型,需要将所有同类型的解除效果,否则看不到效果。 (或者可以在添加非第一个时去除highlight效果,会更自然,但看不清全貌)
  48775. oldVisiBoxes = viewer.scene.volumes.filter(v => v.clipTask == Potree.ClipTask.SHOW_INSIDE && !v.highlight );
  48776. oldVisiBoxes.forEach(box=>box.highlight = true);
  48777. }
  48778. let updatePose = ()=>{ //保证在视野中的大小一致:
  48779. let camera = this.viewer.scene.getActiveCamera();
  48780. let w = math.getScaleForConstantSize({
  48781. width2d: 300,
  48782. camera , position:volume.getWorldPosition(new Vector3()) ,
  48783. resolution: viewer.mainViewport.resolution//2
  48784. });
  48785. /* let wp = volume.getWorldPosition(new THREE.Vector3()).applyMatrix4(camera.matrixWorldInverse);
  48786. // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix);
  48787. let w = Math.abs((wp.z / 3));*/
  48788. if(!isNaN(w))volume.scale.set(w, w, w);
  48789. {//使水平朝向与camera一致
  48790. let direction = viewer.mainViewport.view.direction.setZ(0);
  48791. volume.quaternion.copy(math.getQuaByAim(direction));
  48792. }
  48793. };
  48794. this.dispatchEvent({
  48795. type: 'start_inserting_volume',
  48796. volume: volume
  48797. });
  48798. updatePose();
  48799. this.viewer.scene.addVolume(volume);
  48800. this.scene.add(volume);
  48801. let drag = e => {
  48802. let I = Utils.getMousePointCloudIntersection(
  48803. viewer.mainViewport,
  48804. viewer.inputHandler.mouse,
  48805. viewer.inputHandler.pointer,
  48806. this.viewer.scene.getActiveCamera(),
  48807. this.viewer,
  48808. this.viewer.scene.pointclouds,
  48809. {pickClipped: args.clipTask == Potree.ClipTask.SHOW_OUTSIDE } //无视clip状态
  48810. );
  48811. var worldPos = I && I.location;
  48812. if(!worldPos){
  48813. return
  48814. }
  48815. volume.position.copy(worldPos);
  48816. updatePose();
  48817. };
  48818. let cancel = ()=>{
  48819. end('remove');
  48820. };
  48821. let end = (e) => {
  48822. if(e.button == MOUSE.RIGHT && e.pressDistance<=Potree.config.clickMaxDragDis) {//remove
  48823. e = 'remove';
  48824. }
  48825. //console.log('end',volume.uuid, e)
  48826. if(e != 'remove' && (!e.isAtDomElement || e.pressDistance>Potree.config.clickMaxDragDis))return continueDrag()
  48827. volume.removeEventListener('drag', drag);
  48828. volume.removeEventListener('drop', end);
  48829. this.viewer.removeEventListener('cancel_insertions', cancel);
  48830. volume.isNew = false;
  48831. viewer.removeEventListener('camera_changed', updatePose);
  48832. if(e == 'remove'){
  48833. viewer.scene.removeVolume(volume); //删除没完成的
  48834. }else {
  48835. viewer.transformObject(volume);
  48836. volume.highlight = false;
  48837. }
  48838. volume.dispatchEvent({type:'createFinish', success:e != 'remove' });
  48839. oldVisiBoxes && oldVisiBoxes.forEach(box=>box.highlight = false);
  48840. };
  48841. let continueDrag = ( )=>{
  48842. //console.log('continueDrag',volume.uuid )
  48843. var timer = setTimeout(()=>{//等 drag=null之后 //右键拖拽结束后需要重新得到drag
  48844. if(volume.parent && volume.isNew){
  48845. viewer.inputHandler.startDragging( volume , {notPressMouse:true}
  48846. /* {endDragFun: e.drag.endDragFun, notPressMouse:e.drag.notPressMouse, dragViewport:e.drag.dragViewport} */
  48847. );
  48848. }
  48849. },1);
  48850. return timer
  48851. };
  48852. volume.addEventListener('drag', drag);
  48853. volume.addEventListener('drop', end);
  48854. this.viewer.addEventListener('cancel_insertions', cancel);
  48855. viewer.addEventListener('camera_changed', updatePose);
  48856. this.viewer.inputHandler.startDragging(volume, {notPressMouse:true});
  48857. return volume;
  48858. };
  48859. LineGeometry.prototype.setPositions = function( array ) { //xzw改成类似LineSegments的多段线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序)
  48860. const points = new Float32Array( array );
  48861. LineSegmentsGeometry.prototype.setPositions.call(this, points );
  48862. return this;
  48863. };
  48864. Object.assign(ExtendView.prototype, EventDispatcher.prototype);
  48865. Object.assign(ExtendScene.prototype, EventDispatcher.prototype );
  48866. function start(dom, mapDom, number ){ //t-Zvd3w0m
  48867. /* {
  48868. let obj = JSON.parse(localStorage.getItem('setting'))
  48869. for(let i in obj){
  48870. console.log(i + ': ' + obj[i])
  48871. }
  48872. }
  48873. */
  48874. Potree.settings.number = number || 't-o5YMR13';// 't-iksBApb'// 写在viewer前
  48875. if(!Potree.settings.isOfficial){
  48876. if(/* Potree.settings.isTest && */ browser.isMobile()){
  48877. changeLog();
  48878. }
  48879. }
  48880. if(browser.urlHasValue('google'))Potree.settings.mapCompany = 'google';
  48881. if(browser.urlHasValue('timing'))Potree.measureTimings = 1;
  48882. let viewer = new Potree.Viewer(dom , mapDom);
  48883. let Alignment = viewer.modules.Alignment;
  48884. viewer.setEDLEnabled(false);
  48885. viewer.setFOV(Potree.config.view.fov);
  48886. //viewer.loadSettingsFromURL();
  48887. Potree.settings.cameraFar = Potree.config.view.far;
  48888. if(!Potree.settings.isOfficial){
  48889. viewer.loadGUI(() => {
  48890. viewer.setLanguage('en');
  48891. //$("#menu_appearance").next().show();
  48892. $("#menu_tools").next().show();
  48893. $("#menu_scene").next().show();
  48894. $("#siteModel").show();
  48895. //$("#alignment").show();
  48896. viewer.toggleSidebar();
  48897. });
  48898. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  48899. Potree.settings.rotAroundPoint = false;
  48900. }
  48901. Potree.loadDatasetsCallback = function(data, ifReload){
  48902. if(!data || data.length == 0)return console.error('getDataSet加载的数据为空')
  48903. Potree.datasetData = data;
  48904. viewer.transform = null;
  48905. var datasetLength = data.length;
  48906. var pointcloudLoaded = 0;
  48907. var panosLoaded = 0;
  48908. var pointcloudLoadDone = function(){//点云cloud.js加载完毕后
  48909. };
  48910. var panosLoadDone = function(){
  48911. viewer.images360.loadDone();
  48912. viewer.scene.add360Images(viewer.images360);
  48913. viewer.mapViewer.addListener(viewer.images360);
  48914. viewer.updateModelBound(); //需等pano加载完
  48915. let {boundSize, center} = viewer.bound;
  48916. if(!Potree.settings.isOfficial){
  48917. Potree.loadMapEntity('all'); //加载floorplan
  48918. }
  48919. if(!ifReload){
  48920. viewer.dispatchEvent({type:'loadPointCloudDone'});
  48921. if(!Potree.settings.UserPointDensity){
  48922. Potree.settings.UserPointDensity = 'high';//'middle'
  48923. }
  48924. Potree.Log('loadPointCloudDone 点云加载完毕', {font:[null, 10]});
  48925. }
  48926. {//初始位置
  48927. var panoId = browser.urlHasValue('pano',true);
  48928. if(panoId !== ''){
  48929. var pos;
  48930. var pano = viewer.images360.panos.find(e=>e.id==panoId);
  48931. if(pano){
  48932. viewer.images360.focusPano({
  48933. pano,
  48934. duration:0,
  48935. callback:()=>{/* Potree.settings.displayMode = 'showPanos' */}
  48936. });
  48937. }
  48938. }else {//考虑到多数据集距离很远,或者像隧道那种场景,要使视野范围内一定能看到点云,最好初始点设置在漫游点上
  48939. let {boundSize, center} = viewer.bound;
  48940. let pano = viewer.images360.findNearestPano(center);
  48941. if(pano){
  48942. viewer.images360.flyToPano({
  48943. pano, duration:0,
  48944. target : viewer.images360.bound.center.setZ(pano.position.z) //平视中心区域(但也不能保证这个方向一定能看到点云密集区,如果在边缘的话)
  48945. });
  48946. }else {// 无漫游点 避免加载时看不到点云 SG-t-DXmdymgZ2sX SG-t-rVB03a5GXr8
  48947. //SG-t-XPf1k9pv3Zg 总有极端的场景,如这是倾斜的桥 - -, 只能调整为看到全局了
  48948. viewer.mainViewport.view.pitch = -0.7; //相对俯视
  48949. let bound = viewer.bound.boundingBox.clone();
  48950. viewer.focusOnObject({boundingBox:bound},'boundingBox',0,{dontChangeCamDir:true});
  48951. if(viewer.bound.boundSize.length() > 20){ //否则有可能超出far范围
  48952. viewer.mainViewport.camera.far = 10000;
  48953. viewer.mainViewport.camera.updateProjectionMatrix();
  48954. viewer.fixCamFar = true; //不允许修改camera.far
  48955. //等有点云加载出来后,再去focus其中一个,使camera.far不超过最大值
  48956. let count_ = 0;
  48957. let done = ()=>{
  48958. viewer.fixCamFar = false;
  48959. viewer.mainViewport.camera.far = Potree.settings.cameraFar;
  48960. viewer.mainViewport.camera.updateProjectionMatrix();
  48961. viewer.removeEventListener('pageVisible', focusPoint );
  48962. clearTimeout(timer);
  48963. };
  48964. let timer;
  48965. let focusPoint = (e)=>{//拉近到某个点
  48966. if(e && e.v === false)return
  48967. viewer.removeEventListener('pageVisible', focusPoint );
  48968. let pointcloud = viewer.scene.pointclouds.find(e=>e.root.geometryNode);
  48969. console.log('初始加载focus点云', e , pointcloud);
  48970. if(!pointcloud){
  48971. if(count_ < 10 ){//可能没加载到,可能被隐藏
  48972. if(document.hidden){//等回到页面再focus
  48973. console.log('focus hidden');
  48974. return viewer.addEventListener('pageVisible', focusPoint )
  48975. }
  48976. count_ ++; //如果在别的
  48977. timer = setTimeout(focusPoint, 200);
  48978. }else { //放弃
  48979. console.log('初始加载focus点云 放弃');
  48980. done();
  48981. }
  48982. return console.warn('no!!!!!!!!!!!!!!')
  48983. }
  48984. viewer.flyToDataset({focusOnPoint:true, pointcloud, duration:0, });
  48985. console.warn('ok!!!!!!!!!!!!!!!!');
  48986. done();
  48987. };
  48988. let focus = ()=>{
  48989. timer = setTimeout(focusPoint, 300);
  48990. };
  48991. viewer.addEventListener('setPose',()=>{//设置了初始画面
  48992. viewer.removeEventListener('pointcloud_changed',focus);
  48993. done();
  48994. });
  48995. viewer.addEventListener('pointcloud_changed',focus,{once:true});//加载了点之后
  48996. }
  48997. }
  48998. }
  48999. }
  49000. viewer.addVideo();//addFire()
  49001. viewer.scene.pointclouds.some(e=>!e.hasDepthTex) && (Potree.config.shelterMargin*=3); //没有深度图的话在全景模式测量有偏差
  49002. console.log('allLoaded');
  49003. viewer.dispatchEvent('allLoaded');
  49004. };
  49005. var transformPointcloud = (pointcloud, dataset)=>{
  49006. var locationLonLat = dataset.location.slice(0,2);
  49007. //当只有一个dataset时,无论如何transform 点云和漫游点都能对应上。
  49008. /* if(window.AMapWith84 && Potree.settings.mapCompany != 'google'){
  49009. locationLonLat = AMapWith84.wgs84ToAMap({x:locationLonLat[0], y:locationLonLat[1]})
  49010. locationLonLat = [locationLonLat.x,locationLonLat.y]
  49011. } */
  49012. var location = viewer.transform.lonlatToLocal.forward(locationLonLat); //transform.inverse()
  49013. //初始化位置
  49014. /*
  49015. location[0] = Math.sign(location[0]) * Math.min(7000, Math.abs(location[0]))
  49016. location[1] = Math.sign(location[1]) * Math.min(7000, Math.abs(location[1]))
  49017. */
  49018. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  49019. //dataset.orientation = 0
  49020. Alignment.rotate(pointcloud, null, dataset.orientation);
  49021. Alignment.translate(pointcloud, new Vector3(location[0], location[1], dataset.location[2]));
  49022. pointcloud.updateMatrixWorld();
  49023. Potree.Log(`点云${pointcloud.dataset_id}(${pointcloud.name})旋转值:${pointcloud.orientationUser}, 位置${math.toPrecision(pointcloud.translateUser.toArray(),3)}, 经纬度 ${locationLonLat}, spacing ${pointcloud.material.spacing}`, {font:[null, 13]} );
  49024. //-------------------
  49025. //viewer.mapView.showSources(false);
  49026. };
  49027. if(!Potree.settings.originDatasetId)Potree.settings.originDatasetId = data[0].id;
  49028. var originDataset = data.find(e=>e.id == Potree.settings.originDatasetId);
  49029. {//拿初始数据集作为基准。它的位置是000
  49030. var locationLonLat = originDataset.location.slice(0,2);
  49031. if(window.AMapWith84){//需要转换为高德的
  49032. locationLonLat = AMapWith84.wgs84ToAMap({x:locationLonLat[0], y:locationLonLat[1]});
  49033. locationLonLat = [locationLonLat.x,locationLonLat.y];
  49034. }
  49035. proj4.defs("LOCAL", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); //高德坐标系
  49036. proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  49037. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  49038. let transform1 = proj4("WGS84", "LOCAL"); //这个ok 是展开的平面投影 LOCAL即NAVVIS:TMERC
  49039. let transform2 = proj4("+proj=tmerc +lat_0=0 +lon_0=123 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs;");
  49040. //注:转入后再转出,和原来的有偏差。如果输入是local坐标,数字越大偏差越大,当百万时就明显了。如果是lonlat,很奇怪经度小于50时就乱了。
  49041. viewer.transform = {
  49042. lonlatToLocal : transform1,
  49043. lonlatTo4550 : transform2 // 转大地坐标EPSG:4550
  49044. };
  49045. if(window.AMapWith84 && Potree.settings.mapCompany != 'google'){//需要转换, 因本地高德用的lonlat和数据里的84不一样. (google地图在国内也用的高德,国外84)
  49046. let change = (transform)=>{
  49047. let forward = transform.forward;
  49048. let inverse = transform.inverse;
  49049. transform.forward = function(e){
  49050. let needTran = e.x == void 0;
  49051. if(needTran)var a1 = {x:e[0],y:e[1]};
  49052. else var a1 = e;
  49053. var a = AMapWith84.wgs84ToAMap(a1);
  49054. if(needTran){
  49055. a = [a.x, a.y]; e[2] != void 0 && (a[2] = e[2]);
  49056. }else {
  49057. e.z != void 0 && (a.z = e.z);
  49058. }
  49059. return forward(a)
  49060. };
  49061. transform.inverse = function(e){
  49062. let needTran = e.x == void 0;
  49063. var a = inverse(e);
  49064. needTran && (a = {x:a[0],y:a[1]});
  49065. a = AMapWith84.aMapToWgs84(a);
  49066. if(needTran){
  49067. a = [a.x,a.y]; e[2] != void 0 && (a[2] = e[2]);
  49068. }else {
  49069. e.z != void 0 && (a.z = e.z);
  49070. }
  49071. return a
  49072. };
  49073. };
  49074. for(let f in viewer.transform){
  49075. change(viewer.transform[f]);
  49076. }
  49077. }
  49078. viewer.mapViewer && viewer.mapViewer.mapLayer.maps[0].updateProjection();
  49079. }
  49080. data.forEach((dataset,index)=>{
  49081. if(!ifReload){
  49082. var datasetCode = dataset.sceneCode || dataset.name; //对应4dkk的场景码
  49083. if(Potree.settings.isLocal && dataset.mapping){
  49084. var cloudPath = `${Potree.settings.urls.prefix1}/${dataset.mapping}/${dataset.webBin}`; //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  49085. }else {
  49086. var cloudPath = `${Potree.settings.urls.prefix1}/${dataset.webBin}`; //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  49087. }
  49088. var timeStamp = dataset.updateTime ? dataset.updateTime.replace(/[^0-9]/ig,'') : ''; //每重算一次后缀随updateTime更新一次
  49089. //console.warn(dataset.name, 'timeStamp', timeStamp)
  49090. Potree.loadPointCloud(cloudPath, dataset.name ,datasetCode, timeStamp, e => {
  49091. let scene = viewer.scene;
  49092. let pointcloud = e.pointcloud;
  49093. let config = Potree.config.material;
  49094. let material = pointcloud.material;
  49095. pointcloud.datasetData = dataset;
  49096. pointcloud.dataset_id = dataset.id;//供漫游点找到属于的dataset点云
  49097. pointcloud.hasDepthTex = Potree.settings.useDepthTex && (!!dataset.has_depth || Potree.settings.isLocalhost && Potree.settings.number == 'SS-t-7DUfWAUZ3V'); //test
  49098. material.minSize = config.minSize;
  49099. material.maxSize = config.maxSize;
  49100. material.pointSizeType =/* Potree.settings.isOfficial ? */ config.pointSizeType; /* : 'ADAPTIVE' */ //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  49101. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  49102. pointcloud.changePointOpacity(1);
  49103. material.shape = Potree.PointShape.SQUARE;
  49104. pointcloud.color = pointcloud.material.color = dataset.color;
  49105. pointcloud.timeStamp = timeStamp;
  49106. transformPointcloud(pointcloud,dataset);
  49107. scene.addPointCloud(pointcloud);
  49108. if(!Potree.settings.isOfficial){
  49109. Potree.settings.floorplanEnables[dataset.id] = true;
  49110. Potree.settings.floorplanType[dataset.id] = 'default';
  49111. }
  49112. pointcloudLoaded ++;
  49113. if(pointcloudLoaded == datasetLength)pointcloudLoadDone();
  49114. Potree.loadPanos(dataset.id, (data) => {
  49115. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  49116. viewer.images360.addPanoData(data, dataset.id );
  49117. panosLoaded ++;
  49118. if(panosLoaded == datasetLength){
  49119. Potree.loadImgVersion((e={})=>{
  49120. Potree.settings.panoVersion = e.imgVersion;//全景图被替换后
  49121. panosLoadDone();
  49122. });
  49123. }
  49124. });
  49125. });
  49126. }else {
  49127. let pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == dataset.id);
  49128. if(!pointcloud){
  49129. Potree.Log('数据集id变了,自动使用第一个', {font:['#500' ]} );
  49130. pointcloud = viewer.scene.pointclouds[0];
  49131. }
  49132. //先归零
  49133. Alignment.translate(pointcloud, pointcloud.translateUser.clone().negate());
  49134. Alignment.rotate(pointcloud, null, - pointcloud.orientationUser);
  49135. transformPointcloud(pointcloud, dataset);
  49136. }
  49137. });
  49138. if(ifReload){
  49139. //loadDone()
  49140. }
  49141. };
  49142. number && Potree.loadDatasets(Potree.loadDatasetsCallback);
  49143. window.testTransform = function(locationLonLat, location1, location2){
  49144. proj4.defs("NAVVIS:test", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  49145. let transform = proj4("WGS84", "NAVVIS:test"); //这个ok navvis里也是这两种转换 见proj4Factory
  49146. if(location1){//经纬度
  49147. return transform.forward(location1)
  49148. }else {
  49149. return transform.inverse(location2)
  49150. }
  49151. };
  49152. window.THREE = THREE$1;
  49153. window.buttonFunction = function(){
  49154. viewer.scene.pointclouds.forEach(e=>e.predictNodeMaxLevel());
  49155. /*
  49156. viewer.startScreenshot({type:'measure', measurement:viewer.scene.measurements[0]})
  49157. viewer.modules.RouteGuider.routeStart = new THREE.Vector3(0,0,-1.3)
  49158. viewer.modules.RouteGuider.routeEnd = new THREE.Vector3(-10,0,-1.3)
  49159. */
  49160. };
  49161. if(Potree.settings.isLocalhost){
  49162. let before = {};
  49163. viewer.inputHandler.addEventListener('keydown',e=>{ //测试的代码
  49164. if(e.event.key == 't'){
  49165. viewer.images360.cube.visible = true;
  49166. viewer.images360.cube.material.wireframe = true;
  49167. }else if(e.event.key == 'y'){
  49168. viewer.images360.cube.material.wireframe = false;
  49169. viewer.images360.cube.visible = Potree.settings.displayMode == 'showPanos';
  49170. }
  49171. });
  49172. }
  49173. //--------------------------------
  49174. if(!number){
  49175. Potree.settings.boundAddObjs = true;
  49176. Potree.settings.intersectOnObjs = true;
  49177. // Load untextured bunny from ply
  49178. viewer.loadModel({
  49179. fileType:'ply',
  49180. url:Potree.resourcePath + "/models/indoor.ply",
  49181. name:'test',
  49182. },
  49183. (object)=>{
  49184. object.isModel = true;
  49185. viewer.updateModelBound();
  49186. }
  49187. );
  49188. }
  49189. }
  49190. //=======================================================================
  49191. /*
  49192. 漫游点编辑
  49193. */
  49194. //=======================================================================
  49195. function panoEditStart(dom, number, fileServer){
  49196. Potree.settings.editType = 'pano';
  49197. Potree.settings.number = number;
  49198. Potree.settings.unableNavigate = true;
  49199. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  49200. let viewer = new Potree.Viewer(dom);
  49201. let Alignment = viewer.modules.Alignment;
  49202. viewer.setEDLEnabled(false);
  49203. viewer.setFOV(Potree.config.view.fov);
  49204. //viewer.loadSettingsFromURL();
  49205. let datasetLoaded = 0;
  49206. if(!Potree.settings.isOfficial){
  49207. viewer.loadGUI(() => {
  49208. viewer.setLanguage('en');
  49209. $("#menu_tools").next().show();
  49210. $("#panos").show();
  49211. $("#alignment").show();
  49212. viewer.toggleSidebar();
  49213. });
  49214. Potree.settings.sizeFitToLevel = true;
  49215. }
  49216. var pointcloudLoadDone = function( ){//所有点云cloud.js加载完毕后
  49217. viewer.scene.pointclouds.forEach(c=>{
  49218. transformPointcloud(c);
  49219. });
  49220. viewer.images360.loadDone();
  49221. viewer.scene.add360Images(viewer.images360);
  49222. viewer.updateModelBound();
  49223. let {boundSize, center} = viewer.bound;
  49224. Potree.Log(`中心点: ${math.toPrecision(center.toArray(),2)}, boundSize: ${math.toPrecision(boundSize.toArray(),2)} ` , {font:[null, 12]} );
  49225. viewer.scene.view.setView({
  49226. position: center.clone().add(new Vector3(10,5,10)),
  49227. target: center
  49228. });
  49229. viewer.dispatchEvent({type:'loadPointCloudDone'});
  49230. if(!Potree.settings.UserPointDensity){
  49231. Potree.settings.UserPointDensity = 'panoEdit';//'middle'
  49232. }
  49233. Potree.Log('loadPointCloudDone 点云加载完毕',{font:[null, 10]});
  49234. viewer.dispatchEvent('allLoaded');
  49235. };
  49236. var transformPointcloud = (pointcloud )=>{ //初始化位置
  49237. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  49238. let orientation = pointcloud.panos[0].dataRotation.z + Math.PI;
  49239. let location = pointcloud.panos[0].dataPosition.clone();//.negate()
  49240. Alignment.rotate(pointcloud, null, orientation );
  49241. Alignment.translate(pointcloud, location );
  49242. pointcloud.updateMatrixWorld();
  49243. };
  49244. let loadPanosDone = Potree.loadPanosDone = (datasetId, panoData )=>{ //一个数据集获取到它的panos后
  49245. Potree.settings.datasetsPanos[datasetId] = {panoData, panos:[]};
  49246. console.log('panoData', datasetId, panoData);
  49247. let panoCount = panoData.length;
  49248. let pointcloudLoaded = 0;
  49249. let datasetsCount = Object.keys(Potree.settings.datasetsPanos).length;
  49250. panoData.forEach((pano, index)=>{
  49251. //let cloudPath = `${Potree.scriptPath}/data/panoEdit/uuidcloud/${pano.uuid}/cloud.js`
  49252. let cloudPath = `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${Potree.settings.number}/data/bundle_${Potree.settings.number}/building/uuidcloud/${pano.uuid}/cloud.js`;
  49253. /* if(Potree.settings.isLocal && dataset.mapping){
  49254. var cloudPath = `${Potree.settings.urls.prefix1}/${dataset.mapping}/${dataset.webBin}` //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  49255. }else{
  49256. var cloudPath = `${Potree.settings.urls.prefix1}/${dataset.webBin}` //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  49257. } */
  49258. let name = datasetId + '-'+pano.uuid;
  49259. let timeStamp = 0;
  49260. pano.index = index; //注意:index不等于uuid,因为有的uuid缺失。但是visibles中存的是下标!
  49261. Potree.loadPointCloud(cloudPath, name , name, timeStamp, e => { //开始加载点云
  49262. let scene = viewer.scene;
  49263. let pointcloud = e.pointcloud;
  49264. let config = Potree.config.material;
  49265. let material = pointcloud.material;
  49266. material.minSize = config.minSize;
  49267. material.maxSize = config.maxSize;
  49268. material.pointSizeType = /* 'ADAPTIVE'// */config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  49269. pointcloud.changePointSize( 0.1 /* config.realPointSize */ ); //material.size = config.pointSize;
  49270. pointcloud.changePointOpacity(1);
  49271. material.shape = Potree.PointShape.SQUARE;
  49272. pointcloud.color = config.pointColor;
  49273. pointcloud.dataset_id = datasetId; //多个点云指向一个datasetId
  49274. pointcloud.panoUuid = pano.uuid;
  49275. pointcloud.timeStamp = timeStamp;
  49276. //transformPointcloud(pointcloud, pano)
  49277. scene.addPointCloud(pointcloud);
  49278. pointcloudLoaded ++;
  49279. if(pointcloudLoaded == panoCount ){
  49280. datasetLoaded ++;
  49281. viewer.images360.addPanoData(panoData , datasetId );
  49282. if(datasetLoaded == datasetsCount){
  49283. pointcloudLoadDone();
  49284. }
  49285. }
  49286. });
  49287. });
  49288. };
  49289. if(!Potree.settings.isOfficial){
  49290. Potree.settings.datasetsPano = {'testDataset':null};
  49291. Potree.loadPanosInfo( data=>{loadPanosDone('testDataset', data.sweepLocations);} );
  49292. }
  49293. }
  49294. function mergeEditStart(dom){
  49295. Potree.settings.editType = 'merge';
  49296. Potree.settings.intersectOnObjs = true;
  49297. Potree.settings.boundAddObjs = true;
  49298. Potree.settings.unableNavigate = true;
  49299. let viewer = new Potree.Viewer(dom );
  49300. let Alignment = viewer.modules.Alignment;
  49301. viewer.setEDLEnabled(false);
  49302. viewer.setFOV(Potree.config.view.fov);
  49303. //viewer.loadSettingsFromURL();
  49304. {
  49305. viewer.mainViewport.view.position.set(30,30,30);
  49306. viewer.mainViewport.view.lookAt(0,0,0);
  49307. viewer.updateModelBound();//init
  49308. //this.bound = new THREE.Box3(new THREE.Vector3(-1,-1,-1),new THREE.Vector3(1,1,1))
  49309. viewer.transformationTool.setModeEnable(['translation','rotation'] );
  49310. //viewer.ssaaRenderPass.sampleLevel = 1 // sampleLevel为1 的话,ground就不会变黑
  49311. viewer.inputHandler.fixSelection = true; //不通过点击屏幕而切换transfrom选中状态
  49312. }
  49313. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  49314. Potree.loadPointCloudScene = function(url, type, id, title, done, onError){//对应4dkk的场景码
  49315. let loadCloud = ({cloudPath, sceneName, sceneCode, timeStamp, color } )=>{
  49316. Potree.loadPointCloud(cloudPath, sceneName , sceneCode, timeStamp, e => {
  49317. let scene = viewer.scene;
  49318. let pointcloud = e.pointcloud;
  49319. let config = Potree.config.material;
  49320. let material = pointcloud.material;
  49321. material.minSize = config.minSize;
  49322. material.maxSize = config.maxSize;
  49323. material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  49324. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  49325. pointcloud.changePointOpacity(1);
  49326. material.shape = Potree.PointShape.SQUARE;
  49327. color && (pointcloud.color = pointcloud.material.color = color);
  49328. pointcloud.timeStamp = timeStamp;
  49329. //transformPointcloud(pointcloud, originDataset)
  49330. scene.addPointCloud(pointcloud);
  49331. {
  49332. viewer.updateModelBound();
  49333. let {boundSize, center} = viewer.bound;
  49334. viewer.dispatchEvent({type:'loadPointCloudDone'});
  49335. if(!Potree.settings.UserPointDensity){
  49336. Potree.settings.UserPointDensity = 'high';//'middle'
  49337. }
  49338. Potree.Log('loadPointCloudDone 点云加载完毕', {font:[null,10] });
  49339. }
  49340. /* Potree.loadPanos(dataset.id, (data) => { //暂时不加载panos了,因为没有id
  49341. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  49342. viewer.images360.addPanoData(data, dataset.id )
  49343. viewer.images360.loadDone()
  49344. viewer.scene.add360Images(viewer.images360); */
  49345. viewer.dispatchEvent('allLoaded');
  49346. done(pointcloud);
  49347. },onError);
  49348. };
  49349. if(type == 'laser'){
  49350. let sceneCode = url;
  49351. Potree.loadDatasets((data)=>{
  49352. let originDataset = data.find(e=>e.sceneCode == sceneCode);//只加载初始数据集
  49353. let timeStamp = originDataset.updateTime ? originDataset.updateTime.replace(/[^0-9]/ig,'') : ''; //每重算一次后缀随updateTime更新一次
  49354. //let cloudPath = `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${sceneCode}/data/${sceneCode}/webcloud/cloud.js`
  49355. let cloudPath = `${Potree.settings.urls.prefix1}/${originDataset.webBin}`; //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  49356. loadCloud({cloudPath, sceneName:originDataset.sceneName, sceneCode, timeStamp, color:originDataset.color});
  49357. }, sceneCode, onError);
  49358. }else {//las or ply 直接用url
  49359. let name = type + '|' + id + '|' + title;
  49360. if(url instanceof Array){
  49361. if(url.length == 1){
  49362. url = url[0];
  49363. }else {
  49364. console.error('有多个点云?暂时还不支持', url, name);//多个点云要一起移动没想好怎么写
  49365. }
  49366. }
  49367. let cloudPath = url + '/cloud.js';
  49368. loadCloud({cloudPath, sceneName:name, sceneCode:name, timeStamp:'' });
  49369. }
  49370. };
  49371. let setMatrix = (pointcloud)=>{//为了漫游点变换,要算一下 类似setMatrix
  49372. /* pointcloud.transformMatrix = new THREE.Matrix4().multiplyMatrices(pointcloud.matrix, pointcloud.pos1MatrixInvert)//还原一点位移
  49373. pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert()
  49374. pointcloud.rotateMatrix = new THREE.Matrix4().makeRotationFromEuler(pointcloud.rotation);
  49375. pointcloud.rotateInvMatrix.copy(pointcloud.rotateMatrix).invert()
  49376. pointcloud.panos.forEach(e=>e.transformByPointcloud()) */
  49377. //pointcloud.updateBound()
  49378. //pointcloud.getPanosBound()
  49379. viewer.updateModelBound();
  49380. };
  49381. let moveModel = (e)=>{//根据鼠标移动的位置改变位置
  49382. let camera = viewer.mainViewport.camera;
  49383. var origin = new Vector3(e.pointer.x, e.pointer.y, -1).unproject(camera),
  49384. end = new Vector3(e.pointer.x, e.pointer.y, 1).unproject(camera);
  49385. var dir = end.sub(origin);
  49386. let planeZ = 0;
  49387. let r = (planeZ - origin.z)/dir.z;
  49388. let x = r * dir.x + origin.x;
  49389. let y = r * dir.y + origin.y;
  49390. //过后改为根据intersect的点来设置底部高度;这样的话,需要发送高度
  49391. /*let pos = new THREE.Vector3(x,y, planeZ )
  49392. modelEditing.updateMatrixWorld()
  49393. let boundCenter = modelEditing.boundingBox.getCenter(new THREE.Vector3).applyMatrix4(modelEditing.matrixWorld);
  49394. */
  49395. MergeEditor.moveBoundCenterTo(modelEditing,new Vector3(x,y, modelEditing.boundCenter.z)); //使模型中心的xy在鼠标所在位置
  49396. modelEditing.dispatchEvent("position_changed");
  49397. };
  49398. let cancelMove = ()=>{
  49399. modelEditing = null;
  49400. viewer.removeEventListener('global_mousemove', moveModel);
  49401. viewer.removeEventListener('global_click', confirmPos);
  49402. };
  49403. let confirmPos = ()=>{
  49404. MergeEditor.focusOn(modelEditing);
  49405. cancelMove();
  49406. return {stopContinue:true}
  49407. };
  49408. let modelType, modelEditing, MergeEditor = viewer.modules.MergeEditor;
  49409. Potree.addModel = function(prop, done, onProgress, onError){ //加载模型
  49410. let loadDone = (model)=>{
  49411. model.dataset_id = prop.id; //唯一标识
  49412. if(prop.position){
  49413. model.position.copy(prop.position);
  49414. }
  49415. if(prop.rotation){
  49416. //model.rotation.setFromVector3(prop.rotation)
  49417. model.rotation.copy(prop.rotation);
  49418. }
  49419. if(prop.scale){
  49420. model.scale.set(prop.scale,prop.scale,prop.scale);
  49421. }
  49422. if(model.isPointcloud){
  49423. model.renderOrder = Potree.config.renderOrders.model; //same as glb
  49424. }
  49425. if(Potree.settings.maintainBtmZ)
  49426. {//transform --------维持离地高度和中心点的版本(local ver)
  49427. let updateBound = ()=>{
  49428. model.updateMatrixWorld();
  49429. viewer.updateModelBound();
  49430. };
  49431. let maintainBtmZAndCenter = ()=>{
  49432. MergeEditor.maintainBoundXY(model);
  49433. MergeEditor.setModelBtmHeight(model);
  49434. updateBound();
  49435. model.dispatchEvent('transformChanged');
  49436. };
  49437. model.addEventListener('position_changed', ()=>{
  49438. updateBound();
  49439. MergeEditor.getBoundCenter(model);//更新boundcenter
  49440. MergeEditor.computeBtmHeight(model);
  49441. if(prop.bottomRange && (model.btmHeight > prop.bottomRange.max || model.btmHeight < prop.bottomRange.min)){
  49442. model.btmHeight = MathUtils.clamp(model.btmHeight, prop.bottomRange.min, prop.bottomRange.max);
  49443. MergeEditor.setModelBtmHeight(model);
  49444. updateBound();
  49445. }
  49446. model.dispatchEvent('transformChanged');
  49447. });
  49448. model.addEventListener("rotation_changed", maintainBtmZAndCenter );
  49449. model.addEventListener("scale_changed", maintainBtmZAndCenter );
  49450. model.addEventListener('transformChanged', ()=>{
  49451. MergeEditor.modelTransformCallback(model);
  49452. });
  49453. //离地高度只是boundingbox在transform后的最低点的高度,而非模型transform后的最低点的高度,所以旋转过后看起来不太准确
  49454. } else
  49455. {//transform --------维持中心点的版本
  49456. let updateBound = ()=>{
  49457. model.updateMatrixWorld();
  49458. viewer.updateModelBound();
  49459. };
  49460. let maintainCenter = ()=>{
  49461. //MergeEditor.maintainBoundXY(model)
  49462. MergeEditor.maintainBoundCenter(model);
  49463. updateBound();
  49464. model.dispatchEvent('transformChanged');
  49465. };
  49466. model.addEventListener('position_changed', ()=>{
  49467. updateBound();
  49468. MergeEditor.getBoundCenter(model);//更新boundcenter
  49469. model.dispatchEvent('transformChanged');
  49470. });
  49471. model.addEventListener("rotation_changed", maintainCenter );
  49472. model.addEventListener("scale_changed", maintainCenter );
  49473. model.addEventListener('transformChanged', ()=>{
  49474. MergeEditor.modelTransformCallback(model);
  49475. });
  49476. }
  49477. model.updateMatrixWorld();
  49478. viewer.updateModelBound();
  49479. MergeEditor.getBoundCenter(model); //初始化
  49480. model.lastMatrixWorld = model.matrixWorld.clone();
  49481. done(model); // 先发送成功,因为2d界面会随机执行changePosition等初始化,然后这边再将模型移到中心地面上
  49482. if(prop.isFirstLoad){
  49483. MergeEditor.moveBoundCenterTo(model, new Vector3(0,0,0));
  49484. MergeEditor.setModelBtmHeight(model, 0); //初始加载设置离地高度为0
  49485. if(prop.mode != 'single'){//如果不是模型展示页,模型会随着鼠标位置移动
  49486. modelEditing = model;
  49487. /* if(model.fileType == '3dTiles'){
  49488. setTimeout(()=>{
  49489. moveModel({pointer:{x:0,y:0}}) //3dTiles的移动会错乱,先默认放在当前视图中间吧
  49490. confirmPos()
  49491. },1)
  49492. }else{ */
  49493. viewer.addEventListener('global_mousemove', moveModel);
  49494. viewer.addEventListener('global_click', confirmPos, {importance:3});
  49495. //}
  49496. }
  49497. model.dispatchEvent("position_changed");
  49498. }else {
  49499. //MergeEditor.setModelBtmHeight(model, prop.bottom || 0) //默认离地高度为0
  49500. modelEditing = null;
  49501. }
  49502. MergeEditor.modelAdded(model);
  49503. };
  49504. if(prop.type == 'glb'){
  49505. let callback = (object)=>{
  49506. //focusOnSelect(object, 1000)
  49507. object.isModel = true;
  49508. //object.dataset_id = Date.now() //暂时
  49509. object.traverse(e=>e.material && (e.material.transparent = true));
  49510. /* object.addEventListener('click',(e)=>{
  49511. //只是为了能得到hoverElement识别才加这个侦听
  49512. }) */
  49513. loadDone(object);
  49514. };
  49515. let info = {
  49516. fileType: prop.type,
  49517. id: prop.id,
  49518. unlit:true,
  49519. url : prop.url,
  49520. name : prop.title,
  49521. /* transform : {
  49522. position : prop.position,
  49523. rotation : new THREE.Euler().setFromVector3(prop.rotation),
  49524. scale: new THREE.Vector3(prop.scale,prop.scale,prop.scale),
  49525. } */
  49526. };
  49527. viewer.loadModel(info , callback, onProgress, onError);
  49528. }else if(prop.type == 'obsg' || prop.type == 'b3dm'){ //3d tiles
  49529. let callback = (object)=>{
  49530. object.isModel = true;
  49531. //透明度怎么办
  49532. //object.traverse(e=>e.material && (e.material.transparent = true))
  49533. loadDone(object);
  49534. };
  49535. viewer.loadModel({
  49536. fileType: '3dTiles',
  49537. id: prop.id,
  49538. name : prop.title,
  49539. /* tilesUrl: 'https://4dkk.4dage.com/scene_view_data/SS-Ds19qsmuFA/images/3dtiles/tileset.json',
  49540. transform : {
  49541. rotation : [Math.PI/2, 0, 0],
  49542. position : [0,0,0]
  49543. }
  49544. tilesUrl: 'https://testgis.4dage.com/LVBADUI_qp/tileset.json',
  49545. transform : {
  49546. rotation : [0, 0, 0],
  49547. position : [0,0,0]
  49548. } */
  49549. url:prop.url,
  49550. },callback,onprogress);
  49551. }else {
  49552. //else if(prop.type == 'las' || prop.type == 'ply')
  49553. Potree.loadPointCloudScene(prop.url, prop.type, prop.modelId, prop.title, (pointcloud)=>{
  49554. pointcloud.matrixAutoUpdate = true;
  49555. pointcloud.initialPosition = pointcloud.position.clone();
  49556. pointcloud.pos1MatrixInvert = new Matrix4().setPosition(pointcloud.initialPosition).invert();
  49557. /* let maintainBtmZ = ()=>{
  49558. MergeEditor.setModelBtmHeight(pointcloud)
  49559. updateMatrix()
  49560. }
  49561. let updateMatrix = ()=>{
  49562. setMatrix(pointcloud)
  49563. pointcloud.dispatchEvent('transformChanged')
  49564. }
  49565. pointcloud.addEventListener('position_changed', updateMatrix )
  49566. pointcloud.addEventListener("orientation_changed", maintainBtmZ )
  49567. pointcloud.addEventListener("scale_changed", maintainBtmZ ) */
  49568. loadDone(pointcloud);
  49569. /* pointcloud.addEventListener('select',(e)=>{
  49570. if(Potree.settings.displayMode == 'showPanos')return
  49571. console.log('select',e)
  49572. //viewer.setControls(viewer.orbitControls)
  49573. MergeEditor.focusOnSelect(pointcloud)
  49574. viewer.outlinePass.selectedObjects = [pointcloud]
  49575. return {stopContinue:true}
  49576. },{importance:1})
  49577. pointcloud.addEventListener('deselect',(e)=>{
  49578. console.log('deselect',e)
  49579. //viewer.setControls(viewer.fpControls)
  49580. viewer.outlinePass.selectedObjects = []
  49581. }) */
  49582. }, onError);
  49583. }
  49584. };
  49585. return {THREE: THREE$1}
  49586. }
  49587. var changeLog = ()=>{
  49588. var textarea = document.createElement('textarea');
  49589. textarea.id = "consoleLog";
  49590. textarea.style.width = '160px';
  49591. textarea.style.height = '200px';
  49592. textarea.style.position = 'fixed';
  49593. textarea.style.left = 0;
  49594. textarea.style.bottom = '50px';
  49595. textarea.style['z-index'] = 9999;
  49596. textarea.style.color = 'black';
  49597. textarea.style.opacity = 0.9;
  49598. textarea.style['font-size'] = '12px';
  49599. textarea.style['backgroundColor'] = '#ffffff';
  49600. document.getElementsByTagName("body")[0].appendChild(textarea);
  49601. var list = ["log", "error", "warn", "debug", "info", "time", "timeEnd"];
  49602. var exchange = function (o) {
  49603. console["old" + o] = console[o];
  49604. console[o] = function () {
  49605. var args = Array.from(arguments);
  49606. console["old" + o].apply(this, arguments);
  49607. var t = document.getElementById("consoleLog").innerHTML;
  49608. var str = '';
  49609. args.forEach(a=>{
  49610. str += a + ' ';
  49611. });
  49612. document.getElementById("consoleLog").innerHTML = str + "\n\n" + t;
  49613. };
  49614. };
  49615. for (var i = 0; i < list.length; i++) {
  49616. exchange(list[i]);
  49617. }
  49618. };
  49619. /*
  49620. 坐标转换问题:
  49621. 由于控制点可以随便输入,所以本地和地理位置的转换也是可拉伸的。而navvis的转换是等比由中心展开,
  49622. 所以对比两种转化方式时误差较大。
  49623. 另外地理注册控制点是有参考数据集的,若参考数据集和我放置在0,0,0的数据集一致,就可直接使用,否则要转换。
  49624. ---------
  49625. lonlat和空间坐标其实并非线性关系,因为lonlat其实是角度。当两个数据集在地球两端时,它们之间的夹角都相差180度了。
  49626. 所以若要准确展示的话,需要将点云内所有物体,如漫游点,都先获取lonlat再去算local。或者直接将点云整体的transformMatrix考虑上在地球上相对于初始数据集的偏转。
  49627. */
  49628. //xzw add
  49629. const config$1 = {//配置参数 不可修改
  49630. displayMode:{
  49631. showPointCloud:{
  49632. atPano:{
  49633. showPoint : true,
  49634. showSkybox: false,
  49635. pointUsePanoTex : false
  49636. },
  49637. transition:{
  49638. showPoint: true,
  49639. showSkybox: false,
  49640. pointUsePanoTex: false
  49641. },
  49642. canLeavePano: true //是否能离开pano位置
  49643. },
  49644. showPanos:{
  49645. atPano:{
  49646. showPoint : false,
  49647. showSkybox: true,
  49648. pointUsePanoTex : false
  49649. },
  49650. transition:{
  49651. //showPoint: true,
  49652. showSkybox: true,
  49653. //pointUsePanoTex: true //是否使用全景贴图
  49654. },
  49655. canLeavePano: false
  49656. },
  49657. showBoth:{
  49658. atPano:{
  49659. showPoint : true,
  49660. showSkybox: true,
  49661. pointUsePanoTex : false //?
  49662. },
  49663. transition:{
  49664. showPoint: true,
  49665. showSkybox: true,
  49666. pointUsePanoTex: true
  49667. },
  49668. canLeavePano: true //是否能离开pano位置 离开后自动变为showPointCloud
  49669. },
  49670. //test:
  49671. pointUsePanoTex:{ //---静止时调点云
  49672. atPano:{
  49673. showPoint : true,
  49674. showSkybox: false,
  49675. pointUsePanoTex : true
  49676. },
  49677. transition:{
  49678. showPoint: true,
  49679. showSkybox: true,
  49680. pointUsePanoTex: true //是否使用全景贴图
  49681. },
  49682. canLeavePano: false
  49683. },
  49684. },
  49685. urls:{
  49686. //localTextures:'../resources/textures/',
  49687. prefix1: 'https://laser-oss.4dkankan.com',//oss
  49688. prefix2: 'https://testlaser.4dkankan.com',
  49689. prefix3: 'https://4dkk.4dage.com',
  49690. prefix4: 'https://uat-laser.4dkankan.com',//test.4dkankan
  49691. prefix5: 'https://laser.4dkankan.com/backend',
  49692. prefix6: 'https://mix3d.4dkankan.com/backend',
  49693. prefix7: 'https://xfhd.4dkankan.com/backend',
  49694. },
  49695. transitionsTime:{
  49696. flyMinTime : 650 , // 毫秒/米
  49697. flytimeDistanceMultiplier: 120 ,
  49698. /* panoToPanoMax: 1800 ,
  49699. flyIn:1000,
  49700. flyOut:1000,
  49701. */
  49702. flyTime:650,
  49703. maxDistanceThreshold:14,
  49704. maxDistanceThresholdFlyIn:5,
  49705. }
  49706. ,
  49707. view:{
  49708. fov:70, //navvis:50
  49709. near:0.1,
  49710. far: 10000,
  49711. },
  49712. map:{//mapViewer
  49713. mapHeight : -1000,//要比点云低。最低
  49714. cameraHeight : 1000, //最高 ,注意(如sitemodel)其他的物体不能超过这个高度
  49715. },
  49716. minNodeSize:30, // perspectiveCamera允许加载的node的最小可见像素宽度。越大越省性能
  49717. tiles3DMaxMemory: 250,//M. 最大支持3dTiles的内存大小 超出会崩溃
  49718. pointDensity:{
  49719. magnifier:{
  49720. maxLevelPercent: 1,
  49721. pointBudget : 8*1000*1000,
  49722. },
  49723. panorama:{//显示全景时的漫游。因为点只能显示1个像素的大小,所以必须很密集,但又要限制点的数量
  49724. maxLevelPercent: 0.6,
  49725. pointBudget : /* 4*1000*1000// */browser.isMobile() ? 0.1*1000*1000 : 0.4*1000*1000, //点云总最大数
  49726. minNodeSize : 100,
  49727. },
  49728. fourViewports:{//分四屏时防止卡顿
  49729. maxLevelPercent: 0.9,
  49730. pointBudget :3*1000*1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  49731. minNodeSize : 70,
  49732. },
  49733. fourViewportsMain:{//分四屏时防止卡顿
  49734. maxLevelPercent: 0.9,
  49735. pointBudget :3*1000*1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  49736. minNodeSize : 70,
  49737. }
  49738. ,
  49739. panoEdit:{
  49740. maxLevelPercent: 1, //在远处时由于pointBudget限制而展示稀疏,凑近时就变为最高质量了
  49741. pointBudget :4*1000*1000, //要使点云达到200个以上时还不卡
  49742. percentByUser:true,
  49743. minNodeSize : 80 , //点云多的话远处的尽量就不可见吧
  49744. },
  49745. low:{//highPerformance
  49746. maxLevelPercent: 0.4, //最小为0
  49747. percentByUser:true, //如果用户定义了percent,使用用户的
  49748. pointBudget : browser.isMobile() ? 1*1000*1000 : 2*1000*1000,
  49749. minNodeSize : 40 / window.devicePixelRatio ,
  49750. },
  49751. middle:{//balanced //不同场景相同级别所产生的numVisibleNodes和numVisiblePoints不同,如果分层比较细,可能要到level8才能看清,那么level5看到的点就很大且很少,如隧道t-e2Kb2iU
  49752. maxLevelPercent: 0.7,
  49753. percentByUser:true,
  49754. pointBudget: browser.isMobile() ? 2.0*1000*1000 : 3.5*1000*1000,
  49755. minNodeSize : 30 / window.devicePixelRatio ,
  49756. },
  49757. high:{//highQuality
  49758. maxLevelPercent: 1,
  49759. percentByUser:true,
  49760. pointBudget:browser.isMobile() ? 3*1000*1000 : 6*1000*1000, //原本最高是8,但是大部分电脑都太卡了,降
  49761. minNodeSize : 20 / window.devicePixelRatio , //手机上因为像素点小,远一点的时候更需要加载密集的点云。(没事,有pointBudget限制着,会先从近处加载高级node,再远就不加载了)
  49762. },
  49763. screenshot:{
  49764. maxLevelPercent: 1,
  49765. pointBudget: 8*1000*1000,
  49766. minNodeSize : 40 / window.devicePixelRatio ,
  49767. }
  49768. //数值由testLevelSteps得来,其中nodeMaxLevel为2时,low和middle的都是1,如果真有这么低的点云就单独处理下。
  49769. //多个viewport尽量保证pointBudget一样,或者pointBudget不能太低于所需,否则会反复加载了又清除
  49770. },
  49771. clip:{
  49772. color: '#FFC266', //map
  49773. },
  49774. measure:{
  49775. color:'#00C8AF',
  49776. default:{
  49777. color:"#64C8BB",//"#00c7b2",
  49778. opacity:0.7
  49779. },
  49780. highlight:{
  49781. color:'#00C8AF',//"#00c7b2",
  49782. opacity:1,
  49783. labelOpacity:0.7//1会挡住线和端点
  49784. },
  49785. guide:{
  49786. color:'#FFFFFF',
  49787. opacity:0.8
  49788. }
  49789. ,
  49790. backColor:'#333333',
  49791. lineWidth: 3,
  49792. textColor: "#000000", //"#FFFFFF"
  49793. mulLabelHideFaraway : false ,// 多折线根据远近显示label
  49794. adsorptMinDis : 30, //最小吸附距离(像素)
  49795. },
  49796. material:{//初始化
  49797. pointSize: 0.1,
  49798. realPointSize : 0.1,//实际上的ui滑动条默认大小(兼容旧的版本)
  49799. minSize: 0.1,
  49800. maxSize: 10000,
  49801. pointSizeType: 'ATTENUATED', //'ADAPTIVE'//'ADAPTIVE' \ FIXED //ADAPTIVE的在小房间里大小会不太匹配,但在远景似乎更好
  49802. /*
  49803. ATTENUATED : 衰减 真实大小,靠近时感觉是点云一点点变多,缝隙变小
  49804. ADAPTIVE: 自适应 大小根据level变化,越高越小。靠近时感觉点云由大慢慢细分成小份。这个感觉更佳但是navvis为何不用这个
  49805. */
  49806. absolutePanoramaSize: 1.3 ,//全景漫游时的size 是fixed的模式
  49807. //sizeAtPanoRtEDL : 2000,
  49808. pointColor:'#ffffff',
  49809. //sizeAddAtPanoRtEDL : 0.5, //全景模式静止时的size
  49810. //ADAPTIVE : 字会失真扭曲
  49811. //'ATTENUATED' 往旁边看有缝隙、点在浮动
  49812. }
  49813. ,
  49814. skyboxBgWidth : 100 ,
  49815. renderLayers:{//渲染层,方便分批渲染管理,替代scene的创建。数字不代表顺序。(数字不能太大)
  49816. bg: 20,
  49817. bg2: 21,
  49818. skybox: 1,
  49819. pointcloud: 11,
  49820. sceneObjects:0,//default
  49821. model : 2,
  49822. light: 15,
  49823. measure:4,
  49824. magnifier:5,
  49825. magnifierContent:16,
  49826. volume:6,
  49827. transformationTool:7,
  49828. map:8,
  49829. mapObjects:9,//default
  49830. bothMapAndScene: 3,
  49831. siteModeOnlyMapVisi:12,//只能mapViewer可见
  49832. siteModelMapUnvisi:13,//只有mapViewer不可见
  49833. siteModeSideVisi:14,//只有侧面可见
  49834. layer1: 18,// 备用1
  49835. layer2: 17,// 备用2
  49836. },
  49837. renderOrders:{ //会影响到绘制、pick时的顺序。
  49838. model:10
  49839. },
  49840. siteModel:{
  49841. names:{
  49842. 'building': '建筑',
  49843. 'floor':'楼层',
  49844. 'room':'房间'
  49845. },
  49846. floorHeightDefault: 5,//一层楼的高度
  49847. },
  49848. panosEdit:{
  49849. },
  49850. tiling: {
  49851. panoPreRenderRepeatDelay: 2500,
  49852. panoPreRenderDelay: 500,
  49853. preRenderTourPanos: browser.valueFromHash("tileprerender", 0),
  49854. tilingFlagNames: ["usetiles", "tiles"],
  49855. maxNavPanoQuality: browser.valueFromHash("maxtileq", null),
  49856. maxZoomPanoQuality: browser.valueFromHash("maxztileq", null),
  49857. overlayStyle: browser.valueFromHash("tileoverlay", 0),
  49858. uploadIntervalDelay: browser.valueFromHash("tileupdelay", 10 ),
  49859. initialIntervalDelay: browser.valueFromHash("itiledelay", 0),
  49860. maxNonBaseUploadsPerFrame: browser.valueFromHash("maxnbtpf", 1),
  49861. maxBaseUploadsPerFrame: browser.valueFromHash("maxbtpf",6),
  49862. customCompression: browser.valueFromHash("tilecustcomp", 0),
  49863. mobileHighQualityOverride: !1,
  49864. allowUltraHighResolution: !0
  49865. },
  49866. navigation: {
  49867. panoScores: !1,
  49868. mouseDirection: !0,
  49869. filterStrictness: .75,
  49870. angleFactor: -30,
  49871. directionFactor: 10,
  49872. distanceFactor: -1,
  49873. optionalityFactor: 3
  49874. }
  49875. ,
  49876. axis : { 'x':{color:'#ea3f3f'/* '#d0021b' */ /* 'red' */}, 'y':{ color:'#86c215' /* '#86c542' *//* 'green' */}, 'z': {color:'#3396f8'/* '#3399c8' */ /* 'blue' */}, 'xyz':{color:'#ccc',}},
  49877. shelterMargin:0.15, //多少米内不算遮挡 (有的场景深度图不准,和点云差别蛮大如SG-t-24F0iT3pKAO)
  49878. highQualityMaxZoom: 2,
  49879. ultraHighQualityMaxZoom: 3,
  49880. panoFieldRadius : 10, //当前位置多远范围内可以切全景模式
  49881. clickMaxDragDis:5,
  49882. clickMaxPressTime:500, //ms
  49883. doubleClickTime:300,//双击间隔时间
  49884. testNodeCount1: browser.isMobile() ? 6 : 4, //testMaxNode次数达到这个数字时,changePointSize才使用nodeMaxLevel。 (调试时比较卡,在线上实际只需要3)
  49885. background: '#232323',
  49886. mapBG:/* '#232323', */ '#F5F5F5', //地图的clearColor
  49887. colors: { //from navvis
  49888. red: [213,0,0],
  49889. pink: [197,17,98],
  49890. purple: [170,0,255],
  49891. "deep purple": [98,0,234],
  49892. blue: [ 41,98,255],
  49893. "light blue": [ 0,145,234],
  49894. cyan: [ 0,184,212],
  49895. teal: [ 0,191,165],
  49896. green: [0,200,83],
  49897. "light green": [ 100,221,23],
  49898. lime: [ 174,234,0],
  49899. yellow: [ 255,214,0],
  49900. amber: [ 255,171,0],
  49901. orange: [ 255,109,0],
  49902. "deep orange": [ 255,61,0],
  49903. },
  49904. depthTexUVyLimit: 0.141, // 在这个范围内是没有深度的,从图片算的0.14003, 设置为稍大于这个数值
  49905. };
  49906. config$1.OrthoCameraLimit = {
  49907. standard:{
  49908. zoom:{min:0.0004, max:500}, //如果camera缩太小,地图会因为数字边界问题而扭曲
  49909. latPad:20,
  49910. xBound:[-4e6, 4e6],
  49911. },
  49912. expand:{
  49913. zoom:{min:0.0004, max:500}, //如果camera缩太小,地图会因为数字边界问题而扭曲
  49914. latPad:20,
  49915. xBound:[-6e6, 6e6],
  49916. },
  49917. };
  49918. /* 显示模式:
  49919. 1只显示点云: 滚轮为前进后退,方向键可以行走。进入漫游点时自动变为混合(这样全景可以弥补缝隙),过渡时只显示点云。
  49920. 2只显示全景: 不能任意行走。 过渡时显示贴图材质非edl的点云(否则有折痕不贴合)。
  49921. 3混合:都显示。 不能任意行走。过渡时显示贴图材质非edl的点云(因为只显示点云的话不太美,点云很碎,不细腻)
  49922. */
  49923. window.testLevelSteps = function(steps){//[0.4,0.7,1]
  49924. if(!steps){
  49925. let s = Potree.config.pointDensity;
  49926. steps = [s.low.maxLevelPercent, s.middle.maxLevelPercent, s.high.maxLevelPercent, ];
  49927. }
  49928. let max = 1;
  49929. while(++max<=12){
  49930. let r1 = steps.map(e=>e * max);
  49931. let r2 = steps.map(e=>Math.round(e * max));
  49932. console.log(`当nodeMaxLevel为${max}时,每一级的level分别为${r2}, (小数:${r1})`);
  49933. }
  49934. console.log('请检查每一层的三个level是否有重复');
  49935. };
  49936. function getPrefix(){
  49937. let u = window.location.href.split('//');
  49938. let v = u[1].split('/');
  49939. return v[0]
  49940. }
  49941. let isTest = browser.urlHasValue('test');
  49942. let settings = {//设置 可修改
  49943. editType : '',
  49944. number: '', //场景序号
  49945. originDatasetId:'',//场景原本的数据集id,应该就是数据集第一个吧
  49946. isOfficial:false,
  49947. webSite:'testdata',//正式:'datav1', //不同环境对应的静态文件的地址不同
  49948. isLocal:false, //是否本地 局域网版本
  49949. libsUrl:'../libs/',
  49950. displayMode:'',
  49951. isTest ,
  49952. prefix: getPrefix(),
  49953. pointDensity: '', UserPointDensity:'',//pointDensity会随着进入不同的模块而自动改变,UserPointDensity记录了用户的设置
  49954. UserDensityPercent:null,//点云密度百分比
  49955. ifShowMarker:true,//显示漫游点
  49956. floorplanType:{},//平面图类型 'default' | 'diy' 不同数据集不同{datasetId:...}
  49957. floorplanEnable:false,
  49958. floorplanEnables:{},
  49959. floorplanRequests:{},//开始加载了的
  49960. mapEnable:true,//地图区域是否加载地图
  49961. cameraFar : config$1.view.far, //相机最远范围 1-300
  49962. //limitFar: true, //是否使用setting的cameraFar来限制(如在点云裁剪时为false)
  49963. showPanoMesh:false, //显示小球,
  49964. dblToFocusPoint:false,//调试时如果需要双击飞向某个点云的点,就打开。此时不在漫游点的话单击将无法漫游。//因和单击漫游冲突
  49965. unableNavigate : false,//进入如裁剪界面时 禁止漫游
  49966. sizeFitToLevel: false,//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  49967. zoom:{
  49968. enabled : true,
  49969. min:1,
  49970. max: config$1.highQualityMaxZoom
  49971. },
  49972. navConstantly:true,
  49973. navTileClass: /* browser.isMobile() ? '1k' : */ '2k', //默认加载到
  49974. tileClass:'4k', //最高可达
  49975. /* loadTilesWhenUnfocus:false, //页面unfocus时也仍在加载tiles
  49976. loadPointsWhenUnfocus:true, //页面unfocus时也仍在加载点云 */
  49977. //initialShowPano:true
  49978. drawEntityData: false, //包括marker、线
  49979. zoomFromPointert:{//定点缩放(包括点云模式、全景模式、地图)
  49980. whenPanos:true,
  49981. whenPointCloud:true,
  49982. map:true,
  49983. },
  49984. rotAroundPoint:true,//点云模式是否能绕intersectPoint旋转
  49985. tourTestCameraMove:false, //测试镜头时,不移动真实的镜头, 只移动frustum
  49986. cameraAniSmoothRatio : 20, //镜头动画平滑系数,越高越平滑
  49987. urls : $.extend({}, config$1.urls, {
  49988. prefix : config$1.urls.prefix4 //主要使用的 是测试环境,根据不同工程更改
  49989. }),
  49990. useDepthTex: true,//使用深度贴图,但不代表一定有(得到的intersect更快速准确和稳定) SS-t-7DUfWAUZ3V
  49991. //matUseDepth:false,
  49992. //panoEdit:
  49993. datasetsPanos:{},
  49994. //mergeModel:
  49995. boundAddObjs:false,
  49996. intersectOnObjs:false,
  49997. intersectWhenHover:true,
  49998. depTexLocBindDataset: true,//是否在pano模式下,使用深度图得到intersect的话,改intersect能属于该pano所在的点云。也就相当于在全景模式下intersect的点属于该全景图
  49999. notAdditiveBlending:false, //点云是否使用普通的blend, 否则会曝光过渡
  50000. precision:2, // 两位小数
  50001. unit: 'm',
  50002. useV4url:true, //v4的全景图等路径不一样 scene_view_data
  50003. useRTskybox:true, //直接使用rtEDL绘制到屏幕,当是全景模式时. 在降4倍时能给render节省1毫秒,gpu时间未测
  50004. useRTPoint:true, //直接使用rtEDL绘制到屏幕,当是点云模式时。可以大大节省gpu时间。但有锯齿
  50005. pointEnableRT:false,//点云模式时是否绘制到rtEDL。如果不需要遮挡效果就不需绘制
  50006. cloudSameMat:true, //因为点云个数较多,就使用相同的材质,可见降低绘制速度(要保证所有点云的maxNodelevel一样,且要算出 material.spacing的平均值)
  50007. showCompass : isTest,
  50008. showAxis : isTest,
  50009. // testCube : true,
  50010. // moveToCenter:true, //针对数据集间隔很远的场景 dis>5000 容易抖动
  50011. tiles3DMaxMemory: config$1.tiles3DMaxMemory,
  50012. adsorption:false,//测量时吸附点
  50013. };
  50014. settings.isLocalhost = settings.prefix.includes('localhost');
  50015. settings.isFormal = browser.urlHasValue('formal');//正式环境 本地测试
  50016. if(settings.isFormal){
  50017. settings.urls.prefix = settings.urls.prefix5;
  50018. settings.webSite = 'datav1';
  50019. }
  50020. console.log('2023-11');
  50021. class U {
  50022. static toVector3(v, offset) {
  50023. return new Vector3().fromArray(v, offset || 0);
  50024. }
  50025. static toBox3(b) {
  50026. return new Box3(U.toVector3(b), U.toVector3(b, 3));
  50027. };
  50028. static findDim(schema, name) {
  50029. var dim = schema.find((dim) => dim.name == name);
  50030. if (!dim) throw new Error('Failed to find ' + name + ' in schema');
  50031. return dim;
  50032. }
  50033. static sphereFrom(b) {
  50034. return b.getBoundingSphere(new Sphere());
  50035. }
  50036. };
  50037. class PointCloudEptGeometry {
  50038. constructor(url, info) {
  50039. let version = info.version;
  50040. let schema = info.schema;
  50041. let bounds = info.bounds;
  50042. let boundsConforming = info.boundsConforming;
  50043. let xyz = [
  50044. U.findDim(schema, 'X'),
  50045. U.findDim(schema, 'Y'),
  50046. U.findDim(schema, 'Z')
  50047. ];
  50048. let scale = xyz.map((d) => d.scale || 1);
  50049. let offset = xyz.map((d) => d.offset || 0);
  50050. this.eptScale = U.toVector3(scale);
  50051. this.eptOffset = U.toVector3(offset);
  50052. this.url = url;
  50053. this.info = info;
  50054. this.type = 'ept';
  50055. this.schema = schema;
  50056. this.span = info.span || info.ticks;
  50057. this.boundingBox = U.toBox3(bounds);
  50058. this.tightBoundingBox = U.toBox3(boundsConforming);
  50059. this.offset = U.toVector3([0, 0, 0]);
  50060. this.boundingSphere = U.sphereFrom(this.boundingBox);
  50061. this.tightBoundingSphere = U.sphereFrom(this.tightBoundingBox);
  50062. this.version = new Potree.Version('1.7');
  50063. this.projection = null;
  50064. this.fallbackProjection = null;
  50065. if (info.srs && info.srs.horizontal) {
  50066. this.projection = info.srs.authority + ':' + info.srs.horizontal;
  50067. }
  50068. if (info.srs.wkt) {
  50069. if (!this.projection) this.projection = info.srs.wkt;
  50070. else this.fallbackProjection = info.srs.wkt;
  50071. }
  50072. {
  50073. // TODO [mschuetz]: named projections that proj4 can't handle seem to cause problems.
  50074. // remove them for now
  50075. try{
  50076. proj4(this.projection);
  50077. }catch(e){
  50078. this.projection = null;
  50079. }
  50080. }
  50081. {
  50082. const attributes = new PointAttributes();
  50083. attributes.add(PointAttribute.POSITION_CARTESIAN);
  50084. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  50085. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  50086. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  50087. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  50088. attributes.add(new PointAttribute("returnNumber", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  50089. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  50090. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  50091. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  50092. this.pointAttributes = attributes;
  50093. }
  50094. this.spacing =
  50095. (this.boundingBox.max.x - this.boundingBox.min.x) / this.span;
  50096. let hierarchyType = info.hierarchyType || 'json';
  50097. const dataType = info.dataType;
  50098. if (dataType == 'laszip') {
  50099. this.loader = new Potree.EptLaszipLoader();
  50100. }
  50101. else if (dataType == 'binary') {
  50102. this.loader = new Potree.EptBinaryLoader();
  50103. }
  50104. else if (dataType == 'zstandard') {
  50105. this.loader = new Potree.EptZstandardLoader();
  50106. }
  50107. else {
  50108. throw new Error('Could not read data type: ' + dataType);
  50109. }
  50110. }
  50111. };
  50112. class EptKey {
  50113. constructor(ept, b, d, x, y, z) {
  50114. this.ept = ept;
  50115. this.b = b;
  50116. this.d = d;
  50117. this.x = x || 0;
  50118. this.y = y || 0;
  50119. this.z = z || 0;
  50120. }
  50121. name() {
  50122. return this.d + '-' + this.x + '-' + this.y + '-' + this.z;
  50123. }
  50124. step(a, b, c) {
  50125. let min = this.b.min.clone();
  50126. let max = this.b.max.clone();
  50127. let dst = new Vector3().subVectors(max, min);
  50128. if (a) min.x += dst.x / 2;
  50129. else max.x -= dst.x / 2;
  50130. if (b) min.y += dst.y / 2;
  50131. else max.y -= dst.y / 2;
  50132. if (c) min.z += dst.z / 2;
  50133. else max.z -= dst.z / 2;
  50134. return new Potree.EptKey(
  50135. this.ept,
  50136. new Box3(min, max),
  50137. this.d + 1,
  50138. this.x * 2 + a,
  50139. this.y * 2 + b,
  50140. this.z * 2 + c);
  50141. }
  50142. children() {
  50143. var result = [];
  50144. for (var a = 0; a < 2; ++a) {
  50145. for (var b = 0; b < 2; ++b) {
  50146. for (var c = 0; c < 2; ++c) {
  50147. var add = this.step(a, b, c).name();
  50148. if (!result.includes(add)) result = result.concat(add);
  50149. }
  50150. }
  50151. }
  50152. return result;
  50153. }
  50154. }
  50155. class PointCloudEptGeometryNode extends PointCloudTreeNode {
  50156. constructor(ept, b, d, x, y, z) {
  50157. super();
  50158. this.ept = ept;
  50159. this.key = new Potree.EptKey(
  50160. this.ept,
  50161. b || this.ept.boundingBox,
  50162. d || 0,
  50163. x,
  50164. y,
  50165. z);
  50166. this.id = PointCloudEptGeometryNode.IDCount++;
  50167. this.geometry = null;
  50168. this.boundingBox = this.key.b;
  50169. this.tightBoundingBox = this.boundingBox;
  50170. this.spacing = this.ept.spacing / Math.pow(2, this.key.d);
  50171. this.boundingSphere = U.sphereFrom(this.boundingBox);
  50172. // These are set during hierarchy loading.
  50173. this.hasChildren = false;
  50174. this.children = { };
  50175. this.numPoints = -1;
  50176. this.level = this.key.d;
  50177. this.loaded = false;
  50178. this.loading = false;
  50179. this.oneTimeDisposeHandlers = [];
  50180. let k = this.key;
  50181. this.name = this.toPotreeName(k.d, k.x, k.y, k.z);
  50182. this.index = parseInt(this.name.charAt(this.name.length - 1));
  50183. }
  50184. isGeometryNode() { return true; }
  50185. getLevel() { return this.level; }
  50186. isTreeNode() { return false; }
  50187. isLoaded() { return this.loaded; }
  50188. getBoundingSphere() { return this.boundingSphere; }
  50189. getBoundingBox() { return this.boundingBox; }
  50190. url() { return this.ept.url + 'ept-data/' + this.filename(); }
  50191. getNumPoints() { return this.numPoints; }
  50192. filename() { return this.key.name(); }
  50193. getChildren() {
  50194. let children = [];
  50195. for (let i = 0; i < 8; i++) {
  50196. if (this.children[i]) {
  50197. children.push(this.children[i]);
  50198. }
  50199. }
  50200. return children;
  50201. }
  50202. addChild(child) {
  50203. this.children[child.index] = child;
  50204. child.parent = this;
  50205. }
  50206. load() {
  50207. if (this.loaded || this.loading) return;
  50208. if (Potree.numNodesLoading >= Potree.maxNodesLoading) return;
  50209. this.loading = true;
  50210. ++Potree.numNodesLoading;
  50211. if (this.numPoints == -1) this.loadHierarchy();
  50212. this.loadPoints();
  50213. }
  50214. loadPoints(){
  50215. this.ept.loader.load(this);
  50216. }
  50217. async loadHierarchy() {
  50218. let nodes = { };
  50219. nodes[this.filename()] = this;
  50220. this.hasChildren = false;
  50221. let eptHierarchyFile =
  50222. `${this.ept.url}ept-hierarchy/${this.filename()}.json`;
  50223. let response = await fetch(eptHierarchyFile);
  50224. let hier = await response.json();
  50225. // Since we want to traverse top-down, and 10 comes
  50226. // lexicographically before 9 (for example), do a deep sort.
  50227. var keys = Object.keys(hier).sort((a, b) => {
  50228. let [da, xa, ya, za] = a.split('-').map((n) => parseInt(n, 10));
  50229. let [db, xb, yb, zb] = b.split('-').map((n) => parseInt(n, 10));
  50230. if (da < db) return -1; if (da > db) return 1;
  50231. if (xa < xb) return -1; if (xa > xb) return 1;
  50232. if (ya < yb) return -1; if (ya > yb) return 1;
  50233. if (za < zb) return -1; if (za > zb) return 1;
  50234. return 0;
  50235. });
  50236. keys.forEach((v) => {
  50237. let [d, x, y, z] = v.split('-').map((n) => parseInt(n, 10));
  50238. let a = x & 1, b = y & 1, c = z & 1;
  50239. let parentName =
  50240. (d - 1) + '-' + (x >> 1) + '-' + (y >> 1) + '-' + (z >> 1);
  50241. let parentNode = nodes[parentName];
  50242. if (!parentNode) return;
  50243. parentNode.hasChildren = true;
  50244. let key = parentNode.key.step(a, b, c);
  50245. let node = new Potree.PointCloudEptGeometryNode(
  50246. this.ept,
  50247. key.b,
  50248. key.d,
  50249. key.x,
  50250. key.y,
  50251. key.z);
  50252. node.level = d;
  50253. node.numPoints = hier[v];
  50254. parentNode.addChild(node);
  50255. nodes[key.name()] = node;
  50256. });
  50257. }
  50258. doneLoading(bufferGeometry, tightBoundingBox, np, mean) {
  50259. bufferGeometry.boundingBox = this.boundingBox;
  50260. this.geometry = bufferGeometry;
  50261. this.tightBoundingBox = tightBoundingBox;
  50262. this.numPoints = np;
  50263. this.mean = mean;
  50264. this.loaded = true;
  50265. this.loading = false;
  50266. --Potree.numNodesLoading;
  50267. }
  50268. toPotreeName(d, x, y, z) {
  50269. var name = 'r';
  50270. for (var i = 0; i < d; ++i) {
  50271. var shift = d - i - 1;
  50272. var mask = 1 << shift;
  50273. var step = 0;
  50274. if (x & mask) step += 4;
  50275. if (y & mask) step += 2;
  50276. if (z & mask) step += 1;
  50277. name += step;
  50278. }
  50279. return name;
  50280. }
  50281. dispose() {
  50282. if (this.geometry && this.parent != null) {
  50283. this.geometry.dispose();
  50284. this.geometry = null;
  50285. this.loaded = false;
  50286. // this.dispatchEvent( { type: 'dispose' } );
  50287. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  50288. let handler = this.oneTimeDisposeHandlers[i];
  50289. handler();
  50290. }
  50291. this.oneTimeDisposeHandlers = [];
  50292. }
  50293. }
  50294. }
  50295. PointCloudEptGeometryNode.IDCount = 0;
  50296. class ExtendPointCloudOctree extends PointCloudOctree{
  50297. constructor(geometry, material){
  50298. material = material || new ExtendPointCloudMaterial();
  50299. super(geometry, material);
  50300. //xzw move from material 。 adaptive_point_size才使用
  50301. /* this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new THREE.Color(0xffffff));
  50302. this.visibleNodesTexture.minFilter = THREE.NearestFilter;
  50303. this.visibleNodesTexture.magFilter = THREE.NearestFilter; */
  50304. this.boundingBox = this.pcoGeometry.tightBoundingBox;//this.pcoGeometry.boundingBox; //boundingBox是正方体,所以换掉
  50305. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  50306. this.nodeMaxLevel = 0;//add
  50307. this.maxLevel = Infinity;
  50308. this.temp = { sizeFitToLevel:{}, opacity:{}};//add
  50309. //add
  50310. this.panos = [];
  50311. this.matrixAutoUpdate = false; //最好禁止updateMatrix 直接使用matrixWorld
  50312. this.orientationUser = 0;
  50313. this.translateUser = new Vector3;
  50314. this.rotateMatrix = new Matrix4;
  50315. this.transformMatrix = new Matrix4;// 数据集的变化矩阵
  50316. this.transformInvMatrix = new Matrix4;
  50317. /* this.transformMatrix2 = new THREE.Matrix4;// 数据集的变化矩阵
  50318. this.transformInvMatrix2 = new THREE.Matrix4; */
  50319. this.rotateInvMatrix = new Matrix4;
  50320. this.material.spacing = this.pcoGeometry.spacing;//初始化一下 以便于设置pointsize
  50321. this.nodeMaxLevelPredict = this.predictNodeMaxLevel();//预测maxNodeLevel
  50322. this.testMaxNodeCount = this.testMaxNodeCount2 = 0;
  50323. this._visible = true;
  50324. this.pcoGeometry.addEventListener('updateNodeMaxLevel', this.updateNodeMaxLevel.bind(this));
  50325. this.isPointcloud = true; //add
  50326. }
  50327. /*
  50328. 注释:node的level从最大的box 0开始。
  50329. 且加载任意一个node必定也会加载它的所有祖先。(如visibleNodes中有一个level为4,则一定有3,2,1,0)
  50330. visibleNodes就是所有可见的node,比如:
  50331. 如果相机在0这个位置朝下,这时候的visibleNodes中只有一个level为0的node;
  50332. 而如果朝上看,上方的几个node如果在视野中占据足够大的位置的话,就会加载。
  50333. 如果相机在2这个位置朝上,这时候的visibleNodes中所包含的level为: 0,1,2
  50334. ________________
  50335. | | | |
  50336. |__2| | |
  50337. | 1 | 1 |
  50338. |_______|_______|
  50339. | |
  50340. | |
  50341. | 0 |
  50342. |_______________|
  50343. 查看box可在potree中开启
  50344. */
  50345. updateNodeMaxLevel(e){//目前点云包含node的最高level
  50346. var level = Math.max(e.level, this.nodeMaxLevel);
  50347. if(level != this.nodeMaxLevel){
  50348. this.nodeMaxLevel = level;
  50349. //viewer.dispatchEvent({type:'updateNodeMaxLevel', pointcloud: this, nodeMaxLevel:level})
  50350. console.log('updateNodeMaxLevel ' + this.dataset_id + " : "+ this.nodeMaxLevel);
  50351. this.setPointLevel();//重新计算
  50352. if(!Potree.settings.sizeFitToLevel){
  50353. this.changePointSize();
  50354. }
  50355. }
  50356. }//注:在没有加载到真实的 nodeMaxLevel之前,点云会显示得偏大
  50357. //panoEdit时比预测值小很多?
  50358. testMaxNodeLevel(camera){//手动使maxLevel达到最高,从而迫使updateNodeMaxLevel。 因为Potree.settings.pointDensity 不为 'high'时,maxLevel不是所加载的最高,就很容易加载不出下一个层级,导致无法知道nodeMaxLevel
  50359. if(this.testMaxNodeLevelDone ) return
  50360. //if(this.nodeMaxLevel > this.nodeMaxLevelPredict.min )return
  50361. if( this.nodeMaxLevel==0 )return true
  50362. if(camera.type == "OrthographicCamera" || this.testMaxNodeCount < 50){
  50363. if(!Potree.Utils.isInsideFrustum(this.bound, camera)){
  50364. return true
  50365. }
  50366. }else if( !viewer.atDatasets.includes(this))return true //否则老远就count++
  50367. let levels = this.visibleNodes.map(e=>e.getLevel());
  50368. let actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level
  50369. if(actMaxLevel < this.maxLevel)return true// 还没加载到能加载到的最高。 但在细节设置较低时,排除作用微弱。
  50370. //尝试加载出更高级的level
  50371. let old = this.maxLevel;
  50372. this.maxLevel = 12;
  50373. //var visibleNodes1 = this.visibleNodes.map(e=>e.getLevel())
  50374. //console.log('visibleNodes1',visibleNodes1)
  50375. Potree.updatePointClouds([this], viewer.scene.getActiveCamera(), viewer.mainViewport.resolution );
  50376. //不在camera可视范围内还是加载不出来。即使临时修改位置
  50377. var visibleNodes2 = this.visibleNodes.map(e=>e.getLevel());
  50378. //console.log('visibleNodes2',visibleNodes2)
  50379. this.maxLevel = old;
  50380. this.testMaxNodeCount ++;
  50381. viewer.testMaxNodeCount ++;
  50382. //console.log('testMaxNodeCount', this.dataset_id, this.testMaxNodeCount, 'nodeMaxLevel', this.nodeMaxLevel )
  50383. if( this.testMaxNodeCount == Potree.config.testNodeCount1 ){//差不多等当前所在数据集nodeMaxLevel加载出来
  50384. this.changePointSize(); //重新更新一下大小。因之前用的是nodeMaxLevelPredict (防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现
  50385. }
  50386. if(this.testMaxNodeCount > 100){
  50387. console.log('testMaxNodeLevel次数超出,强制结束:',this.dataset_id, this.nodeMaxLevel, this.nodeMaxLevelPredict.min);
  50388. this.testMaxNodeLevelDone = 'moreThanMaxCount';
  50389. return; //在可以看见点云的情况下,超时,有可能是预测的max是错的
  50390. }
  50391. if(this.nodeMaxLevel < this.nodeMaxLevelPredict.min) return true //仍需要继续testMaxNodeLevel
  50392. this.testMaxNodeCount2 ++; // 已经> this.nodeMaxLevelPredict.min 后,开始计数。因为min可能低于真实nodeMaxLevel所以要再试几次
  50393. if(this.testMaxNodeCount2 < 50) return true //再试几次 ( 主要是细节调得低时需要多测几次才加载到
  50394. this.testMaxNodeLevelDone = true;
  50395. }
  50396. updateMatrixWorld(force){//add
  50397. super.updateMatrixWorld(force);
  50398. this.matrixWorldInverse = this.matrixWorld.clone().invert();
  50399. }
  50400. setPointLevel(){
  50401. var pointDensity = Potree.settings.pointDensity;
  50402. var config = Potree.config.pointDensity[pointDensity];
  50403. if(!config)return
  50404. /* if(this.testingMaxLevel){
  50405. this.maxLevel = 12;//先加载到最大的直到测试完毕。由于5个level为一组来加载,所以如果写4最高能加载到5,如果写5最高能加载到下一个级别的最高也就是10
  50406. //console.log('maxLevel: '+e.maxLevel + ' testingMaxLevel中 ' )
  50407. }else{ */
  50408. let percent = config.percentByUser && Potree.settings.UserDensityPercent != void 0 ? Potree.settings.UserDensityPercent : config.maxLevelPercent;
  50409. this.maxLevel = Math.round( percent * this.nodeMaxLevel);
  50410. //console.log('maxLevel: '+e.maxLevel + ', density : '+Potree.settings.pointDensity, ", percent :"+percent);
  50411. if(Potree.settings.sizeFitToLevel){
  50412. this.changePointSize();
  50413. }
  50414. this.changePointOpacity();
  50415. //}
  50416. viewer.dealBeforeRender || viewer.dispatchEvent('content_changed');
  50417. }
  50418. //预测可能的nodeMaxLevel:
  50419. predictNodeMaxLevel(){//预测maxNodeLevel。 可能只适用于我们相机拍的点云
  50420. let spacing = {min:0.005, max:0.014};//最小节的两点间的距离 ,获得方法:spacing / Math.pow(2, nodeMaxLevel)。 目前观测的我们自己拍的这个数值的范围大概是这样
  50421. let min = Math.log2(this.material.spacing / spacing.max); //有见过最大是0.01368
  50422. let max = Math.log2(this.material.spacing / spacing.min); //大部分是 0.006
  50423. //console.log('predictNodeMaxLevel:', this.name , min, max )
  50424. //只对深时相机,其他相机不准
  50425. return {min, max}
  50426. }
  50427. getHighestNodeSpacing(){
  50428. return this.material.spacing / Math.pow(2, this.nodeMaxLevel) //前提是这个nodeMaxLevel是准确的
  50429. }
  50430. updateMaterial (material, visibleNodes, camera, renderer, resolution) {//改
  50431. material.fov = camera.fov * (Math.PI / 180);
  50432. /* material.screenWidth = renderer.domElement.clientWidth;
  50433. material.screenHeight = renderer.domElement.clientHeight; */
  50434. material.resolution = resolution;
  50435. material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  50436. material.near = camera.near;
  50437. material.far = camera.far;
  50438. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  50439. }
  50440. pick(viewer, viewport, camera, ray, params = {}){//改
  50441. let renderer = viewer.renderer;
  50442. let pRenderer = viewer.pRenderer;
  50443. viewer.addTimeMark('pick','start');
  50444. let getVal = (a, b) => a != void 0 ? a : b;
  50445. let r0 = this.nodeMaxLevel > 0 ? this.maxLevel/this.nodeMaxLevel : 0.5;
  50446. let pickWindowSize_ = MathUtils.clamp( Math.round((1.1-r0)*80), 5, 100);
  50447. let pickWindowSize = getVal(params.pickWindowSize, pickWindowSize_ ); /* 65 */ //拾取像素边长,越小越精准,但点云稀疏的话可能容易出现识别不到的情况。 另外左下侧会有缝隙无法识别到,缝隙大小和这个值有关//突然发现pickWindowSize在一百以内的变化对pick费时影响甚微,1和100差1毫秒不到,但400时会多4毫秒
  50448. if(camera.type == 'OrthographicCamera'){
  50449. var cameraDir = new Vector3(0,0,-1).applyQuaternion(camera.quaternion);
  50450. pickWindowSize *= 4; //pointsize比较大时截取太小会没多少点可以选
  50451. }
  50452. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  50453. let size = viewport ? viewport.resolution : renderer.getSize(new Vector2());
  50454. let width = Math.ceil(getVal(params.width, size.width)); //renderTarget大小。影响识别精度
  50455. let height = Math.ceil(getVal(params.height, size.height));
  50456. let screenshot = ()=>{
  50457. if(window.testScreen){
  50458. let dataUrl = Potree.Utils.renderTargetToDataUrl(pickState.renderTarget, width, height, renderer);
  50459. Common.downloadFile(dataUrl, 'screenshot.jpg'); //为什么图片上不是只有pickWindowSize区域有颜色??
  50460. window.testScreen = 0;
  50461. }
  50462. };
  50463. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  50464. let pointSize = getVal(params.pointSize, this.material.size);
  50465. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  50466. if (nodes.length === 0) {
  50467. return null;
  50468. }
  50469. //console.log('nodes.length != 0', this.name)
  50470. if (!this.pickState) {
  50471. let scene = new Scene();
  50472. let material = new ExtendPointCloudMaterial();
  50473. material.activeAttributeName = "indices";
  50474. let renderTarget = new WebGLRenderTarget(
  50475. 1, 1,
  50476. { minFilter: LinearFilter,
  50477. magFilter: NearestFilter,
  50478. format: RGBAFormat }
  50479. );
  50480. this.pickState = {
  50481. renderTarget: renderTarget,
  50482. material: material,
  50483. scene: scene
  50484. };
  50485. };
  50486. let pickState = this.pickState;
  50487. let pickMaterial = pickState.material;
  50488. { // update pick material
  50489. pickMaterial.pointSizeType = pointSizeType;
  50490. //pickMaterial.shape = this.material.shape;
  50491. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  50492. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  50493. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  50494. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  50495. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  50496. pickMaterial.activeAttributeName = "indices";
  50497. pickMaterial.size = pointSize;
  50498. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  50499. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  50500. pickMaterial.classification = this.material.classification;
  50501. pickMaterial.recomputeClassification();
  50502. //pickClipped判断转移到上一层函数
  50503. let {bigClipInBox,clipBoxes_in,clipBoxes_out} = this.material;
  50504. pickMaterial.setClipBoxes(bigClipInBox, clipBoxes_in, clipBoxes_out, []);
  50505. this.updateMaterial(pickMaterial, nodes, camera, renderer, new Vector2(width, height));
  50506. }
  50507. pickState.renderTarget.setSize(width, height); //仅绘制屏幕大小的,而不乘以devicePixelRatio
  50508. let pixelPos = new Vector2(params.x, params.y);
  50509. let gl = renderer.getContext();
  50510. gl.enable(gl.SCISSOR_TEST);
  50511. gl.scissor( //规定渲染范围,只渲染一小块
  50512. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  50513. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  50514. parseInt(pickWindowSize), parseInt(pickWindowSize));
  50515. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  50516. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  50517. renderer.state.setBlending(NoBlending);
  50518. { // RENDER
  50519. renderer.setRenderTarget(pickState.renderTarget);
  50520. gl.clearColor(0, 0, 0, 0);
  50521. renderer.clear(true, true, true);
  50522. let tmp = this.material;
  50523. this.material = pickMaterial;
  50524. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  50525. screenshot();
  50526. this.material = tmp;
  50527. }
  50528. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  50529. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  50530. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  50531. /* let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  50532. let h = parseInt(Math.min(y + pickWindowSize, height) - y); */
  50533. let pixelCount = pickWindowSize * pickWindowSize;//w * h;
  50534. let buffer = new Uint8Array(4 * pixelCount);
  50535. //w<pickWindowSize会报错
  50536. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer); //这句花费最多时间 pc:2-4, 即使只有1*1像素
  50537. renderer.setRenderTarget(null);
  50538. renderer.state.reset();
  50539. renderer.setScissorTest(false);
  50540. gl.disable(gl.SCISSOR_TEST);
  50541. let pixels = buffer;
  50542. let ibuffer = new Uint32Array(buffer.buffer); //四个数整合成一个
  50543. // find closest hit inside pixelWindow boundaries
  50544. let min = Number.MAX_VALUE;
  50545. let hits = [], hits2 = [], rSquare;
  50546. if(!params.all){
  50547. let r = MathUtils.clamp(Math.floor(pickWindowSize / 2),1, 40);
  50548. rSquare = r * r;
  50549. }
  50550. for (let u = 0; u < pickWindowSize; u++) {
  50551. for (let v = 0; v < pickWindowSize; v++) {
  50552. let offset = (u + v * pickWindowSize);
  50553. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  50554. let pcIndex = pixels[4 * offset + 3];//nodes index(第四位)
  50555. pixels[4 * offset + 3] = 0; //去除nodes index后剩下的是index(前三位)
  50556. let pIndex = ibuffer[offset]; //index
  50557. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  50558. let hit = {
  50559. pIndex: pIndex,
  50560. pcIndex: pcIndex,
  50561. distanceToCenter: distance
  50562. };
  50563. if(params.all){
  50564. hits.push(hit);
  50565. }else {
  50566. if(hits.length > 0){//最后选取的是最靠近鼠标的那个pick
  50567. if(distance < hits[0].distanceToCenter){
  50568. hits[0] = hit;
  50569. }
  50570. }else {
  50571. hits.push(hit);
  50572. }
  50573. if(distance < rSquare) hits2.push(hit); //add
  50574. }
  50575. }
  50576. }
  50577. }
  50578. if(!params.all){
  50579. if(hits2.length){//add
  50580. hits = hits2;
  50581. }
  50582. }
  50583. // { // DEBUG: show panel with pick image
  50584. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  50585. // let screenshot = img.src;
  50586. // if(!this.debugDIV){
  50587. // this.debugDIV = $(`
  50588. // <div id="pickDebug"
  50589. // style="position: absolute;
  50590. // right: 400px; width: 300px;
  50591. // bottom: 44px; width: 300px;
  50592. // z-index: 1000;
  50593. // "></div>`);
  50594. // $(document.body).append(this.debugDIV);
  50595. // }
  50596. // this.debugDIV.empty();
  50597. // this.debugDIV.append($(`<img src="${screenshot}"
  50598. // style="transform: scaleY(-1); width: 300px"/>`));
  50599. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  50600. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  50601. // }
  50602. for(let hit of hits){
  50603. let point = {};
  50604. if (!nodes[hit.pcIndex]) {
  50605. return null;
  50606. }
  50607. let node = nodes[hit.pcIndex];
  50608. let pc = node.sceneNode;
  50609. let geometry = node.geometryNode.geometry;
  50610. for(let attributeName in geometry.attributes){
  50611. let attribute = geometry.attributes[attributeName];
  50612. if (attributeName === 'position') {
  50613. let x = attribute.array[3 * hit.pIndex + 0];
  50614. let y = attribute.array[3 * hit.pIndex + 1];
  50615. let z = attribute.array[3 * hit.pIndex + 2];
  50616. let position = new Vector3(x, y, z);
  50617. position.applyMatrix4( pc.matrixWorld );
  50618. point[attributeName] = position;
  50619. //add
  50620. if(!params.all){
  50621. if(camera.type == 'OrthographicCamera'){
  50622. let vec = new Vector3().subVectors(position, camera.position);
  50623. hit.disSquare = vec.projectOnVector( cameraDir ).length(); //只考虑到相机的垂直距离
  50624. }else {
  50625. hit.disSquare = camera.position.distanceTo(position);
  50626. }
  50627. }
  50628. } else if (attributeName === 'indices') {
  50629. } else {
  50630. let values = attribute.array.slice(attribute.itemSize * hit.pIndex, attribute.itemSize * (hit.pIndex + 1)) ;
  50631. if(attribute.potree){
  50632. const {scale, offset} = attribute.potree;
  50633. values = values.map(v => v / scale + offset);
  50634. }
  50635. point[attributeName] = values;
  50636. //debugger;
  50637. //if (values.itemSize === 1) {
  50638. // point[attribute.name] = values.array[hit.pIndex];
  50639. //} else {
  50640. // let value = [];
  50641. // for (let j = 0; j < values.itemSize; j++) {
  50642. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  50643. // }
  50644. // point[attribute.name] = value;
  50645. //}
  50646. }
  50647. }
  50648. hit.point = point;
  50649. }
  50650. viewer.addTimeMark('pick','end');
  50651. if(params.all){
  50652. return hits.map(hit => hit.point);
  50653. }else {
  50654. if(hits.length === 0){
  50655. return null;
  50656. }else {
  50657. //为了防止透过点云缝隙,选到后排的点云,将选取的位置离相机的距离考虑进去。倾向选择离相机近、且离鼠标位置近的点。(否则按照原方案只选离鼠标位置最近的,可能从高楼不小心走到下层,导航选点也是)
  50658. let sorted1 = hits.sort( (a, b) => a.disSquare - b.disSquare ).slice();
  50659. let nearest = sorted1[0]; //return nearest.point; //直接用最近点 在点云稀疏时不太跟手,如地面上,最近点往往在鼠标下方
  50660. let r = 10;
  50661. hits.forEach( hit=>{
  50662. let disDiff = hit.disSquare - nearest.disSquare; //和最近点的偏差
  50663. hit.disDiff = disDiff;
  50664. hit.score = -hit.distanceToCenter - disDiff * r;
  50665. });
  50666. let sorted2 = hits.sort( (a, b) => b.score - a.score );
  50667. //console.log(sorted2[0].point.position.z )
  50668. return sorted2[0].point;
  50669. }
  50670. }
  50671. }
  50672. // 设置点大小
  50673. changePointSize(num, sizeFitToLevel) {
  50674. let size, nodeMaxLevel;
  50675. let dontRender = viewer.dealBeforeRender;
  50676. if(this.material.pointSizeType != PointSizeType.ATTENUATED){
  50677. num && (size = num / Potree.config.material.realPointSize / 1.3);
  50678. }else {
  50679. let num_ = num;
  50680. if (num_ == void 0) {
  50681. num_ = this.temp.pointSize;
  50682. } else {
  50683. this.temp.pointSize = num_;
  50684. }
  50685. num_ = num_ / (Potree.config.material.realPointSize / Potree.config.material.pointSize); //兼容
  50686. num_ = Math.pow(num_, 1.05) * 6;
  50687. nodeMaxLevel = this.testMaxNodeCount >= Potree.config.testNodeCount1 ? this.nodeMaxLevel : Math.max(this.nodeMaxLevel, this.nodeMaxLevelPredict.max );//防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现
  50688. if(sizeFitToLevel || Potree.settings.sizeFitToLevel){//按照点云质量来调整的版本: 近似将pointSizeType换成ADAPTIVE
  50689. let str = this.temp.pointSize+':'+this.maxLevel+':'+ nodeMaxLevel;
  50690. let value = this.temp.sizeFitToLevel[str]; //储存。防止每次渲染(反复切换density)都要算。
  50691. if(value){
  50692. size = value;
  50693. }else {
  50694. let base = this.material.spacing / Math.pow(2, this.maxLevel); //点云大小在level为0时设置为spacing,每长一级,大小就除以2. (不同场景还是会有偏差)
  50695. let r = nodeMaxLevel > 0 ? this.maxLevel / nodeMaxLevel : 0.5; //越大,越精细,需要越缩小
  50696. base *= nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(r, 3*r+0.3 )) : 0.1; //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙(但是ortho是不用缩小的,如果能分开判断就好了)
  50697. //base *= nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(this.maxLevel / nodeMaxLevel, 1.1)) : 0.1 //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙(但是ortho是不用缩小的,如果能分开判断就好了)
  50698. size = base * 5 * num_;/* * window.devicePixelRatio */
  50699. //在t-8BCqxQAr93 会议室 和 t-e2Kb2iU 隧道 两个场景里调节,因为它们的spacing相差较大,观察会议室墙壁的龟裂程度
  50700. this.temp.sizeFitToLevel[str] = size;
  50701. }
  50702. }else {
  50703. /* let base = 0.007; */ let base = this.material.spacing / Math.pow(2, nodeMaxLevel); //点云大小在level为0时设置为spacing,每长一级,大小就除以2
  50704. //base的数值理论上应该是右侧算出来的,但发现有的场景nodeMaxLevel和nodeMaxLevelPredict差别较大的点云显示也过大,而直接换成固定值反而可以适应所有场景。该固定值来源于 getHighestNodeSpacing 最小值,修改了下。(会不会是我们的相机其实该值是固定的,根据该值算出的spacing才是有误差的? 如果换了相机是否要改值?)
  50705. //2022-12-21又换回非固定值。因为有的场景如SS-t-t01myDqnfE的两个数据集密集程度差别很大,应该将稀疏点云的大小设置的大些。 但是这样的缺点是两个数据集因相接处有大有小无法融合。
  50706. size = base * 5 * num_; /* * window.devicePixelRatio */
  50707. }
  50708. }
  50709. //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 */)
  50710. if(size){
  50711. if(Potree.settings.sortCloudMat){//被废弃,不给material分组了
  50712. this.size = size;this.material.size = size;
  50713. }else {
  50714. this.material.size = size;
  50715. }
  50716. }
  50717. dontRender || viewer.dispatchEvent('content_changed');
  50718. }
  50719. // 设置点透明度
  50720. changePointOpacity(num, canMoreThanOne ) {
  50721. //num:0-1 navvis用的是亮度
  50722. if (num == void 0) {
  50723. num = this.temp.pointOpacity;
  50724. } else {
  50725. this.temp.pointOpacity = num;
  50726. }
  50727. let dontRender = viewer.dealBeforeRender; //在执行beforeRender时更改的话不要发送content_changed 尤其分屏
  50728. if(Potree.settings.notAdditiveBlending){
  50729. return this.material.opacity = num
  50730. }
  50731. let opacity;
  50732. if (num == 1) {
  50733. opacity = 1;
  50734. } else {
  50735. let str = (Potree.settings.sizeFitToLevel?'sizeFit:':'')+ (canMoreThanOne ? 'canMoreThanOne:':'') +this.temp.pointOpacity+':'+this.maxLevel+':'+this.nodeMaxLevel;
  50736. let value = this.temp.opacity[str]; //储存。防止每次渲染(反复切换density)都要算。
  50737. if(value){
  50738. opacity = value;
  50739. }else {
  50740. if(Potree.settings.sizeFitToLevel){//按照点云质量来调整的版本:
  50741. let base = this.material.spacing / Math.pow(1.7, this.maxLevel); //随着level提高,点云重叠几率增多
  50742. let minBase = this.material.spacing / Math.pow(1.7, this.nodeMaxLevel);
  50743. let ratio = Math.min(1 / base, 1 / minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  50744. opacity = base * ratio * num;
  50745. if(!canMoreThanOne){
  50746. opacity = MathUtils.clamp(opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  50747. }
  50748. }else {
  50749. let base = this.material.spacing / Math.pow(2, this.maxLevel);
  50750. let minBase = this.material.spacing / Math.pow(2, this.nodeMaxLevel);
  50751. //console.log(1 / base, 1 / minBase / 6)
  50752. let ratio = Math.min(1 / base, 1 / minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  50753. opacity = base * ratio * num;
  50754. if(!canMoreThanOne){
  50755. opacity = MathUtils.clamp(opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  50756. }
  50757. }
  50758. this.temp.opacity[str] = opacity;
  50759. }
  50760. //缺点:防止颜色过亮主要是相机离远时,当在漫游点处由于离点云太近,可能会导致高质量点云看起来很暗。
  50761. }
  50762. //console.log('changePointOpacity ' + this.dataset_id + ', num : ' + num + ' , opacity : ' + this.material.opacity) //检查是否做到了低质量时num==opacity,中质量opacity稍小于num,高质量更小
  50763. if(Potree.settings.sortCloudMat){
  50764. this.opacity = opacity; this.material.opacity = opacity;
  50765. }else {
  50766. this.material.opacity = opacity;
  50767. }
  50768. dontRender || viewer.dispatchEvent('content_changed');
  50769. }
  50770. updateBound(){
  50771. var boundingBox_ = this.pcoGeometry.tightBoundingBox.clone().applyMatrix4(this.matrixWorld);//tightBoundingBox是点云原始的bound,但经过(绕z)旋转后bound有所改变,比之前体积更大。
  50772. this.bound = boundingBox_;
  50773. this.bound2 = this.getBoundWithPanos();
  50774. }
  50775. getBoundWithPanos(){//确保panoBound在内的bound
  50776. let bound = this.bound.clone();
  50777. this.panos.forEach(pano=>{
  50778. let panoBound = new Box3;
  50779. panoBound.expandByPoint(pano.position);
  50780. panoBound.expandByVector(new Vector3(1,1,1));//give pano a margin
  50781. bound.union(panoBound);
  50782. });
  50783. return bound
  50784. }
  50785. getPanosBound(){//仅由所有pano构成的bound
  50786. if(this.panos.length > 0){
  50787. let minSize = new Vector3(1,1,1);
  50788. this.panosBound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize);
  50789. }else {
  50790. this.panosBound = null;
  50791. }
  50792. }
  50793. getUnrotBoundPoint(type){//获取没有旋转的tightBounding的水平四个点
  50794. //如果alighment支持任意轴旋转,水平面上看到的可能就是六边形了,失去意义,到时候不能用这个。也可以若只绕z旋转, 使用tightBoundingBox,否则bound
  50795. let bound = this.pcoGeometry.tightBoundingBox;
  50796. if(type == 'all'){
  50797. return [new Vector3(bound.min.x, bound.min.y, bound.min.z),
  50798. new Vector3(bound.max.x, bound.min.y, bound.min.z),
  50799. new Vector3(bound.max.x, bound.max.y,bound.min.z),
  50800. new Vector3(bound.min.x, bound.max.y,bound.min.z),
  50801. new Vector3(bound.min.x, bound.min.y, bound.max.z),
  50802. new Vector3(bound.max.x, bound.min.y, bound.max.z),
  50803. new Vector3(bound.max.x, bound.max.y,bound.max.z),
  50804. new Vector3(bound.min.x, bound.max.y,bound.max.z),
  50805. ].map(e=>e.applyMatrix4(this.matrixWorld))
  50806. }else
  50807. return [new Vector3(bound.min.x, bound.min.y,0),
  50808. new Vector3(bound.max.x, bound.min.y,0),
  50809. new Vector3(bound.max.x, bound.max.y,0),
  50810. new Vector3(bound.min.x, bound.max.y,0),
  50811. ].map(e=>e.applyMatrix4(this.matrixWorld))
  50812. }
  50813. getVolume(){
  50814. /* var points = this.getUnrotBoundPoint() -----在只绕z轴旋转时这么写也行
  50815. var area = Math.abs(math.getArea(points))
  50816. return area * (this.bound.max.z - this.bound.min.z) */
  50817. let bound = this.pcoGeometry.tightBoundingBox.clone();
  50818. let size = bound.getSize(new Vector3);
  50819. return size.x * size.y * size.z
  50820. }
  50821. ifContainsPoint(pos){//pos是否坐落于tightBound内
  50822. /* if(!this.bound || !this.bound.containsPoint(pos))return ---这样写也行
  50823. var points = this.getUnrotBoundPoint()
  50824. return math.isPointInArea(points, null, pos) */
  50825. //要把tightBoundingBox想象成一个volumeBox
  50826. let box = this.pcoGeometry.tightBoundingBox;
  50827. let center = box.getCenter(new Vector3);
  50828. let size = box.getSize(new Vector3);
  50829. let boxMatrix = new Matrix4().setPosition(center.x,center.y,center.z);
  50830. boxMatrix.scale(size);
  50831. boxMatrix.premultiply(this.matrixWorld);
  50832. return Potree.Utils.isIntersectBox(pos, boxMatrix)
  50833. }
  50834. intersectBox(boxWorldMatrix){
  50835. let boxM = boxWorldMatrix.clone().premultiply(this.matrixWorld.clone().invert()); //box乘上点云逆矩阵 (因为点云的忽略掉其matrixWorld, 为了保持相对位置不变,box要左乘matrixWorld的逆)(因第一个参数bound不好变形,第二个参数box可以)
  50836. return Potree.Utils.isIntersectBox(this.pcoGeometry.tightBoundingBox, boxM)
  50837. }
  50838. }
  50839. class ProfileData {
  50840. constructor (profile) {
  50841. this.profile = profile;
  50842. this.segments = [];
  50843. this.boundingBox = new Box3();
  50844. for (let i = 0; i < profile.points.length - 1; i++) {
  50845. let start = profile.points[i];
  50846. let end = profile.points[i + 1];
  50847. let startGround = new Vector3(start.x, start.y, 0);
  50848. let endGround = new Vector3(end.x, end.y, 0);
  50849. let center = new Vector3().addVectors(endGround, startGround).multiplyScalar(0.5);
  50850. let length = startGround.distanceTo(endGround);
  50851. let side = new Vector3().subVectors(endGround, startGround).normalize();
  50852. let up = new Vector3(0, 0, 1);
  50853. let forward = new Vector3().crossVectors(side, up).normalize();
  50854. let N = forward;
  50855. let cutPlane = new Plane().setFromNormalAndCoplanarPoint(N, startGround);
  50856. let halfPlane = new Plane().setFromNormalAndCoplanarPoint(side, center);
  50857. let segment = {
  50858. start: start,
  50859. end: end,
  50860. cutPlane: cutPlane,
  50861. halfPlane: halfPlane,
  50862. length: length,
  50863. points: new Points$1()
  50864. };
  50865. this.segments.push(segment);
  50866. }
  50867. }
  50868. size () {
  50869. let size = 0;
  50870. for (let segment of this.segments) {
  50871. size += segment.points.numPoints;
  50872. }
  50873. return size;
  50874. }
  50875. };
  50876. class ProfileRequest {
  50877. constructor (pointcloud, profile, maxDepth, callback) {
  50878. this.pointcloud = pointcloud;
  50879. this.profile = profile;
  50880. this.maxDepth = maxDepth || Number.MAX_VALUE;
  50881. this.callback = callback;
  50882. this.temporaryResult = new ProfileData(this.profile);
  50883. this.pointsServed = 0;
  50884. this.highestLevelServed = 0;
  50885. this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  50886. this.initialize();
  50887. }
  50888. initialize () {
  50889. this.priorityQueue.push({node: this.pointcloud.pcoGeometry.root, weight: Infinity});
  50890. };
  50891. // traverse the node and add intersecting descendants to queue
  50892. traverse (node) {
  50893. let stack = [];
  50894. for (let i = 0; i < 8; i++) {
  50895. let child = node.children[i];
  50896. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  50897. stack.push(child);
  50898. }
  50899. }
  50900. while (stack.length > 0) {
  50901. let node = stack.pop();
  50902. let weight = node.boundingSphere.radius;
  50903. this.priorityQueue.push({node: node, weight: weight});
  50904. // add children that intersect the cutting plane
  50905. if (node.level < this.maxDepth) {
  50906. for (let i = 0; i < 8; i++) {
  50907. let child = node.children[i];
  50908. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  50909. stack.push(child);
  50910. }
  50911. }
  50912. }
  50913. }
  50914. }
  50915. update(){
  50916. if(!this.updateGeneratorInstance){
  50917. this.updateGeneratorInstance = this.updateGenerator();
  50918. }
  50919. let result = this.updateGeneratorInstance.next();
  50920. if(result.done){
  50921. this.updateGeneratorInstance = null;
  50922. }
  50923. }
  50924. * updateGenerator(){
  50925. // load nodes in queue
  50926. // if hierarchy expands, also load nodes from expanded hierarchy
  50927. // once loaded, add data to this.points and remove node from queue
  50928. // only evaluate 1-50 nodes per frame to maintain responsiveness
  50929. let start = performance.now();
  50930. let maxNodesPerUpdate = 1;
  50931. let intersectedNodes = [];
  50932. for (let i = 0; i < Math.min(maxNodesPerUpdate, this.priorityQueue.size()); i++) {
  50933. let element = this.priorityQueue.pop();
  50934. let node = element.node;
  50935. if(node.level > this.maxDepth){
  50936. continue;
  50937. }
  50938. if (node.loaded) {
  50939. // add points to result
  50940. intersectedNodes.push(node);
  50941. exports.lru.touch(node);
  50942. this.highestLevelServed = Math.max(node.getLevel(), this.highestLevelServed);
  50943. var geom = node.pcoGeometry;
  50944. var hierarchyStepSize = geom ? geom.hierarchyStepSize : 1;
  50945. var doTraverse = node.getLevel() === 0 ||
  50946. (node.level % hierarchyStepSize === 0 && node.hasChildren);
  50947. if (doTraverse) {
  50948. this.traverse(node);
  50949. }
  50950. } else {
  50951. node.load();
  50952. this.priorityQueue.push(element);
  50953. }
  50954. }
  50955. if (intersectedNodes.length > 0) {
  50956. for(let done of this.getPointsInsideProfile(intersectedNodes, this.temporaryResult)){
  50957. if(!done){
  50958. //console.log("updateGenerator yields");
  50959. yield false;
  50960. }
  50961. }
  50962. if (this.temporaryResult.size() > 100) {
  50963. this.pointsServed += this.temporaryResult.size();
  50964. this.callback.onProgress({request: this, points: this.temporaryResult});
  50965. this.temporaryResult = new ProfileData(this.profile);
  50966. }
  50967. }
  50968. if (this.priorityQueue.size() === 0) {
  50969. // we're done! inform callback and remove from pending requests
  50970. if (this.temporaryResult.size() > 0) {
  50971. this.pointsServed += this.temporaryResult.size();
  50972. this.callback.onProgress({request: this, points: this.temporaryResult});
  50973. this.temporaryResult = new ProfileData(this.profile);
  50974. }
  50975. this.callback.onFinish({request: this});
  50976. let index = this.pointcloud.profileRequests.indexOf(this);
  50977. if (index >= 0) {
  50978. this.pointcloud.profileRequests.splice(index, 1);
  50979. }
  50980. }
  50981. yield true;
  50982. };
  50983. * getAccepted(numPoints, node, matrix, segment, segmentDir, points, totalMileage){
  50984. let checkpoint = performance.now();
  50985. let accepted = new Uint32Array(numPoints);
  50986. let mileage = new Float64Array(numPoints);
  50987. let acceptedPositions = new Float32Array(numPoints * 3);
  50988. let numAccepted = 0;
  50989. let pos = new Vector3();
  50990. let svp = new Vector3();
  50991. let view = new Float32Array(node.geometry.attributes.position.array);
  50992. for (let i = 0; i < numPoints; i++) {
  50993. pos.set(
  50994. view[i * 3 + 0],
  50995. view[i * 3 + 1],
  50996. view[i * 3 + 2]);
  50997. pos.applyMatrix4(matrix);
  50998. let distance = Math.abs(segment.cutPlane.distanceToPoint(pos));
  50999. let centerDistance = Math.abs(segment.halfPlane.distanceToPoint(pos));
  51000. if (distance < this.profile.width / 2 && centerDistance < segment.length / 2) {
  51001. svp.subVectors(pos, segment.start);
  51002. let localMileage = segmentDir.dot(svp);
  51003. accepted[numAccepted] = i;
  51004. mileage[numAccepted] = localMileage + totalMileage;
  51005. points.boundingBox.expandByPoint(pos);
  51006. pos.sub(this.pointcloud.position);
  51007. acceptedPositions[3 * numAccepted + 0] = pos.x;
  51008. acceptedPositions[3 * numAccepted + 1] = pos.y;
  51009. acceptedPositions[3 * numAccepted + 2] = pos.z;
  51010. numAccepted++;
  51011. }
  51012. if((i % 1000) === 0){
  51013. let duration = performance.now() - checkpoint;
  51014. if(duration > 4){
  51015. //console.log(`getAccepted yield after ${duration}ms`);
  51016. yield false;
  51017. checkpoint = performance.now();
  51018. }
  51019. }
  51020. }
  51021. accepted = accepted.subarray(0, numAccepted);
  51022. mileage = mileage.subarray(0, numAccepted);
  51023. acceptedPositions = acceptedPositions.subarray(0, numAccepted * 3);
  51024. //let end = performance.now();
  51025. //let duration = end - start;
  51026. //console.log("accepted duration ", duration)
  51027. //console.log(`getAccepted finished`);
  51028. yield [accepted, mileage, acceptedPositions];
  51029. }
  51030. * getPointsInsideProfile(nodes, target){
  51031. let checkpoint = performance.now();
  51032. let totalMileage = 0;
  51033. let pointsProcessed = 0;
  51034. for (let segment of target.segments) {
  51035. for (let node of nodes) {
  51036. let numPoints = node.numPoints;
  51037. let geometry = node.geometry;
  51038. if(!numPoints){
  51039. continue;
  51040. }
  51041. { // skip if current node doesn't intersect current segment
  51042. let bbWorld = node.boundingBox.clone().applyMatrix4(this.pointcloud.matrixWorld);
  51043. let bsWorld = bbWorld.getBoundingSphere(new Sphere());
  51044. let start = new Vector3(segment.start.x, segment.start.y, bsWorld.center.z);
  51045. let end = new Vector3(segment.end.x, segment.end.y, bsWorld.center.z);
  51046. let closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  51047. let distance = closest.distanceTo(bsWorld.center);
  51048. let intersects = (distance < (bsWorld.radius + target.profile.width));
  51049. if(!intersects){
  51050. continue;
  51051. }
  51052. }
  51053. //{// DEBUG
  51054. // console.log(node.name);
  51055. // let boxHelper = new Potree.Box3Helper(node.getBoundingBox());
  51056. // boxHelper.matrixAutoUpdate = false;
  51057. // boxHelper.matrix.copy(viewer.scene.pointclouds[0].matrixWorld);
  51058. // viewer.scene.scene.add(boxHelper);
  51059. //}
  51060. let sv = new Vector3().subVectors(segment.end, segment.start).setZ(0);
  51061. let segmentDir = sv.clone().normalize();
  51062. let points = new Points$1();
  51063. let nodeMatrix = new Matrix4().makeTranslation(...node.boundingBox.min.toArray());
  51064. let matrix = new Matrix4().multiplyMatrices(
  51065. this.pointcloud.matrixWorld, nodeMatrix);
  51066. pointsProcessed = pointsProcessed + numPoints;
  51067. let accepted = null;
  51068. let mileage = null;
  51069. let acceptedPositions = null;
  51070. for(let result of this.getAccepted(numPoints, node, matrix, segment, segmentDir, points,totalMileage)){
  51071. if(!result){
  51072. let duration = performance.now() - checkpoint;
  51073. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  51074. yield false;
  51075. checkpoint = performance.now();
  51076. }else {
  51077. [accepted, mileage, acceptedPositions] = result;
  51078. }
  51079. }
  51080. let duration = performance.now() - checkpoint;
  51081. if(duration > 4){
  51082. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  51083. yield false;
  51084. checkpoint = performance.now();
  51085. }
  51086. points.data.position = acceptedPositions;
  51087. let relevantAttributes = Object.keys(geometry.attributes).filter(a => !["position", "indices"].includes(a));
  51088. for(let attributeName of relevantAttributes){
  51089. let attribute = geometry.attributes[attributeName];
  51090. let numElements = attribute.array.length / numPoints;
  51091. if(numElements !== parseInt(numElements)){
  51092. debugger;
  51093. }
  51094. let Type = attribute.array.constructor;
  51095. let filteredBuffer = new Type(numElements * accepted.length);
  51096. let source = attribute.array;
  51097. let target = filteredBuffer;
  51098. for(let i = 0; i < accepted.length; i++){
  51099. let index = accepted[i];
  51100. let start = index * numElements;
  51101. let end = start + numElements;
  51102. let sub = source.subarray(start, end);
  51103. target.set(sub, i * numElements);
  51104. }
  51105. points.data[attributeName] = filteredBuffer;
  51106. }
  51107. points.data['mileage'] = mileage;
  51108. points.numPoints = accepted.length;
  51109. segment.points.add(points);
  51110. }
  51111. totalMileage += segment.length;
  51112. }
  51113. for (let segment of target.segments) {
  51114. target.boundingBox.union(segment.points.boundingBox);
  51115. }
  51116. //console.log(`getPointsInsideProfile finished`);
  51117. yield true;
  51118. };
  51119. finishLevelThenCancel () {
  51120. if (this.cancelRequested) {
  51121. return;
  51122. }
  51123. this.maxDepth = this.highestLevelServed;
  51124. this.cancelRequested = true;
  51125. //console.log(`maxDepth: ${this.maxDepth}`);
  51126. };
  51127. cancel () {
  51128. this.callback.onCancel();
  51129. this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  51130. let index = this.pointcloud.profileRequests.indexOf(this);
  51131. if (index >= 0) {
  51132. this.pointcloud.profileRequests.splice(index, 1);
  51133. }
  51134. };
  51135. }
  51136. class WorkerPool{
  51137. constructor(){
  51138. this.workers = {};
  51139. }
  51140. getWorker(url){
  51141. if (!this.workers[url]){
  51142. this.workers[url] = [];
  51143. }
  51144. if (this.workers[url].length === 0){
  51145. let worker = new Worker(url);
  51146. this.workers[url].push(worker);
  51147. }
  51148. let worker = this.workers[url].pop();
  51149. return worker;
  51150. }
  51151. returnWorker(url, worker){
  51152. this.workers[url].push(worker);
  51153. }
  51154. };
  51155. function createPointcloudData(pointcloud) {
  51156. let material = pointcloud.material;
  51157. let ranges = [];
  51158. for(let [name, value] of material.ranges){
  51159. ranges.push({
  51160. name: name,
  51161. value: value,
  51162. });
  51163. }
  51164. if(typeof material.elevationRange[0] === "number"){
  51165. ranges.push({
  51166. name: "elevationRange",
  51167. value: material.elevationRange,
  51168. });
  51169. }
  51170. if(typeof material.intensityRange[0] === "number"){
  51171. ranges.push({
  51172. name: "intensityRange",
  51173. value: material.intensityRange,
  51174. });
  51175. }
  51176. let pointSizeTypeName = Object.entries(Potree.PointSizeType).find(e => e[1] === material.pointSizeType)[0];
  51177. let jsonMaterial = {
  51178. activeAttributeName: material.activeAttributeName,
  51179. ranges: ranges,
  51180. size: material.size,
  51181. minSize: material.minSize,
  51182. pointSizeType: pointSizeTypeName,
  51183. matcap: material.matcap,
  51184. };
  51185. const pcdata = {
  51186. name: pointcloud.name,
  51187. url: pointcloud.pcoGeometry.url,
  51188. position: pointcloud.position.toArray(),
  51189. rotation: pointcloud.rotation.toArray(),
  51190. scale: pointcloud.scale.toArray(),
  51191. material: jsonMaterial,
  51192. };
  51193. return pcdata;
  51194. }
  51195. function createProfileData(profile){
  51196. const data = {
  51197. uuid: profile.uuid,
  51198. name: profile.name,
  51199. points: profile.points.map(p => p.toArray()),
  51200. height: profile.height,
  51201. width: profile.width,
  51202. };
  51203. return data;
  51204. }
  51205. function createVolumeData(volume){
  51206. const data = {
  51207. uuid: volume.uuid,
  51208. type: volume.constructor.name,
  51209. name: volume.name,
  51210. position: volume.position.toArray(),
  51211. rotation: volume.rotation.toArray(),
  51212. scale: volume.scale.toArray(),
  51213. visible: volume.visible,
  51214. clip: volume.clip,
  51215. };
  51216. return data;
  51217. }
  51218. function createCameraAnimationData(animation){
  51219. const controlPoints = animation.controlPoints.map( cp => {
  51220. const cpdata = {
  51221. position: cp.position.toArray(),
  51222. target: cp.target.toArray(),
  51223. };
  51224. return cpdata;
  51225. });
  51226. const data = {
  51227. uuid: animation.uuid,
  51228. name: animation.name,
  51229. duration: animation.duration,
  51230. t: animation.t,
  51231. curveType: animation.curveType,
  51232. visible: animation.visible,
  51233. controlPoints: controlPoints,
  51234. };
  51235. return data;
  51236. }
  51237. function createMeasurementData(measurement){
  51238. const data = {
  51239. uuid: measurement.uuid,
  51240. name: measurement.name,
  51241. points: measurement.points.map(p => p.position.toArray()),
  51242. showDistances: measurement.showDistances,
  51243. showCoordinates: measurement.showCoordinates,
  51244. showArea: measurement.showArea,
  51245. closed: measurement.closed,
  51246. showAngles: measurement.showAngles,
  51247. showHeight: measurement.showHeight,
  51248. showCircle: measurement.showCircle,
  51249. showAzimuth: measurement.showAzimuth,
  51250. showEdges: measurement.showEdges,
  51251. color: measurement.color.toArray(),
  51252. };
  51253. return data;
  51254. }
  51255. function createOrientedImagesData(images){
  51256. const data = {
  51257. cameraParamsPath: images.cameraParamsPath,
  51258. imageParamsPath: images.imageParamsPath,
  51259. };
  51260. return data;
  51261. }
  51262. function createGeopackageData(geopackage){
  51263. const data = {
  51264. path: geopackage.path,
  51265. };
  51266. return data;
  51267. }
  51268. function createAnnotationData(annotation){
  51269. const data = {
  51270. uuid: annotation.uuid,
  51271. title: annotation.title.toString(),
  51272. description: annotation.description,
  51273. position: annotation.position.toArray(),
  51274. offset: annotation.offset.toArray(),
  51275. children: [],
  51276. };
  51277. if(annotation.cameraPosition){
  51278. data.cameraPosition = annotation.cameraPosition.toArray();
  51279. }
  51280. if(annotation.cameraTarget){
  51281. data.cameraTarget = annotation.cameraTarget.toArray();
  51282. }
  51283. if(typeof annotation.radius !== "undefined"){
  51284. data.radius = annotation.radius;
  51285. }
  51286. return data;
  51287. }
  51288. function createAnnotationsData(viewer){
  51289. const map = new Map();
  51290. viewer.scene.annotations.traverseDescendants(a => {
  51291. const aData = createAnnotationData(a);
  51292. map.set(a, aData);
  51293. });
  51294. for(const [annotation, data] of map){
  51295. for(const child of annotation.children){
  51296. const childData = map.get(child);
  51297. data.children.push(childData);
  51298. }
  51299. }
  51300. const annotations = viewer.scene.annotations.children.map(a => map.get(a));
  51301. return annotations;
  51302. }
  51303. function createSettingsData(viewer){
  51304. return {
  51305. pointBudget: viewer.getPointBudget(),
  51306. fov: viewer.getFOV(),
  51307. edlEnabled: viewer.getEDLEnabled(),
  51308. edlRadius: viewer.getEDLRadius(),
  51309. edlStrength: viewer.getEDLStrength(),
  51310. background: viewer.getBackground(),
  51311. minNodeSize: viewer.getMinNodeSize(),
  51312. showBoundingBoxes: viewer.getShowBoundingBox(),
  51313. };
  51314. }
  51315. function createSceneContentData(viewer){
  51316. const data = [];
  51317. const potreeObjects = [];
  51318. viewer.scene.scene.traverse(node => {
  51319. if(node.potree){
  51320. potreeObjects.push(node);
  51321. }
  51322. });
  51323. for(const object of potreeObjects){
  51324. if(object.potree.file){
  51325. const saveObject = {
  51326. file: object.potree.file,
  51327. };
  51328. data.push(saveObject);
  51329. }
  51330. }
  51331. return data;
  51332. }
  51333. function createViewData(viewer){
  51334. const view = viewer.scene.view;
  51335. const data = {
  51336. position: view.position.toArray(),
  51337. target: view.getPivot().toArray(),
  51338. };
  51339. return data;
  51340. }
  51341. function createClassificationData(viewer){
  51342. const classifications = viewer.classifications;
  51343. const data = classifications;
  51344. return data;
  51345. }
  51346. function saveProject(viewer) {
  51347. const scene = viewer.scene;
  51348. const data = {
  51349. type: "Potree",
  51350. version: 1.7,
  51351. settings: createSettingsData(viewer),
  51352. view: createViewData(viewer),
  51353. classification: createClassificationData(viewer),
  51354. pointclouds: scene.pointclouds.map(createPointcloudData),
  51355. measurements: scene.measurements.map(createMeasurementData),
  51356. volumes: scene.volumes.map(createVolumeData),
  51357. cameraAnimations: scene.cameraAnimations.map(createCameraAnimationData),
  51358. profiles: scene.profiles.map(createProfileData),
  51359. annotations: createAnnotationsData(viewer),
  51360. orientedImages: scene.orientedImages.map(createOrientedImagesData),
  51361. geopackages: scene.geopackages.map(createGeopackageData),
  51362. // objects: createSceneContentData(viewer),
  51363. };
  51364. return data;
  51365. }
  51366. class ControlPoint{
  51367. constructor(){
  51368. this.position = new Vector3(0, 0, 0);
  51369. this.target = new Vector3(0, 0, 0);
  51370. this.positionHandle = null;
  51371. this.targetHandle = null;
  51372. }
  51373. };
  51374. class CameraAnimation extends EventDispatcher$1{
  51375. constructor(viewer){
  51376. super();
  51377. this.viewer = viewer;
  51378. this.selectedElement = null;
  51379. this.controlPoints = [];
  51380. this.uuid = MathUtils.generateUUID();
  51381. this.node = new Object3D();
  51382. this.node.name = "camera animation";
  51383. this.viewer.scene.scene.add(this.node);
  51384. this.frustum = this.createFrustum();
  51385. this.node.add(this.frustum);
  51386. this.name = "Camera Animation";
  51387. this.duration = 5;
  51388. this.t = 0;
  51389. // "centripetal", "chordal", "catmullrom"
  51390. this.curveType = "centripetal";
  51391. this.visible = true;
  51392. this.createUpdateHook();
  51393. this.createPath();
  51394. }
  51395. static defaultFromView(viewer){
  51396. const animation = new CameraAnimation(viewer);
  51397. const camera = viewer.scene.getActiveCamera();
  51398. const target = viewer.scene.view.getPivot();
  51399. const cpCenter = new Vector3(
  51400. 0.3 * camera.position.x + 0.7 * target.x,
  51401. 0.3 * camera.position.y + 0.7 * target.y,
  51402. 0.3 * camera.position.z + 0.7 * target.z,
  51403. );
  51404. const targetCenter = new Vector3(
  51405. 0.05 * camera.position.x + 0.95 * target.x,
  51406. 0.05 * camera.position.y + 0.95 * target.y,
  51407. 0.05 * camera.position.z + 0.95 * target.z,
  51408. );
  51409. const r = camera.position.distanceTo(target) * 0.3;
  51410. //const dir = target.clone().sub(camera.position).normalize();
  51411. const angle = Utils.computeAzimuth(camera.position, target);
  51412. const n = 5;
  51413. for(let i = 0; i < n; i++){
  51414. let u = 1.5 * Math.PI * (i / n) + angle;
  51415. const dx = r * Math.cos(u);
  51416. const dy = r * Math.sin(u);
  51417. const cpPos = [
  51418. cpCenter.x + dx,
  51419. cpCenter.y + dy,
  51420. cpCenter.z,
  51421. ];
  51422. const targetPos = [
  51423. targetCenter.x + dx * 0.1,
  51424. targetCenter.y + dy * 0.1,
  51425. targetCenter.z,
  51426. ];
  51427. const cp = animation.createControlPoint();
  51428. cp.position.set(...cpPos);
  51429. cp.target.set(...targetPos);
  51430. }
  51431. return animation;
  51432. }
  51433. createUpdateHook(){
  51434. const viewer = this.viewer;
  51435. viewer.addEventListener("update", () => {
  51436. const camera = viewer.scene.getActiveCamera();
  51437. const {width, height} = viewer.renderer.getSize(new Vector2());
  51438. this.node.visible = this.visible;
  51439. for(const cp of this.controlPoints){
  51440. { // position
  51441. const projected = cp.position.clone().project(camera);
  51442. const visible = this.visible && (projected.z < 1 && projected.z > -1);
  51443. if(visible){
  51444. const x = width * (projected.x * 0.5 + 0.5);
  51445. const y = height - height * (projected.y * 0.5 + 0.5);
  51446. cp.positionHandle.svg.style.left = x - cp.positionHandle.svg.clientWidth / 2;
  51447. cp.positionHandle.svg.style.top = y - cp.positionHandle.svg.clientHeight / 2;
  51448. cp.positionHandle.svg.style.display = "";
  51449. }else {
  51450. cp.positionHandle.svg.style.display = "none";
  51451. }
  51452. }
  51453. { // target
  51454. const projected = cp.target.clone().project(camera);
  51455. const visible = this.visible && (projected.z < 1 && projected.z > -1);
  51456. if(visible){
  51457. const x = width * (projected.x * 0.5 + 0.5);
  51458. const y = height - height * (projected.y * 0.5 + 0.5);
  51459. cp.targetHandle.svg.style.left = x - cp.targetHandle.svg.clientWidth / 2;
  51460. cp.targetHandle.svg.style.top = y - cp.targetHandle.svg.clientHeight / 2;
  51461. cp.targetHandle.svg.style.display = "";
  51462. }else {
  51463. cp.targetHandle.svg.style.display = "none";
  51464. }
  51465. }
  51466. }
  51467. this.line.material.resolution.set(width, height);
  51468. this.updatePath();
  51469. { // frustum
  51470. const frame = this.at(this.t);
  51471. const frustum = this.frustum;
  51472. frustum.position.copy(frame.position);
  51473. frustum.lookAt(...frame.target.toArray());
  51474. frustum.scale.set(20, 20, 20);
  51475. frustum.material.resolution.set(width, height);
  51476. }
  51477. });
  51478. }
  51479. createControlPoint(index){
  51480. if(index === undefined){
  51481. index = this.controlPoints.length;
  51482. }
  51483. const cp = new ControlPoint();
  51484. if(this.controlPoints.length >= 2 && index === 0){
  51485. const cp1 = this.controlPoints[0];
  51486. const cp2 = this.controlPoints[1];
  51487. const dir = cp1.position.clone().sub(cp2.position).multiplyScalar(0.5);
  51488. cp.position.copy(cp1.position).add(dir);
  51489. const tDir = cp1.target.clone().sub(cp2.target).multiplyScalar(0.5);
  51490. cp.target.copy(cp1.target).add(tDir);
  51491. }else if(this.controlPoints.length >= 2 && index === this.controlPoints.length){
  51492. const cp1 = this.controlPoints[this.controlPoints.length - 2];
  51493. const cp2 = this.controlPoints[this.controlPoints.length - 1];
  51494. const dir = cp2.position.clone().sub(cp1.position).multiplyScalar(0.5);
  51495. cp.position.copy(cp1.position).add(dir);
  51496. const tDir = cp2.target.clone().sub(cp1.target).multiplyScalar(0.5);
  51497. cp.target.copy(cp2.target).add(tDir);
  51498. }else if(this.controlPoints.length >= 2){
  51499. const cp1 = this.controlPoints[index - 1];
  51500. const cp2 = this.controlPoints[index];
  51501. cp.position.copy(cp1.position.clone().add(cp2.position).multiplyScalar(0.5));
  51502. cp.target.copy(cp1.target.clone().add(cp2.target).multiplyScalar(0.5));
  51503. }
  51504. // cp.position.copy(viewer.scene.view.position);
  51505. // cp.target.copy(viewer.scene.view.getPivot());
  51506. cp.positionHandle = this.createHandle(cp.position);
  51507. cp.targetHandle = this.createHandle(cp.target);
  51508. this.controlPoints.splice(index, 0, cp);
  51509. this.dispatchEvent({
  51510. type: "controlpoint_added",
  51511. controlpoint: cp,
  51512. });
  51513. return cp;
  51514. }
  51515. removeControlPoint(cp){
  51516. this.controlPoints = this.controlPoints.filter(_cp => _cp !== cp);
  51517. this.dispatchEvent({
  51518. type: "controlpoint_removed",
  51519. controlpoint: cp,
  51520. });
  51521. cp.positionHandle.svg.remove();
  51522. cp.targetHandle.svg.remove();
  51523. // TODO destroy cp
  51524. }
  51525. createPath(){
  51526. { // position
  51527. const geometry = new LineGeometry();
  51528. let material = new LineMaterial({
  51529. color: 0x00ff00,
  51530. dashSize: 5,
  51531. gapSize: 2,
  51532. linewidth: 2,
  51533. resolution: new Vector2(1000, 1000),
  51534. });
  51535. const line = new Line2(geometry, material);
  51536. this.line = line;
  51537. this.node.add(line);
  51538. }
  51539. { // target
  51540. const geometry = new LineGeometry();
  51541. let material = new LineMaterial({
  51542. color: 0x0000ff,
  51543. dashSize: 5,
  51544. gapSize: 2,
  51545. linewidth: 2,
  51546. resolution: new Vector2(1000, 1000),
  51547. });
  51548. const line = new Line2(geometry, material);
  51549. this.targetLine = line;
  51550. this.node.add(line);
  51551. }
  51552. }
  51553. createFrustum(){
  51554. const f = 0.3;
  51555. const positions = [
  51556. 0, 0, 0,
  51557. -f, -f, +1,
  51558. 0, 0, 0,
  51559. f, -f, +1,
  51560. 0, 0, 0,
  51561. f, f, +1,
  51562. 0, 0, 0,
  51563. -f, f, +1,
  51564. -f, -f, +1,
  51565. f, -f, +1,
  51566. f, -f, +1,
  51567. f, f, +1,
  51568. f, f, +1,
  51569. -f, f, +1,
  51570. -f, f, +1,
  51571. -f, -f, +1,
  51572. ];
  51573. const geometry = new LineGeometry();
  51574. geometry.setPositions(positions);
  51575. geometry.verticesNeedUpdate = true;
  51576. geometry.computeBoundingSphere();
  51577. let material = new LineMaterial({
  51578. color: 0xff0000,
  51579. linewidth: 2,
  51580. resolution: new Vector2(1000, 1000),
  51581. });
  51582. const line = new Line2(geometry, material);
  51583. line.computeLineDistances();
  51584. return line;
  51585. }
  51586. updatePath(){
  51587. { // positions
  51588. const positions = this.controlPoints.map(cp => cp.position);
  51589. const first = positions[0];
  51590. const curve = new CatmullRomCurve3(positions);
  51591. curve.curveType = this.curveType;
  51592. const n = 100;
  51593. const curvePositions = [];
  51594. for(let k = 0; k <= n; k++){
  51595. const t = k / n;
  51596. const position = curve.getPoint(t).sub(first);
  51597. curvePositions.push(position.x, position.y, position.z);
  51598. }
  51599. this.line.geometry.setPositions(curvePositions);
  51600. this.line.geometry.verticesNeedUpdate = true;
  51601. this.line.geometry.computeBoundingSphere();
  51602. this.line.position.copy(first);
  51603. this.line.computeLineDistances();
  51604. this.cameraCurve = curve;
  51605. }
  51606. { // targets
  51607. const positions = this.controlPoints.map(cp => cp.target);
  51608. const first = positions[0];
  51609. const curve = new CatmullRomCurve3(positions);
  51610. curve.curveType = this.curveType;
  51611. const n = 100;
  51612. const curvePositions = [];
  51613. for(let k = 0; k <= n; k++){
  51614. const t = k / n;
  51615. const position = curve.getPoint(t).sub(first);
  51616. curvePositions.push(position.x, position.y, position.z);
  51617. }
  51618. this.targetLine.geometry.setPositions(curvePositions);
  51619. this.targetLine.geometry.verticesNeedUpdate = true;
  51620. this.targetLine.geometry.computeBoundingSphere();
  51621. this.targetLine.position.copy(first);
  51622. this.targetLine.computeLineDistances();
  51623. this.targetCurve = curve;
  51624. }
  51625. }
  51626. at(t){
  51627. if(t > 1){
  51628. t = 1;
  51629. }else if(t < 0){
  51630. t = 0;
  51631. }
  51632. const camPos = this.cameraCurve.getPointAt(t);
  51633. const target = this.targetCurve.getPointAt(t);
  51634. const frame = {
  51635. position: camPos,
  51636. target: target,
  51637. };
  51638. return frame;
  51639. }
  51640. set(t){
  51641. this.t = t;
  51642. }
  51643. createHandle(vector){
  51644. const svgns = "http://www.w3.org/2000/svg";
  51645. const svg = document.createElementNS(svgns, "svg");
  51646. svg.setAttribute("width", "2em");
  51647. svg.setAttribute("height", "2em");
  51648. svg.setAttribute("position", "absolute");
  51649. svg.style.left = "50px";
  51650. svg.style.top = "50px";
  51651. svg.style.position = "absolute";
  51652. svg.style.zIndex = "10000";
  51653. const circle = document.createElementNS(svgns, 'circle');
  51654. circle.setAttributeNS(null, 'cx', "1em");
  51655. circle.setAttributeNS(null, 'cy', "1em");
  51656. circle.setAttributeNS(null, 'r', "0.5em");
  51657. circle.setAttributeNS(null, 'style', 'fill: red; stroke: black; stroke-width: 0.2em;' );
  51658. svg.appendChild(circle);
  51659. const element = this.viewer.renderer.domElement.parentElement;
  51660. element.appendChild(svg);
  51661. const startDrag = (evt) => {
  51662. this.selectedElement = svg;
  51663. document.addEventListener("mousemove", drag);
  51664. };
  51665. const endDrag = (evt) => {
  51666. this.selectedElement = null;
  51667. document.removeEventListener("mousemove", drag);
  51668. };
  51669. const drag = (evt) => {
  51670. if (this.selectedElement) {
  51671. evt.preventDefault();
  51672. const rect = viewer.renderer.domElement.getBoundingClientRect();
  51673. const x = evt.clientX - rect.x;
  51674. const y = evt.clientY - rect.y;
  51675. const {width, height} = this.viewer.renderer.getSize(new Vector2());
  51676. const camera = this.viewer.scene.getActiveCamera();
  51677. //const cp = this.controlPoints.find(cp => cp.handle.svg === svg);
  51678. const projected = vector.clone().project(camera);
  51679. projected.x = ((x / width) - 0.5) / 0.5;
  51680. projected.y = (-(y - height) / height - 0.5) / 0.5;
  51681. const unprojected = projected.clone().unproject(camera);
  51682. vector.set(unprojected.x, unprojected.y, unprojected.z);
  51683. }
  51684. };
  51685. svg.addEventListener('mousedown', startDrag);
  51686. svg.addEventListener('mouseup', endDrag);
  51687. const handle = {
  51688. svg: svg,
  51689. };
  51690. return handle;
  51691. }
  51692. setVisible(visible){
  51693. this.node.visible = visible;
  51694. const display = visible ? "" : "none";
  51695. for(const cp of this.controlPoints){
  51696. cp.positionHandle.svg.style.display = display;
  51697. cp.targetHandle.svg.style.display = display;
  51698. }
  51699. this.visible = visible;
  51700. }
  51701. setDuration(duration){
  51702. this.duration = duration;
  51703. }
  51704. getDuration(duration){
  51705. return this.duration;
  51706. }
  51707. play(){
  51708. const tStart = performance.now();
  51709. const duration = this.duration;
  51710. const originalyVisible = this.visible;
  51711. this.setVisible(false);
  51712. const onUpdate = (delta) => {
  51713. let tNow = performance.now();
  51714. let elapsed = (tNow - tStart) / 1000;
  51715. let t = elapsed / duration;
  51716. this.set(t);
  51717. const frame = this.at(t);
  51718. viewer.scene.view.position.copy(frame.position);
  51719. viewer.scene.view.lookAt(frame.target);
  51720. if(t > 1){
  51721. this.setVisible(originalyVisible);
  51722. this.viewer.removeEventListener("update", onUpdate);
  51723. }
  51724. };
  51725. this.viewer.addEventListener("update", onUpdate);
  51726. }
  51727. }
  51728. function loadPointCloud(viewer, data){
  51729. let loadMaterial = (target) => {
  51730. if(data.material){
  51731. if(data.material.activeAttributeName != null){
  51732. target.activeAttributeName = data.material.activeAttributeName;
  51733. }
  51734. if(data.material.ranges != null){
  51735. for(let range of data.material.ranges){
  51736. if(range.name === "elevationRange"){
  51737. target.elevationRange = range.value;
  51738. }else if(range.name === "intensityRange"){
  51739. target.intensityRange = range.value;
  51740. }else {
  51741. target.setRange(range.name, range.value);
  51742. }
  51743. }
  51744. }
  51745. if(data.material.size != null){
  51746. target.size = data.material.size;
  51747. }
  51748. if(data.material.minSize != null){
  51749. target.minSize = data.material.minSize;
  51750. }
  51751. if(data.material.pointSizeType != null){
  51752. target.pointSizeType = PointSizeType[data.material.pointSizeType];
  51753. }
  51754. if(data.material.matcap != null){
  51755. target.matcap = data.material.matcap;
  51756. }
  51757. }else if(data.activeAttributeName != null){
  51758. target.activeAttributeName = data.activeAttributeName;
  51759. }else {
  51760. // no material data
  51761. }
  51762. };
  51763. const promise = new Promise((resolve) => {
  51764. const names = viewer.scene.pointclouds.map(p => p.name);
  51765. const alreadyExists = names.includes(data.name);
  51766. if(alreadyExists){
  51767. resolve();
  51768. return;
  51769. }
  51770. Potree.loadPointCloud(data.url, data.name, (e) => {
  51771. const {pointcloud} = e;
  51772. pointcloud.position.set(...data.position);
  51773. pointcloud.rotation.set(...data.rotation);
  51774. pointcloud.scale.set(...data.scale);
  51775. loadMaterial(pointcloud.material);
  51776. viewer.scene.addPointCloud(pointcloud);
  51777. resolve(pointcloud);
  51778. });
  51779. });
  51780. return promise;
  51781. }
  51782. function loadMeasurement(viewer, data){
  51783. const duplicate = viewer.scene.measurements.find(measure => measure.uuid === data.uuid);
  51784. if(duplicate){
  51785. return;
  51786. }
  51787. const measure = new Measure();
  51788. measure.uuid = data.uuid;
  51789. measure.name = data.name;
  51790. measure.showDistances = data.showDistances;
  51791. measure.showCoordinates = data.showCoordinates;
  51792. measure.showArea = data.showArea;
  51793. measure.closed = data.closed;
  51794. measure.showAngles = data.showAngles;
  51795. measure.showHeight = data.showHeight;
  51796. measure.showCircle = data.showCircle;
  51797. measure.showAzimuth = data.showAzimuth;
  51798. measure.showEdges = data.showEdges;
  51799. // color
  51800. for(const point of data.points){
  51801. const pos = new Vector3(...point);
  51802. measure.addMarker(pos);
  51803. }
  51804. viewer.scene.addMeasurement(measure);
  51805. }
  51806. function loadVolume(viewer, data){
  51807. const duplicate = viewer.scene.volumes.find(volume => volume.uuid === data.uuid);
  51808. if(duplicate){
  51809. return;
  51810. }
  51811. let volume = new Potree[data.type];
  51812. volume.uuid = data.uuid;
  51813. volume.name = data.name;
  51814. volume.position.set(...data.position);
  51815. volume.rotation.set(...data.rotation);
  51816. volume.scale.set(...data.scale);
  51817. volume.visible = data.visible;
  51818. volume.clip = data.clip;
  51819. viewer.scene.addVolume(volume);
  51820. }
  51821. function loadCameraAnimation(viewer, data){
  51822. const duplicate = viewer.scene.cameraAnimations.find(a => a.uuid === data.uuid);
  51823. if(duplicate){
  51824. return;
  51825. }
  51826. const animation = new CameraAnimation(viewer);
  51827. animation.uuid = data.uuid;
  51828. animation.name = data.name;
  51829. animation.duration = data.duration;
  51830. animation.t = data.t;
  51831. animation.curveType = data.curveType;
  51832. animation.visible = data.visible;
  51833. animation.controlPoints = [];
  51834. for(const cpdata of data.controlPoints){
  51835. const cp = animation.createControlPoint();
  51836. cp.position.set(...cpdata.position);
  51837. cp.target.set(...cpdata.target);
  51838. }
  51839. viewer.scene.addCameraAnimation(animation);
  51840. }
  51841. function loadOrientedImages(viewer, images){
  51842. const {cameraParamsPath, imageParamsPath} = images;
  51843. const duplicate = viewer.scene.orientedImages.find(i => i.imageParamsPath === imageParamsPath);
  51844. if(duplicate){
  51845. return;
  51846. }
  51847. Potree.OrientedImageLoader.load(cameraParamsPath, imageParamsPath, viewer).then( images => {
  51848. viewer.scene.addOrientedImages(images);
  51849. });
  51850. }
  51851. function loadGeopackage(viewer, geopackage){
  51852. const path = geopackage.path;
  51853. const duplicate = viewer.scene.geopackages.find(i => i.path === path);
  51854. if(duplicate){
  51855. return;
  51856. }
  51857. const projection = viewer.getProjection();
  51858. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  51859. proj4.defs("pointcloud", projection);
  51860. const transform = proj4("WGS84", "pointcloud");
  51861. const params = {
  51862. transform: transform,
  51863. };
  51864. Potree.GeoPackageLoader.loadUrl(path, params).then(data => {
  51865. viewer.scene.addGeopackage(data);
  51866. });
  51867. }
  51868. function loadSettings(viewer, data){
  51869. if(!data){
  51870. return;
  51871. }
  51872. viewer.setPointBudget(data.pointBudget);
  51873. viewer.setFOV(data.fov);
  51874. viewer.setEDLEnabled(data.edlEnabled);
  51875. viewer.setEDLRadius(data.edlRadius);
  51876. viewer.setEDLStrength(data.edlStrength);
  51877. viewer.setBackground(data.background);
  51878. viewer.setMinNodeSize(data.minNodeSize);
  51879. viewer.setShowBoundingBox(data.showBoundingBoxes);
  51880. }
  51881. function loadView(viewer, view){
  51882. viewer.scene.view.position.set(...view.position);
  51883. viewer.scene.view.lookAt(...view.target);
  51884. }
  51885. function loadAnnotationItem(item){
  51886. const annotation = new Annotation({
  51887. position: item.position,
  51888. title: item.title,
  51889. cameraPosition: item.cameraPosition,
  51890. cameraTarget: item.cameraTarget,
  51891. });
  51892. annotation.description = item.description;
  51893. annotation.uuid = item.uuid;
  51894. if(item.offset){
  51895. annotation.offset.set(...item.offset);
  51896. }
  51897. return annotation;
  51898. }
  51899. function loadAnnotations(viewer, data){
  51900. if(!data){
  51901. return;
  51902. }
  51903. const findDuplicate = (item) => {
  51904. let duplicate = null;
  51905. viewer.scene.annotations.traverse( a => {
  51906. if(a.uuid === item.uuid){
  51907. duplicate = a;
  51908. }
  51909. });
  51910. return duplicate;
  51911. };
  51912. const traverse = (item, parent) => {
  51913. const duplicate = findDuplicate(item);
  51914. if(duplicate){
  51915. return;
  51916. }
  51917. const annotation = loadAnnotationItem(item);
  51918. for(const childItem of item.children){
  51919. traverse(childItem, annotation);
  51920. }
  51921. parent.add(annotation);
  51922. };
  51923. for(const item of data){
  51924. traverse(item, viewer.scene.annotations);
  51925. }
  51926. }
  51927. function loadProfile(viewer, data){
  51928. const {name, points} = data;
  51929. const duplicate = viewer.scene.profiles.find(profile => profile.uuid === data.uuid);
  51930. if(duplicate){
  51931. return;
  51932. }
  51933. let profile = new Potree.Profile();
  51934. profile.name = name;
  51935. profile.uuid = data.uuid;
  51936. profile.setWidth(data.width);
  51937. for(const point of points){
  51938. profile.addMarker(new Vector3(...point));
  51939. }
  51940. viewer.scene.addProfile(profile);
  51941. }
  51942. function loadClassification(viewer, data){
  51943. if(!data){
  51944. return;
  51945. }
  51946. const classifications = data;
  51947. viewer.setClassifications(classifications);
  51948. }
  51949. async function loadProject(viewer, data){
  51950. if(data.type !== "Potree"){
  51951. console.error("not a valid Potree project");
  51952. return;
  51953. }
  51954. loadSettings(viewer, data.settings);
  51955. loadView(viewer, data.view);
  51956. const pointcloudPromises = [];
  51957. for(const pointcloud of data.pointclouds){
  51958. const promise = loadPointCloud(viewer, pointcloud);
  51959. pointcloudPromises.push(promise);
  51960. }
  51961. for(const measure of data.measurements){
  51962. loadMeasurement(viewer, measure);
  51963. }
  51964. for(const volume of data.volumes){
  51965. loadVolume(viewer, volume);
  51966. }
  51967. for(const animation of data.cameraAnimations){
  51968. loadCameraAnimation(viewer, animation);
  51969. }
  51970. for(const profile of data.profiles){
  51971. loadProfile(viewer, profile);
  51972. }
  51973. if(data.orientedImages){
  51974. for(const images of data.orientedImages){
  51975. loadOrientedImages(viewer, images);
  51976. }
  51977. }
  51978. loadAnnotations(viewer, data.annotations);
  51979. loadClassification(viewer, data.classification);
  51980. // need to load at least one point cloud that defines the scene projection,
  51981. // before we can load stuff in other projections such as geopackages
  51982. //await Promise.any(pointcloudPromises); // (not yet supported)
  51983. Utils.waitAny(pointcloudPromises).then( () => {
  51984. if(data.geopackages){
  51985. for(const geopackage of data.geopackages){
  51986. loadGeopackage(viewer, geopackage);
  51987. }
  51988. }
  51989. });
  51990. await Promise.all(pointcloudPromises);
  51991. }
  51992. //
  51993. // Algorithm by Christian Boucheny
  51994. // shader code taken and adapted from CloudCompare
  51995. //
  51996. // see
  51997. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  51998. // http://www.kitware.com/source/home/post/9
  51999. // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french)
  52000. class EyeDomeLightingMaterial extends RawShaderMaterial{//base
  52001. constructor(parameters = {}){
  52002. super();
  52003. let uniforms = {
  52004. screenWidth: { type: 'f', value: 0 },
  52005. screenHeight: { type: 'f', value: 0 },
  52006. edlStrength: { type: 'f', value: 1.0 },
  52007. uNear: { type: 'f', value: 1.0 },
  52008. uFar: { type: 'f', value: 1.0 },
  52009. radius: { type: 'f', value: 1.0 },
  52010. neighbours: { type: '2fv', value: [] },
  52011. depthMap: { type: 't', value: null },
  52012. uEDLColor: { type: 't', value: null },
  52013. uEDLDepth: { type: 't', value: null },
  52014. opacity: { type: 'f', value: 1.0 },
  52015. uProj: { type: "Matrix4fv", value: [] },
  52016. };
  52017. this.setValues({
  52018. uniforms: uniforms,
  52019. vertexShader: this.getDefines() + Shaders['edl.vs'],
  52020. fragmentShader: this.getDefines() + Shaders['edl.fs'],
  52021. lights: false
  52022. });
  52023. this.neighbourCount = 8;
  52024. }
  52025. getDefines() {
  52026. let defines = '';
  52027. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  52028. return defines;
  52029. }
  52030. updateShaderSource() {
  52031. let vs = this.getDefines() + Shaders['edl.vs'];
  52032. let fs = this.getDefines() + Shaders['edl.fs'];
  52033. this.setValues({
  52034. vertexShader: vs,
  52035. fragmentShader: fs
  52036. });
  52037. this.uniforms.neighbours.value = this.neighbours;
  52038. this.needsUpdate = true;
  52039. }
  52040. get neighbourCount(){
  52041. return this._neighbourCount;
  52042. }
  52043. set neighbourCount(value){
  52044. if (this._neighbourCount !== value) {//周围八个格子
  52045. this._neighbourCount = value;
  52046. this.neighbours = new Float32Array(this._neighbourCount * 2);
  52047. for (let c = 0; c < this._neighbourCount; c++) {
  52048. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  52049. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  52050. }
  52051. this.updateShaderSource();
  52052. }
  52053. }
  52054. }
  52055. /**
  52056. * laslaz code taken and adapted from plas.io js-laslaz
  52057. * http://plas.io/
  52058. * https://github.com/verma/plasio
  52059. *
  52060. * Thanks to Uday Verma and Howard Butler
  52061. *
  52062. */
  52063. class LasLazLoader {
  52064. constructor (version, extension) {
  52065. if (typeof (version) === 'string') {
  52066. this.version = new Version(version);
  52067. } else {
  52068. this.version = version;
  52069. }
  52070. this.extension = extension;
  52071. }
  52072. static progressCB () {
  52073. }
  52074. load (node) {
  52075. if (node.loaded) {
  52076. return;
  52077. }
  52078. let url = node.getURL();
  52079. if (this.version.equalOrHigher('1.4')) {
  52080. url += `.${this.extension}`;
  52081. }
  52082. let xhr = XHRFactory.createXMLHttpRequest();
  52083. xhr.open('GET', url, true);
  52084. xhr.responseType = 'arraybuffer';
  52085. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  52086. xhr.onreadystatechange = () => {
  52087. if (xhr.readyState === 4) {
  52088. if (xhr.status === 200 || xhr.status === 0) {
  52089. let buffer = xhr.response;
  52090. this.parse(node, buffer);
  52091. } else {
  52092. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + url);
  52093. }
  52094. }
  52095. };
  52096. xhr.send(null);
  52097. }
  52098. async parse(node, buffer){
  52099. let lf = new LASFile(buffer);
  52100. let handler = new LasLazBatcher(node);
  52101. try{
  52102. await lf.open();
  52103. lf.isOpen = true;
  52104. }catch(e){
  52105. console.log("failed to open file. :(");
  52106. return;
  52107. }
  52108. let header = await lf.getHeader();
  52109. let skip = 1;
  52110. let totalRead = 0;
  52111. let totalToRead = (skip <= 1 ? header.pointsCount : header.pointsCount / skip);
  52112. let hasMoreData = true;
  52113. while(hasMoreData){
  52114. let data = await lf.readData(1000 * 1000, 0, skip);
  52115. handler.push(new LASDecoder(data.buffer,
  52116. header.pointsFormatId,
  52117. header.pointsStructSize,
  52118. data.count,
  52119. header.scale,
  52120. header.offset,
  52121. header.mins, header.maxs));
  52122. totalRead += data.count;
  52123. LasLazLoader.progressCB(totalRead / totalToRead);
  52124. hasMoreData = data.hasMoreData;
  52125. }
  52126. header.totalRead = totalRead;
  52127. header.versionAsString = lf.versionAsString;
  52128. header.isCompressed = lf.isCompressed;
  52129. LasLazLoader.progressCB(1);
  52130. try{
  52131. await lf.close();
  52132. lf.isOpen = false;
  52133. }catch(e){
  52134. console.error("failed to close las/laz file!!!");
  52135. throw e;
  52136. }
  52137. }
  52138. handle (node, url) {
  52139. }
  52140. };
  52141. class LasLazBatcher{
  52142. constructor (node) {
  52143. this.node = node;
  52144. }
  52145. push (lasBuffer) {
  52146. const workerPath = Potree.scriptPath + '/workers/LASDecoderWorker.js';
  52147. const worker = Potree.workerPool.getWorker(workerPath);
  52148. const node = this.node;
  52149. const pointAttributes = node.pcoGeometry.pointAttributes;
  52150. worker.onmessage = (e) => {
  52151. let geometry = new BufferGeometry();
  52152. let numPoints = lasBuffer.pointsCount;
  52153. let positions = new Float32Array(e.data.position);
  52154. let colors = new Uint8Array(e.data.color);
  52155. let intensities = new Float32Array(e.data.intensity);
  52156. let classifications = new Uint8Array(e.data.classification);
  52157. let returnNumbers = new Uint8Array(e.data.returnNumber);
  52158. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  52159. let pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  52160. let indices = new Uint8Array(e.data.indices);
  52161. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  52162. geometry.setAttribute('color', new BufferAttribute(colors, 4, true));
  52163. geometry.setAttribute('intensity', new BufferAttribute(intensities, 1));
  52164. geometry.setAttribute('classification', new BufferAttribute(classifications, 1));
  52165. geometry.setAttribute('return number', new BufferAttribute(returnNumbers, 1));
  52166. geometry.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1));
  52167. geometry.setAttribute('source id', new BufferAttribute(pointSourceIDs, 1));
  52168. geometry.setAttribute('indices', new BufferAttribute(indices, 4));
  52169. geometry.attributes.indices.normalized = true;
  52170. for(const key in e.data.ranges){
  52171. const range = e.data.ranges[key];
  52172. const attribute = pointAttributes.attributes.find(a => a.name === key);
  52173. attribute.range[0] = Math.min(attribute.range[0], range[0]);
  52174. attribute.range[1] = Math.max(attribute.range[1], range[1]);
  52175. }
  52176. let tightBoundingBox = new Box3(
  52177. new Vector3().fromArray(e.data.tightBoundingBox.min),
  52178. new Vector3().fromArray(e.data.tightBoundingBox.max)
  52179. );
  52180. geometry.boundingBox = this.node.boundingBox;
  52181. this.node.tightBoundingBox = tightBoundingBox;
  52182. this.node.geometry = geometry;
  52183. this.node.numPoints = numPoints;
  52184. this.node.loaded = true;
  52185. this.node.loading = false;
  52186. Potree.numNodesLoading--;
  52187. this.node.mean = new Vector3(...e.data.mean);
  52188. Potree.workerPool.returnWorker(workerPath, worker);
  52189. };
  52190. let message = {
  52191. buffer: lasBuffer.arrayb,
  52192. numPoints: lasBuffer.pointsCount,
  52193. pointSize: lasBuffer.pointSize,
  52194. pointFormatID: 2,
  52195. scale: lasBuffer.scale,
  52196. offset: lasBuffer.offset,
  52197. mins: lasBuffer.mins,
  52198. maxs: lasBuffer.maxs
  52199. };
  52200. worker.postMessage(message, [message.buffer]);
  52201. };
  52202. }
  52203. function parseAttributes(cloudjs){
  52204. let version = new Version(cloudjs.version);
  52205. const replacements = {
  52206. "COLOR_PACKED": "rgba",
  52207. "RGBA": "rgba",
  52208. "INTENSITY": "intensity",
  52209. "CLASSIFICATION": "classification",
  52210. "GPS_TIME": "gps-time",
  52211. };
  52212. const replaceOldNames = (old) => {
  52213. if(replacements[old]){
  52214. return replacements[old];
  52215. }else {
  52216. return old;
  52217. }
  52218. };
  52219. const pointAttributes = [];
  52220. if(version.upTo('1.7')){
  52221. for(let attributeName of cloudjs.pointAttributes){
  52222. const oldAttribute = PointAttribute[attributeName];
  52223. const attribute = {
  52224. name: oldAttribute.name,
  52225. size: oldAttribute.byteSize,
  52226. elements: oldAttribute.numElements,
  52227. elementSize: oldAttribute.byteSize / oldAttribute.numElements,
  52228. type: oldAttribute.type.name,
  52229. description: "",
  52230. };
  52231. pointAttributes.push(attribute);
  52232. }
  52233. }else {
  52234. pointAttributes.push(...cloudjs.pointAttributes);
  52235. }
  52236. {
  52237. const attributes = new PointAttributes();
  52238. const typeConversion = {
  52239. int8: PointAttributeTypes.DATA_TYPE_INT8,
  52240. int16: PointAttributeTypes.DATA_TYPE_INT16,
  52241. int32: PointAttributeTypes.DATA_TYPE_INT32,
  52242. int64: PointAttributeTypes.DATA_TYPE_INT64,
  52243. uint8: PointAttributeTypes.DATA_TYPE_UINT8,
  52244. uint16: PointAttributeTypes.DATA_TYPE_UINT16,
  52245. uint32: PointAttributeTypes.DATA_TYPE_UINT32,
  52246. uint64: PointAttributeTypes.DATA_TYPE_UINT64,
  52247. double: PointAttributeTypes.DATA_TYPE_DOUBLE,
  52248. float: PointAttributeTypes.DATA_TYPE_FLOAT,
  52249. };
  52250. for(let jsAttribute of pointAttributes){
  52251. if(jsAttribute.name == void 0){ //add 有的是这个,也有的不是(点云编辑页的)
  52252. var attribute_ = PointAttribute[jsAttribute];
  52253. attributes.add(attribute_);
  52254. continue;
  52255. }
  52256. const name = replaceOldNames(jsAttribute.name);
  52257. const type = typeConversion[jsAttribute.type];
  52258. const numElements = jsAttribute.elements;
  52259. const description = jsAttribute.description;
  52260. const attribute = new PointAttribute(name, type, numElements);
  52261. attributes.add(attribute);
  52262. }
  52263. {
  52264. // check if it has normals
  52265. let hasNormals =
  52266. pointAttributes.find(a => a.name === "NormalX") !== undefined &&
  52267. pointAttributes.find(a => a.name === "NormalY") !== undefined &&
  52268. pointAttributes.find(a => a.name === "NormalZ") !== undefined;
  52269. if(hasNormals){
  52270. let vector = {
  52271. name: "NORMAL",
  52272. attributes: ["NormalX", "NormalY", "NormalZ"],
  52273. };
  52274. attributes.addVector(vector);
  52275. }
  52276. }
  52277. return attributes;
  52278. }
  52279. }
  52280. function lasLazAttributes(fMno){
  52281. const attributes = new PointAttributes();
  52282. attributes.add(PointAttribute.POSITION_CARTESIAN);
  52283. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  52284. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  52285. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  52286. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  52287. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  52288. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  52289. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  52290. //attributes.add(new PointAttribute("pointSourceID", PointAttributeTypes.DATA_TYPE_INT8, 4));
  52291. return attributes;
  52292. }
  52293. class POCLoader {
  52294. static load(url, timeStamp, callback){ //add timeStamp
  52295. try {
  52296. let pco = new PointCloudOctreeGeometry();
  52297. pco.timeStamp = timeStamp;
  52298. pco.url = url;
  52299. let xhr = XHRFactory.createXMLHttpRequest();
  52300. xhr.open('GET', url+'?m='+timeStamp, true);
  52301. xhr.onreadystatechange = function () {
  52302. if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
  52303. let fMno = JSON.parse(xhr.responseText);
  52304. let version = new Version(fMno.version);
  52305. // assume octreeDir is absolute if it starts with http
  52306. if (fMno.octreeDir.indexOf('http') === 0) {
  52307. pco.octreeDir = fMno.octreeDir;
  52308. } else {
  52309. pco.octreeDir = url + '/../' + fMno.octreeDir;
  52310. }
  52311. pco.spacing = fMno.spacing;
  52312. pco.hierarchyStepSize = fMno.hierarchyStepSize;
  52313. pco.pointAttributes = fMno.pointAttributes;
  52314. let min = new Vector3(fMno.boundingBox.lx, fMno.boundingBox.ly, fMno.boundingBox.lz);
  52315. let max = new Vector3(fMno.boundingBox.ux, fMno.boundingBox.uy, fMno.boundingBox.uz);
  52316. let boundingBox = new Box3(min, max);
  52317. let tightBoundingBox = boundingBox.clone();
  52318. if (fMno.tightBoundingBox) {//这个才是真实的bounding,前面那个bounding的size是个正方体,似乎取了最长边作为边长
  52319. tightBoundingBox.min.copy(new Vector3(fMno.tightBoundingBox.lx, fMno.tightBoundingBox.ly, fMno.tightBoundingBox.lz));
  52320. tightBoundingBox.max.copy(new Vector3(fMno.tightBoundingBox.ux, fMno.tightBoundingBox.uy, fMno.tightBoundingBox.uz));
  52321. }
  52322. let offset = min.clone(); //将成为点云的position,被我用作旋转中心(但在点云中不那么居中,navvis也是这样, 这样可能是为了让模型在这数据的bounding上)
  52323. boundingBox.min.sub(offset); //点云的真实坐标的min都是0,0,0吗(我看案例是,因绕角落旋转,也就是原点)
  52324. boundingBox.max.sub(offset);
  52325. tightBoundingBox.min.sub(offset);
  52326. tightBoundingBox.max.sub(offset);
  52327. //改
  52328. //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 ",
  52329. //"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" //给地图
  52330. pco.boundingBox = boundingBox;
  52331. pco.tightBoundingBox = tightBoundingBox;
  52332. pco.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  52333. pco.tightBoundingSphere = tightBoundingBox.getBoundingSphere(new Sphere());
  52334. pco.offset = offset;
  52335. if (fMno.pointAttributes === 'LAS') {
  52336. pco.loader = new LasLazLoader(fMno.version, "las");
  52337. pco.pointAttributes = lasLazAttributes(fMno);
  52338. } else if (fMno.pointAttributes === 'LAZ') {
  52339. pco.loader = new LasLazLoader(fMno.version, "laz");
  52340. pco.pointAttributes = lasLazAttributes(fMno);
  52341. } else {
  52342. pco.loader = new BinaryLoader(fMno.version, boundingBox, fMno.scale);
  52343. pco.pointAttributes = parseAttributes(fMno);
  52344. }
  52345. let nodes = {};
  52346. { // load root
  52347. let name = 'r';
  52348. let root = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  52349. root.level = 0;
  52350. root.hasChildren = true;
  52351. root.spacing = pco.spacing;
  52352. if (version.upTo('1.5')) {
  52353. root.numPoints = fMno.hierarchy[0][1];
  52354. } else {
  52355. root.numPoints = 0;
  52356. }
  52357. pco.root = root;
  52358. pco.root.load();
  52359. nodes[name] = root;
  52360. }
  52361. // load remaining hierarchy
  52362. if (version.upTo('1.4')) {
  52363. for (let i = 1; i < fMno.hierarchy.length; i++) {
  52364. let name = fMno.hierarchy[i][0];
  52365. let numPoints = fMno.hierarchy[i][1];
  52366. let index = parseInt(name.charAt(name.length - 1));
  52367. let parentName = name.substring(0, name.length - 1);
  52368. let parentNode = nodes[parentName];
  52369. let level = name.length - 1;
  52370. //let boundingBox = POCLoader.createChildAABB(parentNode.boundingBox, index);
  52371. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  52372. let node = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  52373. node.level = level;
  52374. node.numPoints = numPoints;
  52375. node.spacing = pco.spacing / Math.pow(2, level);
  52376. parentNode.addChild(node);
  52377. nodes[name] = node;
  52378. }
  52379. }
  52380. pco.nodes = nodes;
  52381. callback(pco);
  52382. }
  52383. };
  52384. xhr.send(null);
  52385. } catch (e) {
  52386. console.log("loading failed: '" + url + "'");
  52387. console.log(e);
  52388. callback();
  52389. }
  52390. }
  52391. loadPointAttributes(mno){
  52392. let fpa = mno.pointAttributes;
  52393. let pa = new PointAttributes();
  52394. for (let i = 0; i < fpa.length; i++) {
  52395. let pointAttribute = PointAttribute[fpa[i]];
  52396. pa.add(pointAttribute);
  52397. }
  52398. return pa;
  52399. }
  52400. createChildAABB(aabb, index){
  52401. let min = aabb.min.clone();
  52402. let max = aabb.max.clone();
  52403. let size = new Vector3().subVectors(max, min);
  52404. if ((index & 0b0001) > 0) {
  52405. min.z += size.z / 2;
  52406. } else {
  52407. max.z -= size.z / 2;
  52408. }
  52409. if ((index & 0b0010) > 0) {
  52410. min.y += size.y / 2;
  52411. } else {
  52412. max.y -= size.y / 2;
  52413. }
  52414. if ((index & 0b0100) > 0) {
  52415. min.x += size.x / 2;
  52416. } else {
  52417. max.x -= size.x / 2;
  52418. }
  52419. return new Box3(min, max);
  52420. }
  52421. }
  52422. class OctreeGeometry{
  52423. constructor(){
  52424. this.url = null;
  52425. this.spacing = 0;
  52426. this.boundingBox = null;
  52427. this.root = null;
  52428. this.pointAttributes = null;
  52429. this.loader = null;
  52430. }
  52431. };
  52432. class OctreeGeometryNode{
  52433. constructor(name, octreeGeometry, boundingBox){
  52434. this.id = OctreeGeometryNode.IDCount++;
  52435. this.name = name;
  52436. this.index = parseInt(name.charAt(name.length - 1));
  52437. this.octreeGeometry = octreeGeometry;
  52438. this.boundingBox = boundingBox;
  52439. this.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  52440. this.children = {};
  52441. this.numPoints = 0;
  52442. this.level = null;
  52443. this.oneTimeDisposeHandlers = [];
  52444. }
  52445. isGeometryNode(){
  52446. return true;
  52447. }
  52448. getLevel(){
  52449. return this.level;
  52450. }
  52451. isTreeNode(){
  52452. return false;
  52453. }
  52454. isLoaded(){
  52455. return this.loaded;
  52456. }
  52457. getBoundingSphere(){
  52458. return this.boundingSphere;
  52459. }
  52460. getBoundingBox(){
  52461. return this.boundingBox;
  52462. }
  52463. getChildren(){
  52464. let children = [];
  52465. for (let i = 0; i < 8; i++) {
  52466. if (this.children[i]) {
  52467. children.push(this.children[i]);
  52468. }
  52469. }
  52470. return children;
  52471. }
  52472. getBoundingBox(){
  52473. return this.boundingBox;
  52474. }
  52475. load(){
  52476. if (Potree.numNodesLoading >= Potree.maxNodesLoading) {
  52477. return;
  52478. }
  52479. this.octreeGeometry.loader.load(this);
  52480. }
  52481. getNumPoints(){
  52482. return this.numPoints;
  52483. }
  52484. dispose(){
  52485. if (this.geometry && this.parent != null) {
  52486. this.geometry.dispose();
  52487. this.geometry = null;
  52488. this.loaded = false;
  52489. // this.dispatchEvent( { type: 'dispose' } );
  52490. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  52491. let handler = this.oneTimeDisposeHandlers[i];
  52492. handler();
  52493. }
  52494. this.oneTimeDisposeHandlers = [];
  52495. }
  52496. }
  52497. };
  52498. OctreeGeometryNode.IDCount = 0;
  52499. // let loadedNodes = new Set();
  52500. class NodeLoader{
  52501. constructor(url){
  52502. this.url = url;
  52503. }
  52504. async load(node){
  52505. if(node.loaded || node.loading){
  52506. return;
  52507. }
  52508. node.loading = true;
  52509. Potree.numNodesLoading++;
  52510. // console.log(node.name, node.numPoints);
  52511. // if(loadedNodes.has(node.name)){
  52512. // // debugger;
  52513. // }
  52514. // loadedNodes.add(node.name);
  52515. try{
  52516. if(node.nodeType === 2){
  52517. await this.loadHierarchy(node);
  52518. }
  52519. let {byteOffset, byteSize} = node;
  52520. let urlOctree = `${this.url}/../octree.bin`;
  52521. let first = byteOffset;
  52522. let last = byteOffset + byteSize - 1n;
  52523. let buffer;
  52524. if(byteSize === 0n){
  52525. buffer = new ArrayBuffer(0);
  52526. console.warn(`loaded node with 0 bytes: ${node.name}`);
  52527. }else {
  52528. let response = await fetch(urlOctree, {
  52529. headers: {
  52530. 'content-type': 'multipart/byteranges',
  52531. 'Range': `bytes=${first}-${last}`,
  52532. },
  52533. });
  52534. buffer = await response.arrayBuffer();
  52535. }
  52536. let workerPath;
  52537. if(this.metadata.encoding === "BROTLI"){
  52538. workerPath = Potree.scriptPath + '/workers/2.0/DecoderWorker_brotli.js';
  52539. }else {
  52540. workerPath = Potree.scriptPath + '/workers/2.0/DecoderWorker.js';
  52541. }
  52542. let worker = Potree.workerPool.getWorker(workerPath);
  52543. worker.onmessage = function (e) {
  52544. let data = e.data;
  52545. let buffers = data.attributeBuffers;
  52546. Potree.workerPool.returnWorker(workerPath, worker);
  52547. let geometry = new BufferGeometry();
  52548. for(let property in buffers){
  52549. let buffer = buffers[property].buffer;
  52550. if(property === "position"){
  52551. geometry.setAttribute('position', new BufferAttribute(new Float32Array(buffer), 3));
  52552. }else if(property === "rgba"){
  52553. geometry.setAttribute('rgba', new BufferAttribute(new Uint8Array(buffer), 4, true));
  52554. }else if(property === "NORMAL"){
  52555. //geometry.setAttribute('rgba', new THREE.BufferAttribute(new Uint8Array(buffer), 4, true));
  52556. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  52557. }else if (property === "INDICES") {
  52558. let bufferAttribute = new BufferAttribute(new Uint8Array(buffer), 4);
  52559. bufferAttribute.normalized = true;
  52560. geometry.setAttribute('indices', bufferAttribute);
  52561. }else {
  52562. const bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  52563. let batchAttribute = buffers[property].attribute;
  52564. bufferAttribute.potree = {
  52565. offset: buffers[property].offset,
  52566. scale: buffers[property].scale,
  52567. preciseBuffer: buffers[property].preciseBuffer,
  52568. range: batchAttribute.range,
  52569. };
  52570. geometry.setAttribute(property, bufferAttribute);
  52571. }
  52572. }
  52573. // indices ??
  52574. node.density = data.density;
  52575. node.geometry = geometry;
  52576. node.loaded = true;
  52577. node.loading = false;
  52578. Potree.numNodesLoading--;
  52579. };
  52580. let pointAttributes = node.octreeGeometry.pointAttributes;
  52581. let scale = node.octreeGeometry.scale;
  52582. let box = node.boundingBox;
  52583. let min = node.octreeGeometry.offset.clone().add(box.min);
  52584. let size = box.max.clone().sub(box.min);
  52585. let max = min.clone().add(size);
  52586. let numPoints = node.numPoints;
  52587. let offset = node.octreeGeometry.loader.offset;
  52588. let message = {
  52589. name: node.name,
  52590. buffer: buffer,
  52591. pointAttributes: pointAttributes,
  52592. scale: scale,
  52593. min: min,
  52594. max: max,
  52595. size: size,
  52596. offset: offset,
  52597. numPoints: numPoints
  52598. };
  52599. worker.postMessage(message, [message.buffer]);
  52600. }catch(e){
  52601. node.loaded = false;
  52602. node.loading = false;
  52603. Potree.numNodesLoading--;
  52604. console.log(`failed to load ${node.name}`);
  52605. console.log(e);
  52606. console.log(`trying again!`);
  52607. }
  52608. }
  52609. parseHierarchy(node, buffer){
  52610. let view = new DataView(buffer);
  52611. let tStart = performance.now();
  52612. let bytesPerNode = 22;
  52613. let numNodes = buffer.byteLength / bytesPerNode;
  52614. let octree = node.octreeGeometry;
  52615. // let nodes = [node];
  52616. let nodes = new Array(numNodes);
  52617. nodes[0] = node;
  52618. let nodePos = 1;
  52619. for(let i = 0; i < numNodes; i++){
  52620. let current = nodes[i];
  52621. let type = view.getUint8(i * bytesPerNode + 0);
  52622. let childMask = view.getUint8(i * bytesPerNode + 1);
  52623. let numPoints = view.getUint32(i * bytesPerNode + 2, true);
  52624. let byteOffset = view.getBigInt64(i * bytesPerNode + 6, true);
  52625. let byteSize = view.getBigInt64(i * bytesPerNode + 14, true);
  52626. // if(byteSize === 0n){
  52627. // // debugger;
  52628. // }
  52629. if(current.nodeType === 2){
  52630. // replace proxy with real node
  52631. current.byteOffset = byteOffset;
  52632. current.byteSize = byteSize;
  52633. current.numPoints = numPoints;
  52634. }else if(type === 2){
  52635. // load proxy
  52636. current.hierarchyByteOffset = byteOffset;
  52637. current.hierarchyByteSize = byteSize;
  52638. current.numPoints = numPoints;
  52639. }else {
  52640. // load real node
  52641. current.byteOffset = byteOffset;
  52642. current.byteSize = byteSize;
  52643. current.numPoints = numPoints;
  52644. }
  52645. if(current.byteSize === 0n){
  52646. // workaround for issue #1125
  52647. // some inner nodes erroneously report >0 points even though have 0 points
  52648. // however, they still report a byteSize of 0, so based on that we now set node.numPoints to 0
  52649. current.numPoints = 0;
  52650. }
  52651. current.nodeType = type;
  52652. if(current.nodeType === 2){
  52653. continue;
  52654. }
  52655. for(let childIndex = 0; childIndex < 8; childIndex++){
  52656. let childExists = ((1 << childIndex) & childMask) !== 0;
  52657. if(!childExists){
  52658. continue;
  52659. }
  52660. let childName = current.name + childIndex;
  52661. let childAABB = createChildAABB(current.boundingBox, childIndex);
  52662. let child = new OctreeGeometryNode(childName, octree, childAABB);
  52663. child.name = childName;
  52664. child.spacing = current.spacing / 2;
  52665. child.level = current.level + 1;
  52666. current.children[childIndex] = child;
  52667. child.parent = current;
  52668. // nodes.push(child);
  52669. nodes[nodePos] = child;
  52670. nodePos++;
  52671. }
  52672. // if((i % 500) === 0){
  52673. // yield;
  52674. // }
  52675. }
  52676. let duration = (performance.now() - tStart);
  52677. // if(duration > 20){
  52678. // let msg = `duration: ${duration}ms, numNodes: ${numNodes}`;
  52679. // console.log(msg);
  52680. // }
  52681. }
  52682. async loadHierarchy(node){
  52683. let {hierarchyByteOffset, hierarchyByteSize} = node;
  52684. let hierarchyPath = `${this.url}/../hierarchy.bin`;
  52685. let first = hierarchyByteOffset;
  52686. let last = first + hierarchyByteSize - 1n;
  52687. let response = await fetch(hierarchyPath, {
  52688. headers: {
  52689. 'content-type': 'multipart/byteranges',
  52690. 'Range': `bytes=${first}-${last}`,
  52691. },
  52692. });
  52693. let buffer = await response.arrayBuffer();
  52694. this.parseHierarchy(node, buffer);
  52695. // let promise = new Promise((resolve) => {
  52696. // let generator = this.parseHierarchy(node, buffer);
  52697. // let repeatUntilDone = () => {
  52698. // let result = generator.next();
  52699. // if(result.done){
  52700. // resolve();
  52701. // }else{
  52702. // requestAnimationFrame(repeatUntilDone);
  52703. // }
  52704. // };
  52705. // repeatUntilDone();
  52706. // });
  52707. // await promise;
  52708. }
  52709. }
  52710. let tmpVec3 = new Vector3();
  52711. function createChildAABB(aabb, index){
  52712. let min = aabb.min.clone();
  52713. let max = aabb.max.clone();
  52714. let size = tmpVec3.subVectors(max, min);
  52715. if ((index & 0b0001) > 0) {
  52716. min.z += size.z / 2;
  52717. } else {
  52718. max.z -= size.z / 2;
  52719. }
  52720. if ((index & 0b0010) > 0) {
  52721. min.y += size.y / 2;
  52722. } else {
  52723. max.y -= size.y / 2;
  52724. }
  52725. if ((index & 0b0100) > 0) {
  52726. min.x += size.x / 2;
  52727. } else {
  52728. max.x -= size.x / 2;
  52729. }
  52730. return new Box3(min, max);
  52731. }
  52732. let typenameTypeattributeMap = {
  52733. "double": PointAttributeTypes.DATA_TYPE_DOUBLE,
  52734. "float": PointAttributeTypes.DATA_TYPE_FLOAT,
  52735. "int8": PointAttributeTypes.DATA_TYPE_INT8,
  52736. "uint8": PointAttributeTypes.DATA_TYPE_UINT8,
  52737. "int16": PointAttributeTypes.DATA_TYPE_INT16,
  52738. "uint16": PointAttributeTypes.DATA_TYPE_UINT16,
  52739. "int32": PointAttributeTypes.DATA_TYPE_INT32,
  52740. "uint32": PointAttributeTypes.DATA_TYPE_UINT32,
  52741. "int64": PointAttributeTypes.DATA_TYPE_INT64,
  52742. "uint64": PointAttributeTypes.DATA_TYPE_UINT64,
  52743. };
  52744. class OctreeLoader{
  52745. static parseAttributes(jsonAttributes){
  52746. let attributes = new PointAttributes();
  52747. let replacements = {
  52748. "rgb": "rgba",
  52749. };
  52750. for (const jsonAttribute of jsonAttributes) {
  52751. let {name, description, size, numElements, elementSize, min, max} = jsonAttribute;
  52752. let type = typenameTypeattributeMap[jsonAttribute.type];
  52753. let potreeAttributeName = replacements[name] ? replacements[name] : name;
  52754. let attribute = new PointAttribute(potreeAttributeName, type, numElements);
  52755. if(numElements === 1){
  52756. attribute.range = [min[0], max[0]];
  52757. }else {
  52758. attribute.range = [min, max];
  52759. }
  52760. if (name === "gps-time") { // HACK: Guard against bad gpsTime range in metadata, see potree/potree#909
  52761. if (attribute.range[0] === attribute.range[1]) {
  52762. attribute.range[1] += 1;
  52763. }
  52764. }
  52765. attribute.initialRange = attribute.range;
  52766. attributes.add(attribute);
  52767. }
  52768. {
  52769. // check if it has normals
  52770. let hasNormals =
  52771. attributes.attributes.find(a => a.name === "NormalX") !== undefined &&
  52772. attributes.attributes.find(a => a.name === "NormalY") !== undefined &&
  52773. attributes.attributes.find(a => a.name === "NormalZ") !== undefined;
  52774. if(hasNormals){
  52775. let vector = {
  52776. name: "NORMAL",
  52777. attributes: ["NormalX", "NormalY", "NormalZ"],
  52778. };
  52779. attributes.addVector(vector);
  52780. }
  52781. }
  52782. return attributes;
  52783. }
  52784. static async load(url){
  52785. let response = await fetch(url);
  52786. let metadata = await response.json();
  52787. let attributes = OctreeLoader.parseAttributes(metadata.attributes);
  52788. let loader = new NodeLoader(url);
  52789. loader.metadata = metadata;
  52790. loader.attributes = attributes;
  52791. loader.scale = metadata.scale;
  52792. loader.offset = metadata.offset;
  52793. let octree = new OctreeGeometry();
  52794. octree.url = url;
  52795. octree.spacing = metadata.spacing;
  52796. octree.scale = metadata.scale;
  52797. // let aPosition = metadata.attributes.find(a => a.name === "position");
  52798. // octree
  52799. let min = new Vector3(...metadata.boundingBox.min);
  52800. let max = new Vector3(...metadata.boundingBox.max);
  52801. let boundingBox = new Box3(min, max);
  52802. let offset = min.clone();
  52803. boundingBox.min.sub(offset);
  52804. boundingBox.max.sub(offset);
  52805. octree.projection = metadata.projection;
  52806. octree.boundingBox = boundingBox;
  52807. octree.tightBoundingBox = boundingBox.clone();
  52808. octree.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  52809. octree.tightBoundingSphere = boundingBox.getBoundingSphere(new Sphere());
  52810. octree.offset = offset;
  52811. octree.pointAttributes = OctreeLoader.parseAttributes(metadata.attributes);
  52812. octree.loader = loader;
  52813. let root = new OctreeGeometryNode("r", octree, boundingBox);
  52814. root.level = 0;
  52815. root.nodeType = 2;
  52816. root.hierarchyByteOffset = 0n;
  52817. root.hierarchyByteSize = BigInt(metadata.hierarchy.firstChunkSize);
  52818. root.hasChildren = false;
  52819. root.spacing = octree.spacing;
  52820. root.byteOffset = 0;
  52821. octree.root = root;
  52822. loader.load(root);
  52823. let result = {
  52824. geometry: octree,
  52825. };
  52826. return result;
  52827. }
  52828. };
  52829. /**
  52830. * @author Connor Manning
  52831. */
  52832. class EptLoader {
  52833. static async load(file, callback) {
  52834. let response = await fetch(file);
  52835. let json = await response.json();
  52836. let url = file.substr(0, file.lastIndexOf('ept.json'));
  52837. let geometry = new Potree.PointCloudEptGeometry(url, json);
  52838. let root = new Potree.PointCloudEptGeometryNode(geometry);
  52839. geometry.root = root;
  52840. geometry.root.load();
  52841. callback(geometry);
  52842. }
  52843. };
  52844. class EptBinaryLoader {
  52845. extension() {
  52846. return '.bin';
  52847. }
  52848. workerPath() {
  52849. return Potree.scriptPath + '/workers/EptBinaryDecoderWorker.js';
  52850. }
  52851. load(node) {
  52852. if (node.loaded) return;
  52853. let url = node.url() + this.extension();
  52854. let xhr = XHRFactory.createXMLHttpRequest();
  52855. xhr.open('GET', url, true);
  52856. xhr.responseType = 'arraybuffer';
  52857. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  52858. xhr.onreadystatechange = () => {
  52859. if (xhr.readyState === 4) {
  52860. if (xhr.status === 200) {
  52861. let buffer = xhr.response;
  52862. this.parse(node, buffer);
  52863. } else {
  52864. console.log('Failed ' + url + ': ' + xhr.status);
  52865. }
  52866. }
  52867. };
  52868. try {
  52869. xhr.send(null);
  52870. }
  52871. catch (e) {
  52872. console.log('Failed request: ' + e);
  52873. }
  52874. }
  52875. parse(node, buffer) {
  52876. let workerPath = this.workerPath();
  52877. let worker = Potree.workerPool.getWorker(workerPath);
  52878. worker.onmessage = function(e) {
  52879. let g = new BufferGeometry();
  52880. let numPoints = e.data.numPoints;
  52881. let position = new Float32Array(e.data.position);
  52882. g.setAttribute('position', new BufferAttribute(position, 3));
  52883. let indices = new Uint8Array(e.data.indices);
  52884. g.setAttribute('indices', new BufferAttribute(indices, 4));
  52885. if (e.data.color) {
  52886. let color = new Uint8Array(e.data.color);
  52887. g.setAttribute('color', new BufferAttribute(color, 4, true));
  52888. }
  52889. if (e.data.intensity) {
  52890. let intensity = new Float32Array(e.data.intensity);
  52891. g.setAttribute('intensity',
  52892. new BufferAttribute(intensity, 1));
  52893. }
  52894. if (e.data.classification) {
  52895. let classification = new Uint8Array(e.data.classification);
  52896. g.setAttribute('classification',
  52897. new BufferAttribute(classification, 1));
  52898. }
  52899. if (e.data.returnNumber) {
  52900. let returnNumber = new Uint8Array(e.data.returnNumber);
  52901. g.setAttribute('return number',
  52902. new BufferAttribute(returnNumber, 1));
  52903. }
  52904. if (e.data.numberOfReturns) {
  52905. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  52906. g.setAttribute('number of returns',
  52907. new BufferAttribute(numberOfReturns, 1));
  52908. }
  52909. if (e.data.pointSourceId) {
  52910. let pointSourceId = new Uint16Array(e.data.pointSourceId);
  52911. g.setAttribute('source id',
  52912. new BufferAttribute(pointSourceId, 1));
  52913. }
  52914. g.attributes.indices.normalized = true;
  52915. let tightBoundingBox = new Box3(
  52916. new Vector3().fromArray(e.data.tightBoundingBox.min),
  52917. new Vector3().fromArray(e.data.tightBoundingBox.max)
  52918. );
  52919. node.doneLoading(
  52920. g,
  52921. tightBoundingBox,
  52922. numPoints,
  52923. new Vector3(...e.data.mean));
  52924. Potree.workerPool.returnWorker(workerPath, worker);
  52925. };
  52926. let toArray = (v) => [v.x, v.y, v.z];
  52927. let message = {
  52928. buffer: buffer,
  52929. schema: node.ept.schema,
  52930. scale: node.ept.eptScale,
  52931. offset: node.ept.eptOffset,
  52932. mins: toArray(node.key.b.min)
  52933. };
  52934. worker.postMessage(message, [message.buffer]);
  52935. }
  52936. };
  52937. /**
  52938. * laslaz code taken and adapted from plas.io js-laslaz
  52939. * http://plas.io/
  52940. * https://github.com/verma/plasio
  52941. *
  52942. * Thanks to Uday Verma and Howard Butler
  52943. *
  52944. */
  52945. class EptLaszipLoader {
  52946. load(node) {
  52947. if (node.loaded) return;
  52948. let url = node.url() + '.laz';
  52949. let xhr = XHRFactory.createXMLHttpRequest();
  52950. xhr.open('GET', url, true);
  52951. xhr.responseType = 'arraybuffer';
  52952. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  52953. xhr.onreadystatechange = () => {
  52954. if (xhr.readyState === 4) {
  52955. if (xhr.status === 200) {
  52956. let buffer = xhr.response;
  52957. this.parse(node, buffer);
  52958. } else {
  52959. console.log('Failed ' + url + ': ' + xhr.status);
  52960. }
  52961. }
  52962. };
  52963. xhr.send(null);
  52964. }
  52965. async parse(node, buffer){
  52966. let lf = new LASFile(buffer);
  52967. let handler = new EptLazBatcher(node);
  52968. try{
  52969. await lf.open();
  52970. lf.isOpen = true;
  52971. const header = await lf.getHeader();
  52972. {
  52973. let i = 0;
  52974. let toArray = (v) => [v.x, v.y, v.z];
  52975. let mins = toArray(node.key.b.min);
  52976. let maxs = toArray(node.key.b.max);
  52977. let hasMoreData = true;
  52978. while(hasMoreData){
  52979. const data = await lf.readData(1000000, 0, 1);
  52980. let d = new LASDecoder(
  52981. data.buffer,
  52982. header.pointsFormatId,
  52983. header.pointsStructSize,
  52984. data.count,
  52985. header.scale,
  52986. header.offset,
  52987. mins,
  52988. maxs);
  52989. d.extraBytes = header.extraBytes;
  52990. d.pointsFormatId = header.pointsFormatId;
  52991. handler.push(d);
  52992. i += data.count;
  52993. hasMoreData = data.hasMoreData;
  52994. }
  52995. header.totalRead = i;
  52996. header.versionAsString = lf.versionAsString;
  52997. header.isCompressed = lf.isCompressed;
  52998. await lf.close();
  52999. lf.isOpen = false;
  53000. }
  53001. }catch(err){
  53002. console.error('Error reading LAZ:', err);
  53003. if (lf.isOpen) {
  53004. await lf.close();
  53005. lf.isOpen = false;
  53006. }
  53007. throw err;
  53008. }
  53009. }
  53010. };
  53011. class EptLazBatcher {
  53012. constructor(node) { this.node = node; }
  53013. push(las) {
  53014. let workerPath = Potree.scriptPath +
  53015. '/workers/EptLaszipDecoderWorker.js';
  53016. let worker = Potree.workerPool.getWorker(workerPath);
  53017. worker.onmessage = (e) => {
  53018. let g = new BufferGeometry();
  53019. let numPoints = las.pointsCount;
  53020. let positions = new Float32Array(e.data.position);
  53021. let colors = new Uint8Array(e.data.color);
  53022. let intensities = new Float32Array(e.data.intensity);
  53023. let classifications = new Uint8Array(e.data.classification);
  53024. let returnNumbers = new Uint8Array(e.data.returnNumber);
  53025. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  53026. let pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  53027. let indices = new Uint8Array(e.data.indices);
  53028. let gpsTime = new Float32Array(e.data.gpsTime);
  53029. g.setAttribute('position',
  53030. new BufferAttribute(positions, 3));
  53031. g.setAttribute('rgba',
  53032. new BufferAttribute(colors, 4, true));
  53033. g.setAttribute('intensity',
  53034. new BufferAttribute(intensities, 1));
  53035. g.setAttribute('classification',
  53036. new BufferAttribute(classifications, 1));
  53037. g.setAttribute('return number',
  53038. new BufferAttribute(returnNumbers, 1));
  53039. g.setAttribute('number of returns',
  53040. new BufferAttribute(numberOfReturns, 1));
  53041. g.setAttribute('source id',
  53042. new BufferAttribute(pointSourceIDs, 1));
  53043. g.setAttribute('indices',
  53044. new BufferAttribute(indices, 4));
  53045. g.setAttribute('gpsTime',
  53046. new BufferAttribute(gpsTime, 1));
  53047. this.node.gpsTime = e.data.gpsMeta;
  53048. g.attributes.indices.normalized = true;
  53049. let tightBoundingBox = new Box3(
  53050. new Vector3().fromArray(e.data.tightBoundingBox.min),
  53051. new Vector3().fromArray(e.data.tightBoundingBox.max)
  53052. );
  53053. this.node.doneLoading(
  53054. g,
  53055. tightBoundingBox,
  53056. numPoints,
  53057. new Vector3(...e.data.mean));
  53058. Potree.workerPool.returnWorker(workerPath, worker);
  53059. };
  53060. let message = {
  53061. buffer: las.arrayb,
  53062. numPoints: las.pointsCount,
  53063. pointSize: las.pointSize,
  53064. pointFormatID: las.pointsFormatId,
  53065. scale: las.scale,
  53066. offset: las.offset,
  53067. mins: las.mins,
  53068. maxs: las.maxs
  53069. };
  53070. worker.postMessage(message, [message.buffer]);
  53071. };
  53072. };
  53073. class EptZstandardLoader extends EptBinaryLoader {
  53074. extension() {
  53075. return '.zst';
  53076. }
  53077. workerPath() {
  53078. return Potree.scriptPath + '/workers/EptZstandardDecoderWorker.js';
  53079. }
  53080. };
  53081. class ShapefileLoader{
  53082. constructor(){
  53083. this.transform = null;
  53084. }
  53085. async load(path){
  53086. const matLine = new LineMaterial( {
  53087. color: 0xff0000,
  53088. linewidth: 3, // in pixels
  53089. resolution: new Vector2(1000, 1000),
  53090. dashed: false
  53091. } );
  53092. const features = await this.loadShapefileFeatures(path);
  53093. const node = new Object3D();
  53094. for(const feature of features){
  53095. const fnode = this.featureToSceneNode(feature, matLine);
  53096. node.add(fnode);
  53097. }
  53098. let setResolution = (x, y) => {
  53099. matLine.resolution.set(x, y);
  53100. };
  53101. const result = {
  53102. features: features,
  53103. node: node,
  53104. setResolution: setResolution,
  53105. };
  53106. return result;
  53107. }
  53108. featureToSceneNode(feature, matLine){
  53109. let geometry = feature.geometry;
  53110. let color = new Color(1, 1, 1);
  53111. let transform = this.transform;
  53112. if(transform === null){
  53113. transform = {forward: (v) => v};
  53114. }
  53115. if(feature.geometry.type === "Point"){
  53116. let sg = new SphereGeometry(1, 18, 18);
  53117. let sm = new MeshNormalMaterial();
  53118. let s = new Mesh(sg, sm);
  53119. let [long, lat] = geometry.coordinates;
  53120. let pos = transform.forward([long, lat]);
  53121. s.position.set(...pos, 20);
  53122. s.scale.set(10, 10, 10);
  53123. return s;
  53124. }else if(geometry.type === "LineString"){
  53125. let coordinates = [];
  53126. let min = new Vector3(Infinity, Infinity, Infinity);
  53127. for(let i = 0; i < geometry.coordinates.length; i++){
  53128. let [long, lat] = geometry.coordinates[i];
  53129. let pos = transform.forward([long, lat]);
  53130. min.x = Math.min(min.x, pos[0]);
  53131. min.y = Math.min(min.y, pos[1]);
  53132. min.z = Math.min(min.z, 20);
  53133. coordinates.push(...pos, 20);
  53134. if(i > 0 && i < geometry.coordinates.length - 1){
  53135. coordinates.push(...pos, 20);
  53136. }
  53137. }
  53138. for(let i = 0; i < coordinates.length; i += 3){
  53139. coordinates[i+0] -= min.x;
  53140. coordinates[i+1] -= min.y;
  53141. coordinates[i+2] -= min.z;
  53142. }
  53143. const lineGeometry = new LineGeometry();
  53144. lineGeometry.setPositions( coordinates );
  53145. const line = new Line2( lineGeometry, matLine );
  53146. line.computeLineDistances();
  53147. line.scale.set( 1, 1, 1 );
  53148. line.position.copy(min);
  53149. return line;
  53150. }else if(geometry.type === "Polygon"){
  53151. for(let pc of geometry.coordinates){
  53152. let coordinates = [];
  53153. let min = new Vector3(Infinity, Infinity, Infinity);
  53154. for(let i = 0; i < pc.length; i++){
  53155. let [long, lat] = pc[i];
  53156. let pos = transform.forward([long, lat]);
  53157. min.x = Math.min(min.x, pos[0]);
  53158. min.y = Math.min(min.y, pos[1]);
  53159. min.z = Math.min(min.z, 20);
  53160. coordinates.push(...pos, 20);
  53161. if(i > 0 && i < pc.length - 1){
  53162. coordinates.push(...pos, 20);
  53163. }
  53164. }
  53165. for(let i = 0; i < coordinates.length; i += 3){
  53166. coordinates[i+0] -= min.x;
  53167. coordinates[i+1] -= min.y;
  53168. coordinates[i+2] -= min.z;
  53169. }
  53170. const lineGeometry = new LineGeometry();
  53171. lineGeometry.setPositions( coordinates );
  53172. const line = new Line2( lineGeometry, matLine );
  53173. line.computeLineDistances();
  53174. line.scale.set( 1, 1, 1 );
  53175. line.position.copy(min);
  53176. return line;
  53177. }
  53178. }else {
  53179. console.log("unhandled feature: ", feature);
  53180. }
  53181. }
  53182. async loadShapefileFeatures(file){
  53183. let features = [];
  53184. let source = await shapefile.open(file);
  53185. while(true){
  53186. let result = await source.read();
  53187. if (result.done) {
  53188. break;
  53189. }
  53190. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  53191. features.push(result.value);
  53192. }
  53193. }
  53194. return features;
  53195. }
  53196. };
  53197. const defaultColors = {
  53198. "landuse": [0.5, 0.5, 0.5],
  53199. "natural": [0.0, 1.0, 0.0],
  53200. "places": [1.0, 0.0, 1.0],
  53201. "points": [0.0, 1.0, 1.0],
  53202. "roads": [1.0, 1.0, 0.0],
  53203. "waterways": [0.0, 0.0, 1.0],
  53204. "default": [0.9, 0.6, 0.1],
  53205. };
  53206. function getColor(feature){
  53207. let color = defaultColors[feature];
  53208. if(!color){
  53209. color = defaultColors["default"];
  53210. }
  53211. return color;
  53212. }
  53213. class Geopackage$1{
  53214. constructor(){
  53215. this.path = null;
  53216. this.node = null;
  53217. }
  53218. };
  53219. class GeoPackageLoader{
  53220. constructor(){
  53221. }
  53222. static async loadUrl(url, params){
  53223. await Promise.all([
  53224. Utils.loadScript(`${Potree.scriptPath}/lazylibs/geopackage/geopackage.js`),
  53225. Utils.loadScript(`${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.js`),
  53226. ]);
  53227. const result = await fetch(url);
  53228. const buffer = await result.arrayBuffer();
  53229. params = params || {};
  53230. params.source = url;
  53231. return GeoPackageLoader.loadBuffer(buffer, params);
  53232. }
  53233. static async loadBuffer(buffer, params){
  53234. await Promise.all([
  53235. Utils.loadScript(`${Potree.scriptPath}/lazylibs/geopackage/geopackage.js`),
  53236. Utils.loadScript(`${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.js`),
  53237. ]);
  53238. params = params || {};
  53239. const resolver = async (resolve) => {
  53240. let transform = params.transform;
  53241. if(!transform){
  53242. transform = {forward: (arg) => arg};
  53243. }
  53244. const wasmPath = `${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.wasm`;
  53245. const SQL = await initSqlJs({ locateFile: filename => wasmPath});
  53246. const u8 = new Uint8Array(buffer);
  53247. const data = await geopackage.open(u8);
  53248. window.data = data;
  53249. const geopackageNode = new Object3D();
  53250. geopackageNode.name = params.source;
  53251. geopackageNode.potree = {
  53252. source: params.source,
  53253. };
  53254. const geo = new Geopackage$1();
  53255. geo.path = params.source;
  53256. geo.node = geopackageNode;
  53257. const tables = data.getTables();
  53258. for(const table of tables.features){
  53259. const dao = data.getFeatureDao(table);
  53260. let boundingBox = dao.getBoundingBox();
  53261. boundingBox = boundingBox.projectBoundingBox(dao.projection, 'EPSG:4326');
  53262. const geoJson = data.queryForGeoJSONFeaturesInTable(table, boundingBox);
  53263. const matLine = new LineMaterial( {
  53264. color: new Color().setRGB(...getColor(table)),
  53265. linewidth: 2,
  53266. resolution: new Vector2(1000, 1000),
  53267. dashed: false
  53268. } );
  53269. const node = new Object3D();
  53270. node.name = table;
  53271. geo.node.add(node);
  53272. for(const [index, feature] of Object.entries(geoJson)){
  53273. //const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, transform);
  53274. const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, dao.projection, transform);
  53275. node.add(featureNode);
  53276. }
  53277. }
  53278. resolve(geo);
  53279. };
  53280. return new Promise(resolver);
  53281. }
  53282. static featureToSceneNode(feature, matLine, geopackageProjection, transform){
  53283. let geometry = feature.geometry;
  53284. let color = new Color(1, 1, 1);
  53285. if(feature.geometry.type === "Point"){
  53286. let sg = new SphereGeometry(1, 18, 18);
  53287. let sm = new MeshNormalMaterial();
  53288. let s = new Mesh(sg, sm);
  53289. let [long, lat] = geometry.coordinates;
  53290. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  53291. s.position.set(...pos, 20);
  53292. s.scale.set(10, 10, 10);
  53293. return s;
  53294. }else if(geometry.type === "LineString"){
  53295. let coordinates = [];
  53296. let min = new Vector3(Infinity, Infinity, Infinity);
  53297. for(let i = 0; i < geometry.coordinates.length; i++){
  53298. let [long, lat] = geometry.coordinates[i];
  53299. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  53300. min.x = Math.min(min.x, pos[0]);
  53301. min.y = Math.min(min.y, pos[1]);
  53302. min.z = Math.min(min.z, 20);
  53303. coordinates.push(...pos, 20);
  53304. if(i > 0 && i < geometry.coordinates.length - 1){
  53305. coordinates.push(...pos, 20);
  53306. }
  53307. }
  53308. for(let i = 0; i < coordinates.length; i += 3){
  53309. coordinates[i+0] -= min.x;
  53310. coordinates[i+1] -= min.y;
  53311. coordinates[i+2] -= min.z;
  53312. }
  53313. const lineGeometry = new LineGeometry();
  53314. lineGeometry.setPositions( coordinates );
  53315. const line = new Line2( lineGeometry, matLine );
  53316. line.computeLineDistances();
  53317. line.scale.set( 1, 1, 1 );
  53318. line.position.copy(min);
  53319. return line;
  53320. }else if(geometry.type === "Polygon"){
  53321. for(let pc of geometry.coordinates){
  53322. let coordinates = [];
  53323. let min = new Vector3(Infinity, Infinity, Infinity);
  53324. for(let i = 0; i < pc.length; i++){
  53325. let [long, lat] = pc[i];
  53326. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  53327. min.x = Math.min(min.x, pos[0]);
  53328. min.y = Math.min(min.y, pos[1]);
  53329. min.z = Math.min(min.z, 20);
  53330. coordinates.push(...pos, 20);
  53331. if(i > 0 && i < pc.length - 1){
  53332. coordinates.push(...pos, 20);
  53333. }
  53334. }
  53335. for(let i = 0; i < coordinates.length; i += 3){
  53336. coordinates[i+0] -= min.x;
  53337. coordinates[i+1] -= min.y;
  53338. coordinates[i+2] -= min.z;
  53339. }
  53340. const lineGeometry = new LineGeometry();
  53341. lineGeometry.setPositions( coordinates );
  53342. const line = new Line2( lineGeometry, matLine );
  53343. line.computeLineDistances();
  53344. line.scale.set( 1, 1, 1 );
  53345. line.position.copy(min);
  53346. return line;
  53347. }
  53348. }else {
  53349. console.log("unhandled feature: ", feature);
  53350. }
  53351. }
  53352. };
  53353. class ClipVolume extends Object3D{
  53354. constructor(args){
  53355. super();
  53356. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  53357. this.name = "clip_volume_" + this.constructor.counter;
  53358. let alpha = args.alpha || 0;
  53359. let beta = args.beta || 0;
  53360. let gamma = args.gamma || 0;
  53361. this.rotation.x = alpha;
  53362. this.rotation.y = beta;
  53363. this.rotation.z = gamma;
  53364. this.clipOffset = 0.001;
  53365. this.clipRotOffset = 1;
  53366. let boxGeometry = new BoxGeometry(1, 1, 1);
  53367. boxGeometry.computeBoundingBox();
  53368. let boxFrameGeometry = new Geometry();
  53369. {
  53370. // bottom
  53371. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  53372. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  53373. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  53374. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  53375. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  53376. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  53377. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  53378. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  53379. // top
  53380. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  53381. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  53382. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  53383. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  53384. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  53385. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  53386. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  53387. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  53388. // sides
  53389. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  53390. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  53391. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  53392. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  53393. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  53394. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  53395. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  53396. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  53397. boxFrameGeometry.colors.push(new Vector3(1, 1, 1));
  53398. }
  53399. let planeFrameGeometry = new Geometry();
  53400. {
  53401. // middle line
  53402. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  53403. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  53404. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  53405. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  53406. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  53407. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  53408. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  53409. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  53410. }
  53411. this.dimension = new Vector3(1, 1, 1);
  53412. this.material = new MeshBasicMaterial( {
  53413. color: 0x00ff00,
  53414. transparent: true,
  53415. opacity: 0.3,
  53416. depthTest: true,
  53417. depthWrite: false} );
  53418. this.box = new Mesh(boxGeometry, this.material);
  53419. this.box.geometry.computeBoundingBox();
  53420. this.boundingBox = this.box.geometry.boundingBox;
  53421. this.add(this.box);
  53422. this.frame = new LineSegments( boxFrameGeometry, new LineBasicMaterial({color: 0x000000}));
  53423. this.add(this.frame);
  53424. this.planeFrame = new LineSegments( planeFrameGeometry, new LineBasicMaterial({color: 0xff0000}));
  53425. this.add(this.planeFrame);
  53426. // set default thickness
  53427. this.setScaleZ(0.1);
  53428. // create local coordinate system
  53429. let createArrow = (name, direction, color) => {
  53430. let material = new MeshBasicMaterial({
  53431. color: color,
  53432. depthTest: false,
  53433. depthWrite: false});
  53434. let shaftGeometry = new Geometry();
  53435. shaftGeometry.vertices.push(new Vector3(0, 0, 0));
  53436. shaftGeometry.vertices.push(new Vector3(0, 1, 0));
  53437. let shaftMaterial = new LineBasicMaterial({
  53438. color: color,
  53439. depthTest: false,
  53440. depthWrite: false,
  53441. transparent: true
  53442. });
  53443. let shaft = new Line(shaftGeometry, shaftMaterial);
  53444. shaft.name = name + "_shaft";
  53445. let headGeometry = new CylinderGeometry(0, 0.04, 0.1, 10, 1, false);
  53446. let headMaterial = material;
  53447. let head = new Mesh(headGeometry, headMaterial);
  53448. head.name = name + "_head";
  53449. head.position.y = 1;
  53450. let arrow = new Object3D();
  53451. arrow.name = name;
  53452. arrow.add(shaft);
  53453. arrow.add(head);
  53454. return arrow;
  53455. };
  53456. this.arrowX = createArrow("arrow_x", new Vector3(1, 0, 0), 0xFF0000);
  53457. this.arrowY = createArrow("arrow_y", new Vector3(0, 1, 0), 0x00FF00);
  53458. this.arrowZ = createArrow("arrow_z", new Vector3(0, 0, 1), 0x0000FF);
  53459. this.arrowX.rotation.z = -Math.PI / 2;
  53460. this.arrowZ.rotation.x = Math.PI / 2;
  53461. this.arrowX.visible = false;
  53462. this.arrowY.visible = false;
  53463. this.arrowZ.visible = false;
  53464. this.add(this.arrowX);
  53465. this.add(this.arrowY);
  53466. this.add(this.arrowZ);
  53467. { // event listeners
  53468. this.addEventListener("ui_select", e => {
  53469. this.arrowX.visible = true;
  53470. this.arrowY.visible = true;
  53471. this.arrowZ.visible = true;
  53472. });
  53473. this.addEventListener("ui_deselect", e => {
  53474. this.arrowX.visible = false;
  53475. this.arrowY.visible = false;
  53476. this.arrowZ.visible = false;
  53477. });
  53478. this.addEventListener("select", e => {
  53479. let scene_header = $("#" + this.name + " .scene_header");
  53480. if(!scene_header.next().is(":visible")) {
  53481. scene_header.click();
  53482. }
  53483. });
  53484. this.addEventListener("deselect", e => {
  53485. let scene_header = $("#" + this.name + " .scene_header");
  53486. if(scene_header.next().is(":visible")) {
  53487. scene_header.click();
  53488. }
  53489. });
  53490. }
  53491. this.update();
  53492. };
  53493. setClipOffset(offset) {
  53494. this.clipOffset = offset;
  53495. }
  53496. setClipRotOffset(offset) {
  53497. this.clipRotOffset = offset;
  53498. }
  53499. setScaleX(x) {
  53500. this.box.scale.x = x;
  53501. this.frame.scale.x = x;
  53502. this.planeFrame.scale.x = x;
  53503. }
  53504. setScaleY(y) {
  53505. this.box.scale.y = y;
  53506. this.frame.scale.y = y;
  53507. this.planeFrame.scale.y = y;
  53508. }
  53509. setScaleZ(z) {
  53510. this.box.scale.z = z;
  53511. this.frame.scale.z = z;
  53512. this.planeFrame.scale.z = z;
  53513. }
  53514. offset(args) {
  53515. let cs = args.cs || null;
  53516. let axis = args.axis || null;
  53517. let dir = args.dir || null;
  53518. if(!cs || !axis || !dir) return;
  53519. if(axis === "x") {
  53520. if(cs === "local") {
  53521. this.position.add(this.localX.clone().multiplyScalar(dir * this.clipOffset));
  53522. } else if(cs === "global") {
  53523. this.position.x = this.position.x + dir * this.clipOffset;
  53524. }
  53525. }else if(axis === "y") {
  53526. if(cs === "local") {
  53527. this.position.add(this.localY.clone().multiplyScalar(dir * this.clipOffset));
  53528. } else if(cs === "global") {
  53529. this.position.y = this.position.y + dir * this.clipOffset;
  53530. }
  53531. }else if(axis === "z") {
  53532. if(cs === "local") {
  53533. this.position.add(this.localZ.clone().multiplyScalar(dir * this.clipOffset));
  53534. } else if(cs === "global") {
  53535. this.position.z = this.position.z + dir * this.clipOffset;
  53536. }
  53537. }
  53538. this.dispatchEvent({"type": "clip_volume_changed", "viewer": viewer, "volume": this});
  53539. }
  53540. rotate(args) {
  53541. let cs = args.cs || null;
  53542. let axis = args.axis || null;
  53543. let dir = args.dir || null;
  53544. if(!cs || !axis || !dir) return;
  53545. if(cs === "local") {
  53546. if(axis === "x") {
  53547. this.rotateOnAxis(new Vector3(1, 0, 0), dir * this.clipRotOffset * Math.PI / 180);
  53548. } else if(axis === "y") {
  53549. this.rotateOnAxis(new Vector3(0, 1, 0), dir * this.clipRotOffset * Math.PI / 180);
  53550. } else if(axis === "z") {
  53551. this.rotateOnAxis(new Vector3(0, 0, 1), dir * this.clipRotOffset * Math.PI / 180);
  53552. }
  53553. } else if(cs === "global") {
  53554. let rotaxis = new Vector4(1, 0, 0, 0);
  53555. if(axis === "y") {
  53556. rotaxis = new Vector4(0, 1, 0, 0);
  53557. } else if(axis === "z") {
  53558. rotaxis = new Vector4(0, 0, 1, 0);
  53559. }
  53560. this.updateMatrixWorld();
  53561. let invM = newthis.matrixWorld.clone().invert();
  53562. rotaxis = rotaxis.applyMatrix4(invM).normalize();
  53563. rotaxis = new Vector3(rotaxis.x, rotaxis.y, rotaxis.z);
  53564. this.rotateOnAxis(rotaxis, dir * this.clipRotOffset * Math.PI / 180);
  53565. }
  53566. this.updateLocalSystem();
  53567. this.dispatchEvent({"type": "clip_volume_changed", "viewer": viewer, "volume": this});
  53568. }
  53569. update(){
  53570. this.boundingBox = this.box.geometry.boundingBox;
  53571. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  53572. this.box.visible = false;
  53573. this.updateLocalSystem();
  53574. };
  53575. updateLocalSystem() {
  53576. // extract local coordinate axes
  53577. let rotQuat = this.getWorldQuaternion();
  53578. this.localX = new Vector3(1, 0, 0).applyQuaternion(rotQuat).normalize();
  53579. this.localY = new Vector3(0, 1, 0).applyQuaternion(rotQuat).normalize();
  53580. this.localZ = new Vector3(0, 0, 1).applyQuaternion(rotQuat).normalize();
  53581. }
  53582. raycast(raycaster, intersects){
  53583. let is = [];
  53584. this.box.raycast(raycaster, is);
  53585. if(is.length > 0){
  53586. let I = is[0];
  53587. intersects.push({
  53588. distance: I.distance,
  53589. object: this,
  53590. point: I.point.clone()
  53591. });
  53592. }
  53593. };
  53594. };
  53595. //这个文件只是clipping polygon的,没用到
  53596. class ClippingTool extends EventDispatcher$1{
  53597. constructor(viewer){
  53598. super();
  53599. this.viewer = viewer;
  53600. this.maxPolygonVertices = 8;
  53601. this.addEventListener("start_inserting_clipping_volume", e => {
  53602. this.viewer.dispatchEvent({
  53603. type: "cancel_insertions"
  53604. });
  53605. });
  53606. this.sceneMarker = new Scene();
  53607. this.sceneVolume = new Scene();
  53608. this.sceneVolume.name = "scene_clip_volume";
  53609. this.viewer.inputHandler.registerInteractiveScene(this.sceneVolume);
  53610. this.onRemove = e => {
  53611. this.sceneVolume.remove(e.volume);
  53612. };
  53613. this.onAdd = e => {
  53614. this.sceneVolume.add(e.volume);
  53615. };
  53616. this.viewer.inputHandler.addEventListener("delete", e => {
  53617. let volumes = e.selection.filter(e => (e instanceof ClipVolume));
  53618. volumes.forEach(e => this.viewer.scene.removeClipVolume(e));
  53619. let polyVolumes = e.selection.filter(e => (e instanceof PolygonClipVolume));
  53620. polyVolumes.forEach(e => this.viewer.scene.removePolygonClipVolume(e));
  53621. });
  53622. }
  53623. setScene(scene){
  53624. if(this.scene === scene){
  53625. return;
  53626. }
  53627. if(this.scene){
  53628. this.scene.removeEventListeners("clip_volume_added", this.onAdd);
  53629. this.scene.removeEventListeners("clip_volume_removed", this.onRemove);
  53630. this.scene.removeEventListeners("polygon_clip_volume_added", this.onAdd);
  53631. this.scene.removeEventListeners("polygon_clip_volume_removed", this.onRemove);
  53632. }
  53633. this.scene = scene;
  53634. this.scene.addEventListener("clip_volume_added", this.onAdd);
  53635. this.scene.addEventListener("clip_volume_removed", this.onRemove);
  53636. this.scene.addEventListener("polygon_clip_volume_added", this.onAdd);
  53637. this.scene.addEventListener("polygon_clip_volume_removed", this.onRemove);
  53638. }
  53639. startInsertion(args = {}) {
  53640. let type = args.type || null;
  53641. if(!type) return null;
  53642. let domElement = this.viewer.renderer.domElement;
  53643. let canvasSize = this.viewer.renderer.getSize(new Vector2());
  53644. let svg = $(`
  53645. <svg height="${canvasSize.height}" width="${canvasSize.width}" style="position:absolute; pointer-events: none">
  53646. <defs>
  53647. <marker id="diamond" markerWidth="24" markerHeight="24" refX="12" refY="12"
  53648. markerUnits="userSpaceOnUse">
  53649. <circle cx="12" cy="12" r="6" fill="white" stroke="black" stroke-width="3"/>
  53650. </marker>
  53651. </defs>
  53652. <polyline fill="none" stroke="black"
  53653. style="stroke:rgb(0, 0, 0);
  53654. stroke-width:6;"
  53655. stroke-dasharray="9, 6"
  53656. stroke-dashoffset="2"
  53657. />
  53658. <polyline fill="none" stroke="black"
  53659. style="stroke:rgb(255, 255, 255);
  53660. stroke-width:2;"
  53661. stroke-dasharray="5, 10"
  53662. marker-start="url(#diamond)"
  53663. marker-mid="url(#diamond)"
  53664. marker-end="url(#diamond)"
  53665. />
  53666. </svg>`);
  53667. $(domElement.parentElement).append(svg);
  53668. let polyClipVol = new PolygonClipVolume(this.viewer.scene.getActiveCamera().clone());
  53669. this.dispatchEvent({"type": "start_inserting_clipping_volume"});
  53670. this.viewer.scene.addPolygonClipVolume(polyClipVol);
  53671. this.sceneMarker.add(polyClipVol);
  53672. let cancel = {
  53673. callback: null
  53674. };
  53675. let insertionCallback = (e) => {
  53676. if(e.button === MOUSE.LEFT){
  53677. polyClipVol.addMarker();
  53678. // SVC Screen Line
  53679. svg.find("polyline").each((index, target) => {
  53680. let newPoint = svg[0].createSVGPoint();
  53681. newPoint.x = e.offsetX;
  53682. newPoint.y = e.offsetY;
  53683. let polyline = target.points.appendItem(newPoint);
  53684. });
  53685. if(polyClipVol.markers.length > this.maxPolygonVertices){
  53686. cancel.callback();
  53687. }
  53688. this.viewer.inputHandler.startDragging(
  53689. polyClipVol.markers[polyClipVol.markers.length - 1]);
  53690. }else if(e.button === MOUSE.RIGHT){
  53691. cancel.callback(e);
  53692. }
  53693. };
  53694. cancel.callback = e => {
  53695. //let first = svg.find("polyline")[0].points[0];
  53696. //svg.find("polyline").each((index, target) => {
  53697. // let newPoint = svg[0].createSVGPoint();
  53698. // newPoint.x = first.x;
  53699. // newPoint.y = first.y;
  53700. // let polyline = target.points.appendItem(newPoint);
  53701. //});
  53702. svg.remove();
  53703. if(polyClipVol.markers.length > 3) {
  53704. polyClipVol.removeLastMarker();
  53705. polyClipVol.initialized = true;
  53706. } else {
  53707. this.viewer.scene.removePolygonClipVolume(polyClipVol);
  53708. }
  53709. this.viewer.renderer.domElement.removeEventListener("mouseup", insertionCallback, true);
  53710. this.viewer.removeEventListener("cancel_insertions", cancel.callback);
  53711. this.viewer.inputHandler.enabled = true;
  53712. };
  53713. this.viewer.addEventListener("cancel_insertions", cancel.callback);
  53714. this.viewer.renderer.domElement.addEventListener("mouseup", insertionCallback , true);
  53715. this.viewer.inputHandler.enabled = false;
  53716. polyClipVol.addMarker();
  53717. this.viewer.inputHandler.startDragging(
  53718. polyClipVol.markers[polyClipVol.markers.length - 1]);
  53719. return polyClipVol;
  53720. }
  53721. update() {
  53722. }
  53723. };
  53724. var GeoTIFF = (function (exports) {
  53725. 'use strict';
  53726. const Endianness = new Enum({
  53727. LITTLE: "II",
  53728. BIG: "MM",
  53729. });
  53730. const Type = new Enum({
  53731. BYTE: {value: 1, bytes: 1},
  53732. ASCII: {value: 2, bytes: 1},
  53733. SHORT: {value: 3, bytes: 2},
  53734. LONG: {value: 4, bytes: 4},
  53735. RATIONAL: {value: 5, bytes: 8},
  53736. SBYTE: {value: 6, bytes: 1},
  53737. UNDEFINED: {value: 7, bytes: 1},
  53738. SSHORT: {value: 8, bytes: 2},
  53739. SLONG: {value: 9, bytes: 4},
  53740. SRATIONAL: {value: 10, bytes: 8},
  53741. FLOAT: {value: 11, bytes: 4},
  53742. DOUBLE: {value: 12, bytes: 8},
  53743. });
  53744. const Tag = new Enum({
  53745. IMAGE_WIDTH: 256,
  53746. IMAGE_HEIGHT: 257,
  53747. BITS_PER_SAMPLE: 258,
  53748. COMPRESSION: 259,
  53749. PHOTOMETRIC_INTERPRETATION: 262,
  53750. STRIP_OFFSETS: 273,
  53751. ORIENTATION: 274,
  53752. SAMPLES_PER_PIXEL: 277,
  53753. ROWS_PER_STRIP: 278,
  53754. STRIP_BYTE_COUNTS: 279,
  53755. X_RESOLUTION: 282,
  53756. Y_RESOLUTION: 283,
  53757. PLANAR_CONFIGURATION: 284,
  53758. RESOLUTION_UNIT: 296,
  53759. SOFTWARE: 305,
  53760. COLOR_MAP: 320,
  53761. SAMPLE_FORMAT: 339,
  53762. MODEL_PIXEL_SCALE: 33550, // [GeoTIFF] TYPE: double N: 3
  53763. MODEL_TIEPOINT: 33922, // [GeoTIFF] TYPE: double N: 6 * NUM_TIEPOINTS
  53764. GEO_KEY_DIRECTORY: 34735, // [GeoTIFF] TYPE: short N: >= 4
  53765. GEO_DOUBLE_PARAMS: 34736, // [GeoTIFF] TYPE: short N: variable
  53766. GEO_ASCII_PARAMS: 34737, // [GeoTIFF] TYPE: ascii N: variable
  53767. });
  53768. const typeMapping = new Map([
  53769. [Type.BYTE, Uint8Array],
  53770. [Type.ASCII, Uint8Array],
  53771. [Type.SHORT, Uint16Array],
  53772. [Type.LONG, Uint32Array],
  53773. [Type.RATIONAL, Uint32Array],
  53774. [Type.SBYTE, Int8Array],
  53775. [Type.UNDEFINED, Uint8Array],
  53776. [Type.SSHORT, Int16Array],
  53777. [Type.SLONG, Int32Array],
  53778. [Type.SRATIONAL, Int32Array],
  53779. [Type.FLOAT, Float32Array],
  53780. [Type.DOUBLE, Float64Array],
  53781. ]);
  53782. class IFDEntry{
  53783. constructor(tag, type, count, offset, value){
  53784. this.tag = tag;
  53785. this.type = type;
  53786. this.count = count;
  53787. this.offset = offset;
  53788. this.value = value;
  53789. }
  53790. }
  53791. class Image{
  53792. constructor(){
  53793. this.width = 0;
  53794. this.height = 0;
  53795. this.buffer = null;
  53796. this.metadata = [];
  53797. }
  53798. }
  53799. class Reader{
  53800. constructor(){
  53801. }
  53802. static read(data){
  53803. let endiannessTag = String.fromCharCode(...Array.from(data.slice(0, 2)));
  53804. let endianness = Endianness.fromValue(endiannessTag);
  53805. let tiffCheckTag = data.readUInt8(2);
  53806. if(tiffCheckTag !== 42){
  53807. throw new Error("not a valid tiff file");
  53808. }
  53809. let offsetToFirstIFD = data.readUInt32LE(4);
  53810. console.log("offsetToFirstIFD", offsetToFirstIFD);
  53811. let ifds = [];
  53812. let IFDsRead = false;
  53813. let currentIFDOffset = offsetToFirstIFD;
  53814. let i = 0;
  53815. while(IFDsRead || i < 100){
  53816. console.log("currentIFDOffset", currentIFDOffset);
  53817. let numEntries = data.readUInt16LE(currentIFDOffset);
  53818. let nextIFDOffset = data.readUInt32LE(currentIFDOffset + 2 + numEntries * 12);
  53819. console.log("next offset: ", currentIFDOffset + 2 + numEntries * 12);
  53820. let entryBuffer = data.slice(currentIFDOffset + 2, currentIFDOffset + 2 + 12 * numEntries);
  53821. for(let i = 0; i < numEntries; i++){
  53822. let tag = Tag.fromValue(entryBuffer.readUInt16LE(i * 12));
  53823. let type = Type.fromValue(entryBuffer.readUInt16LE(i * 12 + 2));
  53824. let count = entryBuffer.readUInt32LE(i * 12 + 4);
  53825. let offsetOrValue = entryBuffer.readUInt32LE(i * 12 + 8);
  53826. let valueBytes = type.bytes * count;
  53827. let value;
  53828. if(valueBytes <= 4){
  53829. value = offsetOrValue;
  53830. }else {
  53831. let valueBuffer = new Uint8Array(valueBytes);
  53832. valueBuffer.set(data.slice(offsetOrValue, offsetOrValue + valueBytes));
  53833. let ArrayType = typeMapping.get(type);
  53834. value = new ArrayType(valueBuffer.buffer);
  53835. if(type === Type.ASCII){
  53836. value = String.fromCharCode(...value);
  53837. }
  53838. }
  53839. let ifd = new IFDEntry(tag, type, count, offsetOrValue, value);
  53840. ifds.push(ifd);
  53841. }
  53842. console.log("nextIFDOffset", nextIFDOffset);
  53843. if(nextIFDOffset === 0){
  53844. break;
  53845. }
  53846. currentIFDOffset = nextIFDOffset;
  53847. i++;
  53848. }
  53849. let ifdForTag = (tag) => {
  53850. for(let entry of ifds){
  53851. if(entry.tag === tag){
  53852. return entry;
  53853. }
  53854. }
  53855. return null;
  53856. };
  53857. let width = ifdForTag(Tag.IMAGE_WIDTH, ifds).value;
  53858. let height = ifdForTag(Tag.IMAGE_HEIGHT, ifds).value;
  53859. let compression = ifdForTag(Tag.COMPRESSION, ifds).value;
  53860. let rowsPerStrip = ifdForTag(Tag.ROWS_PER_STRIP, ifds).value;
  53861. let ifdStripOffsets = ifdForTag(Tag.STRIP_OFFSETS, ifds);
  53862. let ifdStripByteCounts = ifdForTag(Tag.STRIP_BYTE_COUNTS, ifds);
  53863. let numStrips = Math.ceil(height / rowsPerStrip);
  53864. let stripByteCounts = [];
  53865. for(let i = 0; i < ifdStripByteCounts.count; i++){
  53866. let type = ifdStripByteCounts.type;
  53867. let offset = ifdStripByteCounts.offset + i * type.bytes;
  53868. let value;
  53869. if(type === Type.SHORT){
  53870. value = data.readUInt16LE(offset);
  53871. }else if(type === Type.LONG){
  53872. value = data.readUInt32LE(offset);
  53873. }
  53874. stripByteCounts.push(value);
  53875. }
  53876. let stripOffsets = [];
  53877. for(let i = 0; i < ifdStripOffsets.count; i++){
  53878. let type = ifdStripOffsets.type;
  53879. let offset = ifdStripOffsets.offset + i * type.bytes;
  53880. let value;
  53881. if(type === Type.SHORT){
  53882. value = data.readUInt16LE(offset);
  53883. }else if(type === Type.LONG){
  53884. value = data.readUInt32LE(offset);
  53885. }
  53886. stripOffsets.push(value);
  53887. }
  53888. let imageBuffer = new Uint8Array(width * height * 3);
  53889. let linesProcessed = 0;
  53890. for(let i = 0; i < numStrips; i++){
  53891. let stripOffset = stripOffsets[i];
  53892. let stripBytes = stripByteCounts[i];
  53893. let stripData = data.slice(stripOffset, stripOffset + stripBytes);
  53894. let lineBytes = width * 3;
  53895. for(let y = 0; y < rowsPerStrip; y++){
  53896. let line = stripData.slice(y * lineBytes, y * lineBytes + lineBytes);
  53897. imageBuffer.set(line, linesProcessed * lineBytes);
  53898. if(line.length === lineBytes){
  53899. linesProcessed++;
  53900. }else {
  53901. break;
  53902. }
  53903. }
  53904. }
  53905. console.log(`width: ${width}`);
  53906. console.log(`height: ${height}`);
  53907. console.log(`numStrips: ${numStrips}`);
  53908. console.log("stripByteCounts", stripByteCounts.join(", "));
  53909. console.log("stripOffsets", stripOffsets.join(", "));
  53910. let image = new Image();
  53911. image.width = width;
  53912. image.height = height;
  53913. image.buffer = imageBuffer;
  53914. image.metadata = ifds;
  53915. return image;
  53916. }
  53917. }
  53918. class Exporter{
  53919. constructor(){
  53920. }
  53921. static toTiffBuffer(image, params = {}){
  53922. let offsetToFirstIFD = 8;
  53923. let headerBuffer = new Uint8Array([0x49, 0x49, 42, 0, offsetToFirstIFD, 0, 0, 0]);
  53924. let [width, height] = [image.width, image.height];
  53925. let ifds = [
  53926. new IFDEntry(Tag.IMAGE_WIDTH, Type.SHORT, 1, null, width),
  53927. new IFDEntry(Tag.IMAGE_HEIGHT, Type.SHORT, 1, null, height),
  53928. new IFDEntry(Tag.BITS_PER_SAMPLE, Type.SHORT, 4, null, new Uint16Array([8, 8, 8, 8])),
  53929. new IFDEntry(Tag.COMPRESSION, Type.SHORT, 1, null, 1),
  53930. new IFDEntry(Tag.PHOTOMETRIC_INTERPRETATION, Type.SHORT, 1, null, 2),
  53931. new IFDEntry(Tag.ORIENTATION, Type.SHORT, 1, null, 1),
  53932. new IFDEntry(Tag.SAMPLES_PER_PIXEL, Type.SHORT, 1, null, 4),
  53933. new IFDEntry(Tag.ROWS_PER_STRIP, Type.LONG, 1, null, height),
  53934. new IFDEntry(Tag.STRIP_BYTE_COUNTS, Type.LONG, 1, null, width * height * 3),
  53935. new IFDEntry(Tag.PLANAR_CONFIGURATION, Type.SHORT, 1, null, 1),
  53936. new IFDEntry(Tag.RESOLUTION_UNIT, Type.SHORT, 1, null, 1),
  53937. new IFDEntry(Tag.SOFTWARE, Type.ASCII, 6, null, "......"),
  53938. new IFDEntry(Tag.STRIP_OFFSETS, Type.LONG, 1, null, null),
  53939. new IFDEntry(Tag.X_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])),
  53940. new IFDEntry(Tag.Y_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])),
  53941. ];
  53942. if(params.ifdEntries){
  53943. ifds.push(...params.ifdEntries);
  53944. }
  53945. let valueOffset = offsetToFirstIFD + 2 + ifds.length * 12 + 4;
  53946. // create 12 byte buffer for each ifd and variable length buffers for ifd values
  53947. let ifdEntryBuffers = new Map();
  53948. let ifdValueBuffers = new Map();
  53949. for(let ifd of ifds){
  53950. let entryBuffer = new ArrayBuffer(12);
  53951. let entryView = new DataView(entryBuffer);
  53952. let valueBytes = ifd.type.bytes * ifd.count;
  53953. entryView.setUint16(0, ifd.tag.value, true);
  53954. entryView.setUint16(2, ifd.type.value, true);
  53955. entryView.setUint32(4, ifd.count, true);
  53956. if(ifd.count === 1 && ifd.type.bytes <= 4){
  53957. entryView.setUint32(8, ifd.value, true);
  53958. }else {
  53959. entryView.setUint32(8, valueOffset, true);
  53960. let valueBuffer = new Uint8Array(ifd.count * ifd.type.bytes);
  53961. if(ifd.type === Type.ASCII){
  53962. valueBuffer.set(new Uint8Array(ifd.value.split("").map(c => c.charCodeAt(0))));
  53963. }else {
  53964. valueBuffer.set(new Uint8Array(ifd.value.buffer));
  53965. }
  53966. ifdValueBuffers.set(ifd.tag, valueBuffer);
  53967. valueOffset = valueOffset + valueBuffer.byteLength;
  53968. }
  53969. ifdEntryBuffers.set(ifd.tag, entryBuffer);
  53970. }
  53971. let imageBufferOffset = valueOffset;
  53972. new DataView(ifdEntryBuffers.get(Tag.STRIP_OFFSETS)).setUint32(8, imageBufferOffset, true);
  53973. let concatBuffers = (buffers) => {
  53974. let totalLength = buffers.reduce( (sum, buffer) => (sum + buffer.byteLength), 0);
  53975. let merged = new Uint8Array(totalLength);
  53976. let offset = 0;
  53977. for(let buffer of buffers){
  53978. merged.set(new Uint8Array(buffer), offset);
  53979. offset += buffer.byteLength;
  53980. }
  53981. return merged;
  53982. };
  53983. let ifdBuffer = concatBuffers([
  53984. new Uint16Array([ifds.length]),
  53985. ...ifdEntryBuffers.values(),
  53986. new Uint32Array([0])]);
  53987. let ifdValueBuffer = concatBuffers([...ifdValueBuffers.values()]);
  53988. let tiffBuffer = concatBuffers([
  53989. headerBuffer,
  53990. ifdBuffer,
  53991. ifdValueBuffer,
  53992. image.buffer
  53993. ]);
  53994. return {width: width, height: height, buffer: tiffBuffer};
  53995. }
  53996. }
  53997. exports.Tag = Tag;
  53998. exports.Type = Type;
  53999. exports.IFDEntry = IFDEntry;
  54000. exports.Image = Image;
  54001. exports.Reader = Reader;
  54002. exports.Exporter = Exporter;
  54003. return exports;
  54004. }({}));
  54005. class Message{
  54006. constructor(content){
  54007. this.content = content;
  54008. let closeIcon = `${exports.resourcePath}/icons/close.svg`;
  54009. this.element = $(`
  54010. <div class="potree_message">
  54011. <span name="content_container" style="flex-grow: 1; padding: 5px"></span>
  54012. <img name="close" src="${closeIcon}" class="button-icon" style="width: 16px; height: 16px;">
  54013. </div>`);
  54014. this.elClose = this.element.find("img[name=close]");
  54015. this.elContainer = this.element.find("span[name=content_container]");
  54016. if(typeof content === "string"){
  54017. this.elContainer.append($(`<span>${content}</span>`));
  54018. }else {
  54019. this.elContainer.append(content);
  54020. }
  54021. }
  54022. setMessage(content){
  54023. this.elContainer.empty();
  54024. if(typeof content === "string"){
  54025. this.elContainer.append($(`<span>${content}</span>`));
  54026. }else {
  54027. this.elContainer.append(content);
  54028. }
  54029. }
  54030. }
  54031. class PointCloudSM{
  54032. constructor(potreeRenderer){
  54033. this.potreeRenderer = potreeRenderer;
  54034. this.threeRenderer = this.potreeRenderer.threeRenderer;
  54035. this.target = new WebGLRenderTarget(2 * 1024, 2 * 1024, {
  54036. minFilter: LinearFilter,
  54037. magFilter: LinearFilter,
  54038. format: RGBAFormat,
  54039. type: FloatType
  54040. });
  54041. this.target.depthTexture = new DepthTexture();
  54042. this.target.depthTexture.type = UnsignedIntType;
  54043. //this.threeRenderer.setClearColor(0x000000, 1);
  54044. this.threeRenderer.setClearColor(0xff0000, 1);
  54045. //HACK? removed while moving to three.js 109
  54046. //this.threeRenderer.clearTarget(this.target, true, true, true);
  54047. {
  54048. const oldTarget = this.threeRenderer.getRenderTarget();
  54049. this.threeRenderer.setRenderTarget(this.target);
  54050. this.threeRenderer.clear(true, true, true);
  54051. this.threeRenderer.setRenderTarget(oldTarget);
  54052. }
  54053. }
  54054. setLight(light){
  54055. this.light = light;
  54056. let fov = (180 * light.angle) / Math.PI;
  54057. let aspect = light.shadow.mapSize.width / light.shadow.mapSize.height;
  54058. let near = 0.1;
  54059. let far = light.distance === 0 ? 10000 : light.distance;
  54060. this.camera = new PerspectiveCamera(fov, aspect, near, far);
  54061. this.camera.up.set(0, 0, 1);
  54062. this.camera.position.copy(light.position);
  54063. let target = new Vector3().subVectors(light.position, light.getWorldDirection(new Vector3()));
  54064. this.camera.lookAt(target);
  54065. this.camera.updateProjectionMatrix();
  54066. this.camera.updateMatrix();
  54067. this.camera.updateMatrixWorld();
  54068. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  54069. }
  54070. setSize(width, height){
  54071. if(this.target.width !== width || this.target.height !== height){
  54072. this.target.dispose();
  54073. }
  54074. this.target.setSize(width, height);
  54075. }
  54076. render(scene, camera){
  54077. this.threeRenderer.setClearColor(0x000000, 1);
  54078. const oldTarget = this.threeRenderer.getRenderTarget();
  54079. this.threeRenderer.setRenderTarget(this.target);
  54080. this.threeRenderer.clear(true, true, true);
  54081. this.potreeRenderer.render(scene, this.camera, this.target, {});
  54082. this.threeRenderer.setRenderTarget(oldTarget);
  54083. }
  54084. }
  54085. class Label extends EventDispatcher{
  54086. constructor(o={}){
  54087. super();
  54088. this.position = o.pos;
  54089. this.text = o.text || '';
  54090. this.elem = $('<div class="hide"><a></a></div>');
  54091. o.className && this.elem.addClass(o.className);
  54092. this.elem.find('a').html(this.text);
  54093. $("#potree_labels").append(this.elem);
  54094. this.pos2d = new Vector3;
  54095. this.dom = o.dom || viewer.renderArea;
  54096. this.camera = o.camera || viewer.scene.getActiveCamera();
  54097. let update = (e)=>{
  54098. this.update(e);
  54099. };
  54100. viewer.addEventListener('camera_changed', update);
  54101. this.addEventListener('dispose', ()=>{
  54102. viewer.removeEventListener('camera_changed', update);
  54103. this.dispose();
  54104. });
  54105. }
  54106. update(){
  54107. if(!this.position || this.elem.hasClass('unvisible'))return
  54108. var p = Utils.getPos2d(this.position, viewer.mainViewport,this.dom);
  54109. if(!p.trueSide){
  54110. this.elem.addClass("hide"); return;
  54111. }
  54112. this.elem.css({
  54113. left: p.pos.x +'px',
  54114. top: p.pos.y +'px'
  54115. });
  54116. this.elem.removeClass("hide");
  54117. this.pos2d = p.vector;
  54118. }
  54119. setVisible(visi){
  54120. if(!visi){
  54121. this.elem.addClass("unvisible");
  54122. }else {
  54123. this.elem.removeClass("unvisible");
  54124. this.update();
  54125. }
  54126. }
  54127. setText(text){
  54128. this.text = text || '';
  54129. this.elem.find('a').html(this.text);
  54130. }
  54131. setPos(pos){
  54132. this.position = pos;
  54133. }
  54134. dispose(){
  54135. this.elem.remove();
  54136. this.removeAllListeners();
  54137. }
  54138. }
  54139. const verticalLine = new Line3();
  54140. //控制点和边的合集。具有可以拖拽修改的功能,拖拽时能防止线相交。
  54141. class ctrlPolygon extends Object3D {
  54142. constructor (type, prop) {
  54143. super();
  54144. this.type = type;
  54145. this.maxMarkers = Number.MAX_SAFE_INTEGER;
  54146. this.transformData(prop);
  54147. for(let i in prop){
  54148. this[i] = prop[i];
  54149. }
  54150. if(this.atPlane && this.closed && this.dimension == '2d'){
  54151. this.areaPlane = this.createAreaPlane();
  54152. this.add(this.areaPlane);
  54153. }
  54154. //数据--刚开始一定是空的
  54155. this.points = [];
  54156. //mesh 不一定有
  54157. this.markers = [];
  54158. this.edges = [];
  54159. this.center;
  54160. }
  54161. initData(prop){
  54162. //开始加数据
  54163. if(Potree.settings.editType == 'merge'){ //融合页面没有地图,measure的不需要指定datasetId,每个点都有各自的datasetId,跟着各自的模型走
  54164. if(this.dataset_points){
  54165. this.dataset_points = this.dataset_points.map(e=>{
  54166. return e && new Vector3().copy(e)
  54167. });
  54168. prop.points = this.dataset_points.map((p,i)=>{
  54169. return Potree.Utils.datasetPosTransform({fromDataset:true, datasetId:this.points_datasets[i], position: p})
  54170. });
  54171. if(prop.points.some(e=>e == void 0)){
  54172. return false
  54173. }
  54174. }else {
  54175. this.dataset_points = [];
  54176. }
  54177. }
  54178. if(prop.points){
  54179. for(const p of prop.points){
  54180. const pos = new Vector3().copy(p);
  54181. this.addMarker({point:pos});
  54182. }
  54183. if(Potree.settings.editType != 'merge'){
  54184. if(this.datasetId != void 0){//初始化位置
  54185. if(this.dataset_points){
  54186. this.dataset_points = this.dataset_points.map(e=>{
  54187. return e && new Vector3().copy(e)
  54188. });
  54189. this.transformByPointcloud(); //根据dataset_points生成points
  54190. }
  54191. }else {
  54192. if(prop.dataset_points && prop.dataset_points.some(e=>e != void 0)){
  54193. console.error('存在测量线的datasetId为空而dataset_points有值,请检查并删除:'+this.sid);//存在过的bug,原因未知,可能是后台处理dataset时替换的错误:http://192.168.0.21/index.php?m=bug&f=view&bugID=23601
  54194. console.log(this);
  54195. }
  54196. }
  54197. }
  54198. this.facePlane = this.getFacePlane();
  54199. this.getPoint2dInfo(this.points);
  54200. this.update({ifUpdateMarkers:true});
  54201. //this.dragChange(new THREE.Vector3().copy(prop.points[prop.points.length-1]), prop.points.length-1);
  54202. this.setSelected(false );
  54203. this.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  54204. return true
  54205. }
  54206. }
  54207. addMarker(o={}){
  54208. var index = o.index == void 0 ? this.points.length : o.index; //要当第几个
  54209. this.points = [...this.points.slice(0,index), o.point, ...this.points.slice(index,this.points.length)];
  54210. //this.points.push(o.point);
  54211. if(o.marker){
  54212. this.add(o.marker);
  54213. this.markers = [...this.markers.slice(0,index), o.marker, ...this.markers.slice(index,this.markers.length)];
  54214. this.updateMarker(o.marker, o.point);
  54215. o.marker.addEventListener('drag', this.dragMarker.bind(this));
  54216. o.marker.addEventListener('drop', this.dropMarker.bind(this));
  54217. o.marker.createTime = Date.now();
  54218. let addHoverEvent = (e)=>{
  54219. let mouseover = (e) => {
  54220. this.setMarkerSelected(e.object, 'hover', 'single');
  54221. viewer.dispatchEvent({
  54222. type : "CursorChange", action : "add", name:"markerMove"
  54223. });
  54224. };
  54225. let mouseleave = (e) => {
  54226. this.setMarkerSelected(e.object, 'unhover', 'single');
  54227. viewer.dispatchEvent({
  54228. type : "CursorChange", action : "remove", name:"markerMove"
  54229. });
  54230. };
  54231. o.marker.addEventListener('mouseover', mouseover);
  54232. o.marker.addEventListener('mouseleave', mouseleave);
  54233. o.marker.addEventListener('startDragging', (e)=>{//for mobile
  54234. this.setMarkerSelected(o.marker, 'hover', 'single');
  54235. });
  54236. o.marker.addEventListener('drop', (e)=>{//for mobile
  54237. this.setMarkerSelected(o.marker, 'unhover', 'single');
  54238. });
  54239. o.marker.removeEventListener('addHoverEvent',addHoverEvent);
  54240. };
  54241. o.marker.addEventListener('addHoverEvent',addHoverEvent);//当非isNew时才添加事件
  54242. if(!this.isNew){
  54243. o.marker.dispatchEvent('addHoverEvent');
  54244. }
  54245. }
  54246. if(o.edge){
  54247. this.add(o.edge);
  54248. this.edges = [...this.edges.slice(0,index), o.edge, ...this.edges.slice(index,this.edges.length)];
  54249. }
  54250. }
  54251. dragMarker(e){
  54252. var I, atMap;
  54253. if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  54254. viewer.dispatchEvent({
  54255. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  54256. });
  54257. return
  54258. }
  54259. if(e.drag.pointerDelta.length() == 0 && !this.isNew){ //部分设备(华为matePad11)在touchstart后立即执行了touchmove,导致marker立即移动,需要屏蔽..(刚创建时也会是0)
  54260. return
  54261. }
  54262. viewer.dispatchEvent({
  54263. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  54264. });
  54265. atMap = e.drag.dragViewport.name == 'mapViewport';
  54266. if(atMap && this.unableDragAtMap){
  54267. e.drag.object = null; //取消拖拽
  54268. return
  54269. }
  54270. e.drag.object.isDragging = true;
  54271. I = e.intersect && (e.intersect.adsorption ? e.intersect.location : (e.intersect.orthoIntersect || e.intersect.location));
  54272. //记录数据集
  54273. //在三维中脱离点云(在map中拉到周围都没有点云的地方)的顶点,无法拖拽怎么办
  54274. if (I) {
  54275. let i = this.markers.indexOf(e.drag.object);
  54276. if (i !== -1) {
  54277. this.dragChange(I.clone(), i, atMap);
  54278. if(this.points_datasets){
  54279. if(e.intersect.pointcloud) this.points_datasets[i] = e.intersect.pointcloud.dataset_id;
  54280. else if(e.intersect.object) this.points_datasets[i] = e.intersect.object.dataset_id;
  54281. else this.points_datasets[i] = null;
  54282. }
  54283. }
  54284. this.editStateChange(true);
  54285. return true
  54286. }
  54287. };
  54288. dragChange(intersectPos, i, atMap){
  54289. let len = this.markers.length;
  54290. let oldPoint = this.points[i];
  54291. if(atMap){
  54292. intersectPos.setZ(oldPoint.z); //在地图上拖拽,不改变其高度。
  54293. }
  54294. let location = intersectPos.clone();
  54295. if(this.faceDirection && this.maxMarkers == 2 && len == 2){//add 固定方向的点不直接拖拽
  54296. var p1 = this.markers[0].position;
  54297. if(this.faceDirection == 'horizontal'){
  54298. var projectPos = location.clone().setZ(p1.z);
  54299. }else {
  54300. var projectPos = p1.clone().setZ(location.z);
  54301. }
  54302. //var p2 = p1.clone().add(this.direction)
  54303. //var projectPos = math.getFootPoint(location, p1, p2)
  54304. LineDraw.updateLine(this.guideLine, [location, projectPos]);
  54305. location = projectPos;
  54306. this.guideLine.visible = true;
  54307. }else if( len > 1 ){
  54308. var points = this.points.map(e=>e.clone());
  54309. points[i].copy(location); //算normal需要提前确认point
  54310. //若为定义了面朝向的矩形
  54311. if(this.faceDirection == 'horizontal'){
  54312. if(len == 2){
  54313. location.setZ(points[0].z);
  54314. }
  54315. if(!this.facePlane){//一个点就能确定面
  54316. this.facePlane = new Plane().setFromNormalAndCoplanarPoint( new Vector3(0,0,1), this.points[0] );
  54317. }
  54318. }else if(this.faceDirection == 'vertical'){//当有两个点时, 有两个方向的可能
  54319. if(len == 2){
  54320. if(this.isRect){
  54321. let vec = points[0].clone().sub(location);
  54322. if(Math.sqrt(vec.x*vec.x+vec.y*vec.y) > Math.abs(vec.z) ){//水平(高度差小于水平距离时)
  54323. location.setZ(points[0].z);
  54324. //this.cannotConfirmNormal = false;//能确定面为水平方向
  54325. }else {//垂直 (当两点一样时也属于这种)
  54326. location.setX(points[0].x);
  54327. location.setY(points[0].y);
  54328. //this.cannotConfirmNormal = true; //不能确定面,因第三点可绕着纵轴线自由移动
  54329. }
  54330. }
  54331. }else {
  54332. {//判断cannotConfirmNormal. 如果前几段都在竖直线上,就不能固定出面方向。
  54333. this.cannotConfirmNormal = true;
  54334. let max = this.isRect ? 1 : len-2;
  54335. for(let i=0;i<max;i++){
  54336. let p1 = points[i].clone();
  54337. let p2 = points[i+1].clone();
  54338. let vec = p1.sub(p2);
  54339. if(vec.x != 0 || vec.y != 0){
  54340. this.cannotConfirmNormal = false;
  54341. break;
  54342. }
  54343. }
  54344. }
  54345. if(!this.facePlane || this.cannotConfirmNormal){//三个点且为水平方向时,计算面
  54346. var points_ = points.map(e=>new Vector2(e.x,e.y));
  54347. var points2 = getDifferentPoint(points_, 2);
  54348. if(points2){
  54349. let normal = math.getNormal2d({p1:points2[0], p2:points2[1]});
  54350. normal = new Vector3(normal.x, normal.y, 0);
  54351. this.facePlane = new Plane().setFromNormalAndCoplanarPoint( normal, this.points[0] );
  54352. }
  54353. }
  54354. }
  54355. }
  54356. if(len > 2){
  54357. if(!this.faceDirection && this.showArea){
  54358. if(len == 3 || this.isRect) this.cannotConfirmNormal = true; //当第三个点固定后(有四个点时)才能固定面
  54359. if(!this.facePlane || this.cannotConfirmNormal){
  54360. var points3 = getDifferentPoint(points, 3);//只有找到三个不同的点算拥有面和area
  54361. if(points3){
  54362. this.facePlane = new Plane().setFromCoplanarPoints(...points3 );
  54363. }
  54364. }
  54365. }
  54366. if(this.atPlane && this.facePlane && !this.cannotConfirmNormal ){//之后加的点一定要在面上
  54367. if(atMap){
  54368. //地图上用垂直线,得到和面的交点。
  54369. verticalLine.set(location.clone().setZ(100000), location.clone().setZ(-100000));//确保长度范围覆盖所有测量面
  54370. location = this.facePlane.intersectLine(verticalLine, new Vector3() );
  54371. if(!location) return;
  54372. }else {
  54373. location = this.facePlane.projectPoint(intersectPos, new Vector3() );
  54374. }
  54375. }
  54376. points[i].copy(location);//再copy确认一次
  54377. if(len == 3 && this.faceDirection == 'horizontal' && this.closed){ //normal方向还不确定 会影响label在里侧还是外侧
  54378. let facePlane = new Plane().setFromCoplanarPoints(...points);
  54379. if(facePlane.normal.z && facePlane.normal.z * this.facePlane.normal.z < 0){
  54380. this.facePlane.normal.z *= -1, this.facePlane.constant *= -1;
  54381. //console.log(this.facePlane.normal, this.facePlane.constant)
  54382. }
  54383. }
  54384. if(this.isRect){ //是矩形 (即使没有faceDirection也能执行)
  54385. //根据前两个点计算当前和下一个点
  54386. var p1 = points[(i-2+len)%len];
  54387. var p2 = points[(i-1+len)%len];
  54388. if(p1.equals(p2)){//意外情况:重复点两次 ( bug点,改了好多遍)
  54389. if(this.faceDirection == 'vertical'){
  54390. p2.add(new Vector3(0,0,0.0001));
  54391. }else {
  54392. p2.add(new Vector3(0,0.0001,0));
  54393. }
  54394. }
  54395. //p3 : location
  54396. var foot = math.getFootPoint(location, p1, p2);//p2 修改p2到垂足的位置
  54397. var vec = foot.clone().sub(location);
  54398. var p4 = p1.clone().sub(vec);
  54399. points[(i-1+len)%len].copy(foot);
  54400. points[(i+1)%len].copy(p4);
  54401. this.setPosition((i-1+len)%len, foot);//p2
  54402. this.setPosition((i+1)%len, p4);
  54403. }
  54404. this.getPoint2dInfo(points);
  54405. var isIntersectSelf = this.atPlane && this.closed && !this.isRect && this.point2dInfo && this.intersectSelf(this.point2dInfo.points2d);//检测相交
  54406. this.isIntersectSelf = isIntersectSelf;
  54407. if(isIntersectSelf){//not-allowed
  54408. if(!this.isNew && isIntersectSelf == 'lastLine') this.isIntersectSelf = 'all'; //已经画好了就不用特别对待最后一条线
  54409. if(this.isIntersectSelf == 'lastLine'){
  54410. Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', false);
  54411. Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', false);
  54412. }else {
  54413. viewer.dispatchEvent({
  54414. type : "CursorChange", action : "add", name:"polygon_isIntersectSelf"
  54415. });
  54416. return
  54417. }
  54418. }
  54419. if(!this.isIntersectSelf){
  54420. this.areaPlane && Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', true);
  54421. this.areaLabel && Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', true);
  54422. }
  54423. if(!this.isIntersectSelf || this.isIntersectSelf == 'lastLine' ){
  54424. viewer.dispatchEvent({
  54425. type : "CursorChange", action : "remove", name:"polygon_isIntersectSelf"
  54426. });
  54427. }
  54428. }
  54429. var showGuideLine = len>1 && (this.faceDirection || len > 3);
  54430. if(showGuideLine && this.guideLine){
  54431. LineDraw.updateLine(this.guideLine, [intersectPos, location]);
  54432. this.guideLine.visible = true;
  54433. }
  54434. //console.log(this.points.map(e=>e.toArray()))
  54435. }
  54436. if(this.restrictArea){
  54437. let holes = this.restrictArea.holes.concat(this.restrictArea.parentHoles);
  54438. let holesPoints = holes.filter(e=>e!=this && e.points.length>2).map(e=>e.points);
  54439. if(!math.isPointInArea(this.restrictArea.points, holesPoints, location)){
  54440. viewer.dispatchEvent({
  54441. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  54442. });
  54443. this.isAtWrongPlace = true;
  54444. return
  54445. }
  54446. //就不处理相交线了。 有个缺点:floor上的hole可以限制room,但hole不受room限制,会导致room的marker被框在hole里而动不了。只能去调整hole了
  54447. }
  54448. viewer.dispatchEvent({
  54449. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  54450. });
  54451. this.isAtWrongPlace = false;
  54452. this.setPosition(i, location);
  54453. this.update();
  54454. this.dispatchEvent({type:'dragChange', index:i});
  54455. }
  54456. dropMarker(e){
  54457. //console.log('dropMarker')
  54458. if (this.isNew && e.pressDistance>Potree.config.clickMaxDragDis){//拖拽的话返回
  54459. return this.continueDrag(null,e)
  54460. }
  54461. if(e.hoverViewport != e.drag.dragViewport){//copy from dragMarker, for sitemodel, only mapViewport can be dropped
  54462. return this.continueDrag(null,e)
  54463. }
  54464. if(e.isTouch){
  54465. if(e.hoverViewport != viewer.mainViewport && this.unableDragAtMap){
  54466. viewer.dispatchEvent({type:'reticule_forbit', v:true});
  54467. //console.log('reticule_forbit',true)
  54468. return this.continueDrag(null,e)
  54469. }else {
  54470. viewer.dispatchEvent({type:'reticule_forbit', v:false});
  54471. //console.log('reticule_forbit',false)
  54472. }
  54473. this.isNew && this.dragMarker(e); //isNew触屏点击时必须先更新下点,因为指尖不在屏幕上时没更新。但对已经创建的marker点击时不应该更新
  54474. }
  54475. if (e.button != MOUSE.RIGHT && (//右键click的话继续执行,因为会停止
  54476. this.isIntersectSelf == 'all' && this.isNew //有线相交了
  54477. || this.isAtWrongPlace && this.isNew
  54478. || !e.isAtDomElement && this.isNew//如果是刚添加时在其他dom点击, 不要响应
  54479. || e.hoverViewport != viewer.mainViewport && this.unableDragAtMap //垂直的测量线不允许在地图上放点
  54480. || this.isNew && !getDifferentPoint(this.points, this.points.length ) //不允许和之前的点相同, 但这句在点云稀疏时会导致难结束
  54481. )
  54482. ){
  54483. return this.continueDrag(null,e)
  54484. }
  54485. //console.log('drop marker' )
  54486. let i = this.markers.indexOf(e.drag.object);
  54487. if (i !== -1) {
  54488. this.dispatchEvent({
  54489. 'type': 'marker_dropped',
  54490. 'index': i
  54491. });
  54492. if(this.markers.length>2 && this.facePlane)this.cannotConfirmNormal = false;
  54493. this.guideLine &&(this.guideLine.visible = false);
  54494. }
  54495. this.setMarkerSelected(e.drag.object, 'unhover', 'single');
  54496. this.editStateChange(false);
  54497. e.drag.endDragFun && e.drag.endDragFun(e);// addmarker
  54498. //if(this.changeCallBack)this.changeCallBack()
  54499. return true
  54500. };
  54501. getFacePlane(){//最普通一种get方法,根据顶点。且假设所有点已经共面,且不重合
  54502. if(/* !this.atPlane || */this.points.length<3) return
  54503. /* this.facePlane = new THREE.Plane().setFromCoplanarPoints(...this.points.slice(0,3) ) */
  54504. let facePlane = this.facePlane;
  54505. if(!this.atPlane || !facePlane){//多折线 没有实时更新facePlane所以重新算
  54506. let normal = new Vector3, len = this.points.length - 2;
  54507. for(let i=0;i<len;i++){ //获取normal的顺序方法必须和setFromCoplanarPoints一致
  54508. let vec0 = new Vector3().subVectors(this.points[i+2], this.points[i+1], );
  54509. let vec1 = new Vector3().subVectors(this.points[i], this.points[i+1]);
  54510. let nor = vec0.cross(vec1).normalize();
  54511. normal.add(nor);
  54512. }
  54513. normal.normalize();
  54514. facePlane = new Plane().setFromNormalAndCoplanarPoint(normal, this.points[0]);
  54515. }
  54516. return facePlane
  54517. }
  54518. getPoint2dInfo(points){ //在更新areaplane之前必须更新过point2dInfo
  54519. if(this.facePlane){
  54520. var originPoint0 = points[0].clone();
  54521. var qua = math.getQuaBetween2Vector(this.facePlane.normal, new Vector3(0,0,1), new Vector3(0,0,1));
  54522. let points2d = points.map(e=>e.clone().applyQuaternion(qua));
  54523. this.point2dInfo = {
  54524. originPoint0 ,
  54525. points2d,
  54526. quaInverse : qua.clone().invert()
  54527. };
  54528. }
  54529. }
  54530. setPosition (index, position) {//拖拽后设置位置
  54531. let point = this.points[index];
  54532. point.copy(position);
  54533. /* if(this.datasetId){
  54534. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.datasetId, position:point.clone()})
  54535. } */
  54536. /* if(Potree.settings.editType == 'merge'){
  54537. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true,this.points_datasets[i], position:point.clone()})
  54538. } */
  54539. let marker = this.markers[index];
  54540. this.updateMarker(marker, point);
  54541. }
  54542. updateMarker(marker, pos){
  54543. marker.position.copy(pos);
  54544. marker.waitUpdate();
  54545. }
  54546. intersectSelf(points2d){//add
  54547. var len = points2d.length;
  54548. for(var i=0;i<len;i++){
  54549. for(var j=i+2;j<len;j++){
  54550. if(Math.abs(j-len-i)<2)continue;//不和邻边比
  54551. var p1 = points2d[i];
  54552. var p2 = points2d[i+1];
  54553. var p3 = points2d[j];
  54554. var p4 = points2d[(j+1)%len];
  54555. if(p1.equals(p2) || p3.equals(p4) || p1.equals(p3) || p2.equals(p3) || p1.equals(p4) || p2.equals(p4))continue
  54556. var line1 = [p1,p2];
  54557. var line2 = [p3,p4];
  54558. var intersect = math.isLineIntersect(line1, line2, false, 0.001);
  54559. if(intersect){
  54560. if(i==len-1 || j==len-1){//最后一条线。如果还没绘制完,最后的线还没定下,可被允许继续绘制,但无法显示面积。
  54561. return 'lastLine'
  54562. }else {
  54563. return 'all'
  54564. }
  54565. break
  54566. }
  54567. }
  54568. }
  54569. }
  54570. removeMarker (index) {
  54571. this.points.splice(index, 1);
  54572. const marker = this.markers[index];
  54573. //this.remove(marker);
  54574. this.markers.splice(index, 1);
  54575. marker.dispatchEvent({type:'dispose'});
  54576. let edgeIndex = index; //(index === 0) ? 0 : (index - 1);
  54577. const edge = this.edges[edgeIndex];
  54578. if(edge){
  54579. this.remove(edge);
  54580. this.edges.splice(edgeIndex, 1);
  54581. edge.dispatchEvent({type:'dispose'});
  54582. }
  54583. this.point2dInfo && this.point2dInfo.points2d.splice(index, 1); //add
  54584. this.dispatchEvent({type:'removeMarker',index,marker});
  54585. }
  54586. createAreaPlane(mat){
  54587. var geometry = new Geometry();
  54588. var mesh = new Mesh(geometry, mat);
  54589. return mesh
  54590. }
  54591. updateAreaPlane(){
  54592. if(!this.point2dInfo)return
  54593. this.areaPlane.geometry.dispose();
  54594. if(this.points.length>2){
  54595. this.areaPlane.geometry = MeshDraw.getShapeGeo(this.point2dInfo.points2d);
  54596. var center = math.getCenterOfGravityPoint(this.point2dInfo.points2d); //重心
  54597. var firstPos = this.point2dInfo.points2d[0].clone();
  54598. firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距
  54599. firstPos.applyQuaternion(this.point2dInfo.quaInverse);
  54600. var vec = this.point2dInfo.originPoint0.clone().sub(firstPos);
  54601. center = new Vector3(center.x, center.y, 0);
  54602. center.applyQuaternion(this.point2dInfo.quaInverse);
  54603. this.areaPlane.quaternion.copy(this.point2dInfo.quaInverse);
  54604. this.areaPlane.position.copy(vec);
  54605. center.add(vec);
  54606. this.center = center;
  54607. }else {
  54608. this.areaPlane.geometry = new Geometry();
  54609. }
  54610. }
  54611. update(options={}){
  54612. if(this.points.length === 0){
  54613. return;
  54614. }
  54615. let lastIndex = this.points.length - 1;
  54616. for (let index = 0; index <= lastIndex; index++) {
  54617. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  54618. let previousIndex = (index === 0) ? lastIndex : index - 1;
  54619. let point = this.points[index];
  54620. let nextPoint = this.points[nextIndex];
  54621. let previousPoint = this.points[previousIndex];
  54622. if(options.ifUpdateMarkers){
  54623. this.updateMarker(this.markers[index], point);
  54624. }
  54625. if(!this.closed && nextIndex == 0 )break; //add
  54626. { // edges
  54627. let edge = this.edges[index];
  54628. if(edge){
  54629. LineDraw.updateLine(edge, [point, nextPoint]);
  54630. //edge.visible = index < lastIndex || this.isRect || (this.closed && !this.isNew);
  54631. }
  54632. }
  54633. }
  54634. if(this.areaPlane){
  54635. this.updateAreaPlane();
  54636. }
  54637. //this.dispatchEvent({type:'update'})
  54638. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed'); //暂时先这么都通知
  54639. }
  54640. dispose(){//add
  54641. this.parent.remove(this);
  54642. this.markers.concat(this.edges).forEach(e=>e.dispatchEvent({type:'dispose'}));
  54643. }
  54644. reDraw(restMarkerCount=0){//重新开始画
  54645. let pointCount = this.points.length - restMarkerCount; // restMarkerCount为需要留下的marker数量
  54646. while(pointCount > 0){
  54647. this.removeMarker(--pointCount);
  54648. }
  54649. this.point2dInfo = null;
  54650. this.facePlane = null;
  54651. }
  54652. setMarkerSelected(){}
  54653. editStateChange(state){
  54654. if(!state){
  54655. viewer.dispatchEvent({
  54656. type : "CursorChange", action : "remove", name:"polygon_isIntersectSelf"
  54657. });
  54658. viewer.dispatchEvent({
  54659. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  54660. });
  54661. viewer.dispatchEvent({type:'reticule_forbit', v:false});
  54662. this.markers.forEach(e=>e.isDragging = false );
  54663. }
  54664. }
  54665. transformData(prop){
  54666. const pick = (defaul, alternative) => {
  54667. if(defaul != null){
  54668. return defaul;
  54669. }else {
  54670. return alternative;
  54671. }
  54672. };
  54673. prop.showDistances = (prop.showDistances === null) ? true : prop.showDistances;
  54674. prop.showArea = pick(prop.showArea, false);
  54675. prop.showAngles = pick(prop.showAngles, false);
  54676. prop.showCoordinates = pick(prop.showCoordinates, false);
  54677. prop.showHeight = pick(prop.showHeight, false);
  54678. prop.showCircle = pick(prop.showCircle, false);
  54679. prop.showAzimuth = pick(prop.showAzimuth, false);
  54680. prop.showEdges = pick(prop.showEdges, true);
  54681. prop.closed = pick(prop.closed, false);
  54682. prop.maxMarkers = pick(prop.maxMarkers, Infinity);
  54683. prop.direction = prop.direction;//add
  54684. prop.type = prop.type;
  54685. prop.showGuideLine = pick(prop.showGuideLine, false);
  54686. prop.isRect = pick(prop.isRect, false);
  54687. }
  54688. setSelected(){}
  54689. continueDrag(marker, e){
  54690. let object = marker || e.drag.object;
  54691. object.isDragging = true;
  54692. this.editStateChange(true);
  54693. var timer = setTimeout(()=>{//等 drag=null之后 //右键拖拽结束后需要重新得到drag
  54694. if(this.parent && object.isDragging){
  54695. //console.log('continueDrag')
  54696. viewer.inputHandler.startDragging( object ,
  54697. {endDragFun: e.drag.endDragFun, notPressMouse:e.drag.notPressMouse, dragViewport:e.drag.dragViewport}
  54698. );
  54699. }
  54700. },1);
  54701. return timer
  54702. }
  54703. }
  54704. function getDifferentPoint(points, count){//for facePlane
  54705. var result = [];
  54706. for(let i=0;i<points.length;i++){
  54707. var p = points[i];
  54708. if(result.find(e=>e.equals(p)))continue;
  54709. else result.push(p);
  54710. if(result.length == count)break
  54711. }
  54712. if(result.length == count)return result
  54713. }
  54714. let texLoader$2 = new TextureLoader();
  54715. let defaultColor$1 = new Color(config$1.measure.default.color);
  54716. let highlightColor = new Color(config$1.measure.highlight.color);
  54717. let color = new Color(config$1.measure.color);
  54718. let textColor = new Color(config$1.measure.textColor);
  54719. var markerMats;
  54720. var lineMats;
  54721. var planeMats;
  54722. const textSizeRatio = math.linearClamp(window.outerWidth * window.outerHeight , 360*720, 1920*1080, 0.7, 1); //pc字显示大一些 用
  54723. const lineDepthInfo = {
  54724. clipDistance : 4,//消失距离
  54725. occlusionDistance: 1,//变为backColor距离
  54726. };
  54727. const markerMapShrink = browser.isMobile() ? 0.4 : 0.8; //触屏需要更大的热区
  54728. const markerSizeInfo = {
  54729. width2d : 18 / markerMapShrink , nearBound : 1.5, farBound : 15,
  54730. };
  54731. /* const markerSizeInfo = {
  54732. minSize : 10 , maxSize : 15 , nearBound : 1.5, farBound : 15,
  54733. } */
  54734. const labelSizeInfo = {width2d:200};
  54735. const mainLabelProp = {
  54736. //backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity},
  54737. backgroundColor: {r: 0, g: 0, b: 0, a:0},
  54738. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  54739. textBorderColor: {r:255, g: 255, b:255, a: 1.0},
  54740. textBorderThick:3 ,
  54741. fontsize: 15 * textSizeRatio,
  54742. borderRadius : 12, margin:{x:20,y:4},
  54743. renderOrder : 5, pickOrder:5,
  54744. disToLine:-0.15,
  54745. useDepth : true ,
  54746. // 2023.10 尽量不让数字被挡住
  54747. clipDistance : 10,//消失距离
  54748. occlusionDistance: 10,//变为backColor距离
  54749. maxOcclusionFactor:0.3,
  54750. maxClipFactor:0.8
  54751. };
  54752. const subLabelProp = {
  54753. backgroundColor: {r: 255, g: 255, b: 255, a:0},
  54754. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  54755. textBorderColor: {r:255, g: 255, b:255, a: 1.0},
  54756. textBorderThick:3 ,
  54757. fontsize: 14 * textSizeRatio,
  54758. renderOrder : 4, pickOrder:4,
  54759. disToLine:-0.13,
  54760. };
  54761. const angle = MathUtils.degToRad(5);//显示水平垂直辅助线的最小角度
  54762. const guideShowMinAngle = {min: angle, max: Math.PI/2 - angle};
  54763. class Measure$1 extends ctrlPolygon{
  54764. constructor (prop) {
  54765. prop.dimension = '2d';
  54766. super('measure',prop);
  54767. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  54768. this.name = this.measureType + this.constructor.counter; //'Measure_' + this.constructor.counter;
  54769. this.markerLabels = [];
  54770. this.edgeLabels = [];
  54771. this.angleLabels = [];
  54772. this.coordinateLabels = [];
  54773. this.area = {value:0,string:''};
  54774. if( this.showArea ){
  54775. this.areaLabel = this.createAreaLabel();
  54776. this.add(this.areaLabel);
  54777. }
  54778. //add:
  54779. if(this.atPlane || this.faceDirection){ //是一个平面上的话
  54780. this.createGuideLine();
  54781. }
  54782. if(this.measureType == 'Distance' /* || this.measureType.includes('MulDistance') */){
  54783. this.createHorVerGuideLine();
  54784. }
  54785. this.selectStates = {};
  54786. this.setUnitSystem(prop.unit || viewer.unitConvert.UnitService.defaultSystem);
  54787. Potree.Utils.setObjectLayers(this, 'measure' );
  54788. /* if(this.measureType == 'MulDistance'){
  54789. this.showTotalDis = true
  54790. this.totalDisLabel = this.createTotalDisLabel()
  54791. this.add(this.totalDisLabel)
  54792. }
  54793. */
  54794. //addMarkers:
  54795. this.initData(prop);
  54796. this.pointsPos2d = new Map; //屏幕上的二维坐标
  54797. this.points_datasets || (this.points_datasets = []); //存每个点是哪个数据集
  54798. this.addEventListener('marker_dropped',(e)=>{
  54799. this.updateDatasetBelong(e.index);
  54800. });
  54801. this.addEventListener('isVisible', ()=>{
  54802. viewer.mapViewer && viewer.mapViewer.dispatchEvent({type:'content_changed'});
  54803. });
  54804. }
  54805. initData(prop){
  54806. let makeIt = super.initData(prop);
  54807. if(makeIt){
  54808. this.edges.forEach(edge=>{edge.dispatchEvent('addHoverEvent'); });
  54809. }else {
  54810. this.failBuilded = true;
  54811. }
  54812. }
  54813. updateDatasetBelong(changeIndex){//更新所属数据集
  54814. if(Potree.settings.editType == "merge"){//无地图
  54815. /* this.dataset_points = this.points.map((e,i)=>{
  54816. return Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.points_datasets[i], position:e.clone()})
  54817. }) */
  54818. this.dataset_points[changeIndex] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.points_datasets[changeIndex], position:this.points[changeIndex].clone()});
  54819. return
  54820. }
  54821. let old = this.datasetId;
  54822. let maxCount = {id:null,count:0};
  54823. let datasets = {};
  54824. this.points_datasets.forEach(e=>{
  54825. if(e == void 0)return
  54826. if(datasets[e]){
  54827. datasets[e] ++;
  54828. }else {
  54829. datasets[e] = 1;
  54830. }
  54831. });
  54832. for(let i in datasets) {
  54833. if(datasets[i]>maxCount.count){
  54834. maxCount = {id:i, count:datasets[i]};
  54835. }
  54836. }
  54837. this.datasetId = maxCount.count > 0 ? maxCount.id : null;
  54838. //if(this.datasetId != old){
  54839. //this.dispatchEvent({type:'changeDatasetId'})
  54840. if(this.datasetId == void 0){
  54841. this.dataset_points = null; //可能为空或[null,null...]
  54842. }else {
  54843. this.dataset_points = this.points.map(e=>{
  54844. return Potree.Utils.datasetPosTransform({toDataset:true,datasetId:this.datasetId, position:e.clone()})
  54845. });
  54846. }
  54847. //}
  54848. }
  54849. transformByPointcloud(){//每次移动点云 or 加载测量线时要获取一下当前position //有地图时
  54850. if(this.datasetId == void 0)return
  54851. this.points = this.dataset_points.map(e=>{
  54852. return Potree.Utils.datasetPosTransform({fromDataset:true, datasetId:this.datasetId, position:e.clone()})
  54853. });
  54854. this.getPoint2dInfo(this.points);
  54855. this.update({ifUpdateMarkers:true});
  54856. this.setSelected(false);//隐藏edgelabel
  54857. }
  54858. update(options={}) {
  54859. super.update(options);
  54860. if(this.showCoordinates && this.points.length>0){
  54861. let position = this.points[0];
  54862. this.markers[0].position.copy(position);
  54863. { // coordinate labels
  54864. let coordinateLabel = this.coordinateLabels[0];
  54865. let lonlat = viewer.transform.lonlatToLocal.inverse(position.toArray());
  54866. let EPSG4550 = viewer.transform.lonlatTo4550.forward(lonlat);
  54867. let pos = [
  54868. position.toArray(),
  54869. lonlat,
  54870. EPSG4550
  54871. ];
  54872. //let msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / ");
  54873. let msg = pos.map(a=>
  54874. a.map(p => Utils.addCommas(p.toFixed(10))).join(", ")
  54875. ).join("<br>");
  54876. coordinateLabel.setText(msg);
  54877. coordinateLabel.setPos(position);
  54878. coordinateLabel.setVisible(true);//this.showCoordinates;
  54879. }
  54880. return
  54881. }
  54882. let setEdgeLabel = (label,p1,p2,distance)=>{//设置label位置和字
  54883. this.setEdgeLabelPos(label,p1,p2);
  54884. distance = distance == void 0 ? p1.distanceTo(p2) : distance;
  54885. //var text = viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision, this.unitSystem, 1 , true)//distance要传0.1 这个factor
  54886. var text = viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision , this.unitSystem, 0.01 , true );//distance要传0.1 这个factor
  54887. label.setText(text);
  54888. return distance
  54889. };
  54890. /* let setEdgeLabel = (label,p1,p2,distance)=>{//设置label位置和字
  54891. this.setEdgeLabelPos(label,p1,p2)
  54892. distance = distance == void 0 ? p1.distanceTo(p2) : distance;
  54893. var text = this.labelText || viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision , this.unitSystem, 0.001 , true, true)//distance要传0.1 这个factor
  54894. label.setText(text)
  54895. } */
  54896. let lastIndex = this.points.length - 1;
  54897. for (let index = 0; index <= lastIndex; index++) {
  54898. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  54899. let previousIndex = (index === 0) ? lastIndex : index - 1;
  54900. //if(!this.closed && nextIndex == 0 )break; //add
  54901. let point = this.points[index];
  54902. let nextPoint = this.points[nextIndex];
  54903. let previousPoint = this.points[previousIndex];
  54904. if(this.showDistances){ // edge labels
  54905. let edgeLabel = this.edgeLabels[index];
  54906. let distance = point.distanceTo(nextPoint);
  54907. edgeLabel.shouldVisi = (index < lastIndex || this.isRect || this.closed && !this.isNew ) && distance>0;
  54908. /* this.closed || */edgeLabel.setVisible(edgeLabel.shouldVisi);
  54909. if(edgeLabel.shouldVisi){
  54910. edgeLabel.lineDir = new Vector3().subVectors(point,nextPoint).normalize(); //[point,nextPoint]
  54911. setEdgeLabel(edgeLabel,point,nextPoint,distance);
  54912. }
  54913. }
  54914. }
  54915. if(Potree.config.measure.mulLabelHideFaraway ){
  54916. this.measureType == 'MulDistance' && this.clearEdgeLabelVisi();
  54917. }
  54918. if(this.measureType == 'Distance' && this.points.length>1){//设置水平垂直辅助线
  54919. var pTop, pBtm;
  54920. if(this.points[0].z > this.points[1].z ){
  54921. pTop = this.points[0];
  54922. pBtm = this.points[1];
  54923. }else {
  54924. pTop = this.points[1];
  54925. pBtm = this.points[0];
  54926. }
  54927. let projectPos = new Vector3(pTop.x, pTop.y, pBtm.z);//两条guideline的交点
  54928. {//倾斜角度太小的时候不显示
  54929. let tan = pTop.distanceTo(projectPos) / pBtm.distanceTo(projectPos);
  54930. let angle = Math.atan(tan);
  54931. this.shouldShowHorVerGuide = angle > guideShowMinAngle.min && angle < guideShowMinAngle.max;
  54932. }
  54933. LineDraw.updateLine(this.verGuideEdge, [pTop, projectPos]);
  54934. LineDraw.updateLine(this.horGuideEdge, [pBtm, projectPos]);
  54935. setEdgeLabel(this.verEdgeLabel,pTop,projectPos);
  54936. setEdgeLabel(this.horEdgeLabel,pBtm,projectPos);
  54937. this.verGuideEdge.visible = this.horGuideEdge.visible = this.shouldShowHorVerGuide;
  54938. this.verEdgeLabel.visible = this.horEdgeLabel.visible = this.shouldShowHorVerGuide;
  54939. }
  54940. if(this.showArea && this.point2dInfo){ // update area
  54941. /* if(this.points.length>2){
  54942. this.area = {value:0};
  54943. this.areaLabel.setVisible(false)
  54944. }else{ */
  54945. let area = Math.abs(math.getArea(this.point2dInfo.points2d));//this.getArea();
  54946. let msg = viewer.unitConvert.convert(area, 'area', Potree.settings.precision, this.unitSystem/* , 0.1 */ );
  54947. this.area = {value:area, string:msg};
  54948. this.areaLabel.setPos(this.center);
  54949. this.areaLabel.setText(msg);
  54950. this.areaLabel.setVisible(true);
  54951. //}
  54952. }
  54953. if(this.showTotalDis && this.points.length > 2){
  54954. //this.ifShowTotalDis()
  54955. let dis = this.getTotalDistance();
  54956. let msg = viewer.unitConvert.convert(dis, 'distance', Potree.settings.precision , this.unitSystem, 0.01 , true );
  54957. this.center = this.getCenter();
  54958. this.totalDisLabel.setPos(this.center);
  54959. this.totalDisLabel.setText(msg);
  54960. this.totalDisLabel.setVisible(true);
  54961. }
  54962. };
  54963. ifShowTotalDis(){
  54964. if(this.measureType == 'MulDistance' ){
  54965. let show = this.points.length > 2;
  54966. if(show){
  54967. }
  54968. this.showTotalDis = show;
  54969. }
  54970. /* 连续测量:
  54971. 1. ≥2次测量,单个距离<15cm时,居中显示总长
  54972. 2. 若连续测量的线段中,大于等于1段超出15cm,所有线段均显示长度
  54973. -------------------
  54974. 所有连续测量共用逻辑:
  54975. 选中或者鼠标悬浮时,显示所有单个线段的长度(第1点不同,选中或悬浮也显示总长)
  54976. 离开时,均显示总长 */
  54977. }
  54978. clearEdgeLabelVisi(){//修改点位置后清空,下次render时会自动getEdgeLabelVisi
  54979. let lastIndex = this.points.length - 1;
  54980. for (let index = 0; index <= lastIndex; index++) {
  54981. if(!this.closed && index == lastIndex)continue
  54982. let edgeLabel = this.edgeLabels[index];
  54983. edgeLabel.visiMap.clear();
  54984. }
  54985. }
  54986. getEdgeLabelVisi(viewport){//获取多折线的edgelabel在不同视图里的可见性。要保证任何时候label能出现的线最小二维长度一致
  54987. let camera = viewport.camera;
  54988. let lastIndex = this.points.length - 1;
  54989. /* let pos2ds = this.points.map(point=> point.clone().project(camera) ) //即使只是旋转也会变动,尤其是转到屏幕外后变为显示。所以不用这种
  54990. let minDis = 0.01; */
  54991. let minDis = 0.02 , minAngleRatio = 0.07, minAngle;
  54992. let vecs;
  54993. let forceShow;
  54994. if(camera.type == 'OrthographicCamera'){
  54995. minDis *= Math.pow(camera.top / camera.zoom, 2);
  54996. //console.log(minDis)
  54997. }else {
  54998. if(Potree.settings.displayMode == 'showPanos' && viewer.images360.zoomLevel == Potree.settings.zoom.max){
  54999. forceShow = true; //当zoom到最大时强制显示,避免有的线太短永远显示不出长度
  55000. }else {
  55001. vecs = this.points.map(point=> new Vector3().subVectors(point, camera.position).normalize());
  55002. minAngleRatio /= viewport.resolution.y / 1000 / textSizeRatio; //角度占fov最小比率
  55003. minAngle = minAngleRatio * MathUtils.degToRad(camera.fov);
  55004. }
  55005. }
  55006. for (let index = 0; index <= lastIndex; index++) {
  55007. if(!this.closed && index == lastIndex)continue
  55008. let edgeLabel = this.edgeLabels[index];
  55009. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  55010. let previousIndex = (index === 0) ? lastIndex : index - 1;
  55011. let point = this.points[index];
  55012. let nextPoint = this.points[nextIndex];
  55013. /* let point2d = pos2ds[index];
  55014. let nextPoint2d = pos2ds[nextIndex];
  55015. let dis2d = point2d.distanceToSquared(nextPoint2d)
  55016. let v = dis2d > minDis //可见长度太小,为避免拥挤,不显示
  55017. edgeLabel.visiMap.set(camera, v) */
  55018. let v;
  55019. if(forceShow){
  55020. v = true;
  55021. }else if(camera.type == 'OrthographicCamera'){
  55022. let vec = new Vector3().subVectors(point,nextPoint);
  55023. let projVec = vec.projectOnPlane(viewport.view.direction);
  55024. v = projVec.lengthSq() > minDis;
  55025. }else {
  55026. let vec0 = vecs[index];
  55027. let vec1 = vecs[nextIndex];
  55028. v = Math.acos(vec0.dot(vec1)) > minAngle; //角度过小代表可见长度太小,为避免拥挤,不显示
  55029. }
  55030. edgeLabel.visiMap.set(camera, v);
  55031. }
  55032. }
  55033. setEdgeLabelPos(label,p1,p2){ //调整label的位置,使倾斜后看起来在线的中心,而不要挡住端点
  55034. let center = new Vector3().addVectors(p1,p2).multiplyScalar(0.5);
  55035. return label.setPos(center)
  55036. if(label.lineDir && label.lineDir.length() > 0){
  55037. if(viewer.mainViewport.camera.type == 'OrthographicCamera'){
  55038. label.setPos(center);
  55039. }else {
  55040. //根据视线和线的夹角(后又加入相机和两个端点距离差)来决定标签偏移位置。+
  55041. let eyePos = viewer.mainViewport.camera.position;
  55042. let dir = viewer.mainViewport.view.direction; //new THREE.Vector3().subVectors(center,eyePos).normalize()
  55043. /*let centerDir = new THREE.Vector3().subVectors(center,eyePos).normalize()
  55044. if(centerDir.dot(dir)<0){//中点在相机后方,就不设置
  55045. label.setPos(center)
  55046. return
  55047. } */
  55048. let cos = dir.dot(label.lineDir);
  55049. let nearPoint = cos > 0 ? p2 : p1; //近端点。
  55050. let far = cos > 0 ? p1 : p2; //远端点。
  55051. let nearPointDir = new Vector3().subVectors(nearPoint,eyePos);//.normalize()
  55052. //使label在中点和近端点中变化, 近端点可能到了相机后方,需要投影到相机所在平面上
  55053. if(nearPointDir.dot(dir)<0){//近端点到了相机后方,前移。
  55054. //let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true ); //暂且只看水平fov
  55055. //if(nearPointDir.dot(dir)<Math.cos(hfov/2)){//近端点在镜头外,前移。 --但是这个就得把点转化成在镜头边缘而非左右两边(camDirPlane上)
  55056. let ray = new Raycaster();
  55057. ray.set(nearPoint, cos>0?label.lineDir:label.lineDir.clone().negate());
  55058. let camDirPlane = new Plane().setFromNormalAndCoplanarPoint(dir, eyePos);
  55059. nearPoint = ray.ray.intersectPlane(camDirPlane, new Vector3());
  55060. if(!nearPoint){//线是垂直的,视线是水平的时候
  55061. return label.setPos(center)
  55062. }
  55063. }
  55064. //防止离远了之后也偏移很多,但远了之后相机到端点vec和到中点的vec的夹角接近,不需要怎么偏移的。
  55065. let dis1 = nearPoint.distanceToSquared(eyePos);
  55066. let dis2 = far.distanceToSquared(eyePos);
  55067. let diff = Math.abs(dis1/dis2);
  55068. diff<1 && (diff = 1/diff);
  55069. diff = math.linearClamp(diff,0, 30, 0,1 );
  55070. let efficiency = 0.7; // 0-1 数值越高,r越容易接近1或-1,label越容易在倾斜后靠近近端点。
  55071. //let r = 0.5*efficiency*cos + 0.5
  55072. let r = 0.5*efficiency*diff*cos + 0.5;
  55073. r = MathUtils.clamp(r,0.1,0.9);
  55074. //视线越接近线的方向,标签应该越往近端点偏移,防止看起来几乎在远端。
  55075. if(cos > 0){
  55076. center = p1.clone().multiplyScalar(1-r).add(nearPoint.clone().multiplyScalar(r)); //label在线上滑动,使尽量保持在视觉中心
  55077. }else {
  55078. center = nearPoint.clone().multiplyScalar(1-r).add(p2.clone().multiplyScalar(r)); //label在线上滑动,使尽量保持在视觉中心
  55079. }
  55080. label.setPos(center);
  55081. }
  55082. //归零
  55083. //this.orient2dInfo = null
  55084. //this.markers.forEach(e=>e.needsUpdate=true)
  55085. }else {
  55086. label.setPos(center);
  55087. }
  55088. }
  55089. addMarker (o={}) {
  55090. let marker = new Sprite$2({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo, name:"measure_point"} );
  55091. Potree.Utils.setObjectLayers(marker, 'measure' );
  55092. marker.pickOrder = marker.renderOrder = 3;
  55093. marker.markerSelectStates = {};
  55094. marker.addEventListener('startDragging',(e)=>{
  55095. /* if(e.drag.dragViewport.name == 'MainView') */viewer.inputHandler.dispatchEvent( {type: 'measuring',v:true, cause:'startDragging', situation:'dragging', object:this});
  55096. });
  55097. marker.addEventListener('drop',(e)=>{
  55098. viewer.inputHandler.dispatchEvent({type: 'measuring', v:false, cause:'stopDragging', situation:'dragging', object:this} );
  55099. if(Potree.settings.adsorption){
  55100. this.isNew || viewer.viewports.forEach((viewport)=>{
  55101. this.getPointsPos2d(viewport, true );//forceUpdate
  55102. });
  55103. }
  55104. });
  55105. //marker.measure = this
  55106. let edge;
  55107. { // edges
  55108. edge = LineDraw.createFatLine( [ ],{mat:this.getLineMat('edgeDefault')} );
  55109. edge.pickOrder = 0;
  55110. Potree.Utils.setObjectLayers(edge, 'measure' );
  55111. let addHoverEvent = ()=>{ //当非isNew时才添加事件
  55112. let mouseover = (e) => {this.setSelected(true, 'edge');};
  55113. let mouseleave = (e) => {this.setSelected(false, 'edge');};
  55114. edge.addEventListener('mouseover', mouseover);
  55115. edge.addEventListener('mouseleave', mouseleave);
  55116. edge.removeEventListener('addHoverEvent', addHoverEvent);
  55117. edge.addEventListener('click',()=>{
  55118. this.isNew || viewer.focusOnObject(this, 'measure');
  55119. });
  55120. };
  55121. edge.addEventListener('addHoverEvent', addHoverEvent);
  55122. }
  55123. super.addMarker({point:o.point, marker:marker, edge});
  55124. if(this.showEdges){ // edge labels
  55125. const edgeLabel = this.createEdgeLabel('edgeLabel', !this.closed);
  55126. this.edgeLabels.push(edgeLabel);
  55127. }
  55128. if(this.showCoordinates){ // coordinate labels
  55129. let coordinateLabel = new Label({
  55130. className:'measure_pointPos',
  55131. camera: viewer.scene.getActiveCamera()
  55132. });
  55133. coordinateLabel.setVisible(false);
  55134. this.coordinateLabels.push(coordinateLabel);
  55135. }
  55136. let event = {
  55137. type: 'marker_added',
  55138. measurement: this,
  55139. marker: marker
  55140. };
  55141. this.dispatchEvent(event);
  55142. //this.setMarker(this.points.length - 1, point);
  55143. this.update();//更新一下倒数第二条线
  55144. return marker;//add
  55145. };
  55146. editStateChange(state){ //主要针对edgeLabels显示切换,编辑时显示
  55147. super.editStateChange(state);
  55148. if(!state){
  55149. this.editStateTimer = setTimeout(()=>{
  55150. if(!this.isEditing){
  55151. this.dispatchEvent({type:'editStateChange',state:false});
  55152. this.setEdgesDisplay(false);
  55153. this.areaPlane && Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', true);
  55154. this.areaLabel && Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', true);
  55155. }
  55156. },100);
  55157. }else {
  55158. if(!this.isEditing){
  55159. this.dispatchEvent({type:'editStateChange',state:true});
  55160. this.setEdgesDisplay(true);
  55161. clearTimeout(this.editStateTimer);
  55162. }
  55163. }
  55164. this.isEditing = state;
  55165. }
  55166. setMarkerSelected(marker, state, hoverObject){
  55167. //console.warn(marker.id , state, hoverObject)
  55168. marker.markerSelectStates[hoverObject] = state;
  55169. let absoluteState = false;
  55170. for(var i in marker.markerSelectStates){
  55171. if(marker.markerSelectStates[i] == 'hover'){
  55172. absoluteState = true; break;
  55173. }
  55174. }
  55175. if(absoluteState){
  55176. marker.material = this.getMarkerMaterial('select');
  55177. }else {
  55178. marker.material = this.getMarkerMaterial('default');
  55179. }
  55180. marker.selected = absoluteState;
  55181. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  55182. viewer.dispatchEvent('content_changed');
  55183. }
  55184. setEdgesDisplay(state, ignoreGuideLine){
  55185. this.closed && this.edgeLabels.forEach(e=>e.setVisible(!!(state && e.shouldVisi)) );
  55186. if(!ignoreGuideLine && this.measureType == 'Distance'){
  55187. this.horEdgeLabel.visible = this.verEdgeLabel.visible = this.horGuideEdge.visible = this.verGuideEdge.visible = !!(state && this.shouldShowHorVerGuide);
  55188. }
  55189. }
  55190. setSelected(state, hoverObject){//add
  55191. //console.log('setSelected',state, hoverObject)
  55192. hoverObject && (this.selectStates[hoverObject] = state);
  55193. let absoluteState = false;
  55194. for(var i in this.selectStates){
  55195. if(this.selectStates[i]){
  55196. absoluteState = true; break;
  55197. }
  55198. }
  55199. if(absoluteState){
  55200. this.markers.forEach(e=>this.setMarkerSelected(e, 'hover', 'selectAll' ) );
  55201. this.edges.forEach(e=>e.material = this.getLineMat('edgeSelect') );
  55202. this.areaPlane && (this.areaPlane.material = planeMats.selected);
  55203. //this.areaLabel && this.areaLabel.elem.addClass('highLight')
  55204. //this.closed || this.edgeLabels.forEach(e=>e.elem.addClass('highLight') )
  55205. this.setEdgesDisplay(true, hoverObject=="screenshot");
  55206. this.areaLabel && setLabelHightState(this.areaLabel, true);
  55207. this.closed || this.edgeLabels.forEach(e=>setLabelHightState(e, true) );
  55208. }else {
  55209. this.markers.forEach(e=>this.setMarkerSelected(e, 'unhover', 'selectAll' ));
  55210. this.edges.forEach(e=>e.material = this.getLineMat('edgeDefault') );
  55211. this.areaPlane && (this.areaPlane.material = planeMats.default);
  55212. this.setEdgesDisplay(false, hoverObject=="screenshot");
  55213. //this.areaLabel && this.areaLabel.elem.removeClass('highLight')
  55214. //this.closed || this.edgeLabels.forEach(e=>e.elem.removeClass('highLight') )
  55215. this.areaLabel && setLabelHightState(this.areaLabel, false);
  55216. this.closed || this.edgeLabels.forEach(e=>setLabelHightState(e, false) );
  55217. }
  55218. this.selected = absoluteState;
  55219. if(hoverObject != 'byList'){
  55220. //this.bus && this.bus.emit('highlight', this.selected)
  55221. this.dispatchEvent({type:'highlight',state:this.selected});//列表高亮
  55222. }
  55223. viewer.dispatchEvent('content_changed');
  55224. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  55225. }
  55226. removeMarker(index ){
  55227. super.removeMarker(index);
  55228. this.points_datasets.splice(index, 1);
  55229. this.dataset_points && this.dataset_points.splice(index, 1);
  55230. this.coordinateLabels.splice(index, 1);
  55231. let edgeIndex = index;//(index === 0) ? 0 : (index - 1);
  55232. if(this.edgeLabels[edgeIndex]){
  55233. this.edgeLabels[edgeIndex].dispose();
  55234. this.edgeLabels.splice(edgeIndex, 1);
  55235. }
  55236. this.update();
  55237. this.dispatchEvent({type: 'marker_removed', measurement: this});
  55238. }
  55239. setPosition(index, position) {
  55240. super.setPosition(index, position);
  55241. let event = {
  55242. type: 'marker_moved',
  55243. measure: this,
  55244. index: index,
  55245. position: position.clone()
  55246. };
  55247. this.dispatchEvent(event);
  55248. }
  55249. dispose(){//add
  55250. var labels = this.edgeLabels.concat(this.coordinateLabels);
  55251. this.areaLabel && labels.push(this.areaLabel);
  55252. labels.forEach(e=>e.dispatchEvent({type:'dispose'}));
  55253. super.dispose();
  55254. }
  55255. getTotalDistance () {
  55256. if (this.points.length === 0) {
  55257. return 0;
  55258. }
  55259. let distance = 0;
  55260. for (let i = 1; i < this.points.length; i++) {
  55261. let prev = this.points[i - 1];
  55262. let curr = this.points[i];
  55263. let d = prev.distanceTo(curr);
  55264. distance += d;
  55265. }
  55266. if (this.closed && this.points.length > 1) {
  55267. let first = this.points[0];
  55268. let last = this.points[this.points.length - 1];
  55269. let d = last.distanceTo(first);
  55270. distance += d;
  55271. }
  55272. return distance;
  55273. }
  55274. getAngleBetweenLines (cornerPoint, point1, point2) {
  55275. let v1 = new Vector3().subVectors(point1, cornerPoint);
  55276. let v2 = new Vector3().subVectors(point2, cornerPoint);
  55277. // avoid the error printed by threejs if denominator is 0
  55278. const denominator = Math.sqrt( v1.lengthSq() * v2.lengthSq() );
  55279. if(denominator === 0){
  55280. return 0;
  55281. }else {
  55282. return v1.angleTo(v2);
  55283. }
  55284. };
  55285. getAngle (index) {
  55286. if (this.points.length < 3 || index >= this.points.length) {
  55287. return 0;
  55288. }
  55289. let previous = (index === 0) ? this.points[this.points.length - 1] : this.points[index - 1];
  55290. let point = this.points[index];
  55291. let next = this.points[(index + 1) % (this.points.length)];
  55292. return this.getAngleBetweenLines(point, previous, next);
  55293. }
  55294. getCenter(/* update */){
  55295. if(this.closed){
  55296. return this.center.clone()
  55297. }else {
  55298. let center = this.points.reduce(function(total, currentValue ){
  55299. return total.add(currentValue)
  55300. }, new Vector3 );
  55301. center.multiplyScalar(1/this.points.length);
  55302. return center //求不出重心呜呜
  55303. }
  55304. }
  55305. // updateAzimuth(){
  55306. // // if(this.points.length !== 2){
  55307. // // return;
  55308. // // }
  55309. // // const azimuth = this.azimuth;
  55310. // // const [p0, p1] = this.points;
  55311. // // const r = p0.distanceTo(p1);
  55312. // }
  55313. createGuideLine(){//add 辅助线
  55314. var guideLine = LineDraw.createFatLine([ ],{mat:this.getLineMat('guide')} );
  55315. guideLine.visible = false;
  55316. this.guideLine = guideLine;
  55317. this.add(guideLine);
  55318. }
  55319. createHorVerGuideLine(){//创建水平与垂直辅助线,仅距离测量有。
  55320. var verGuideEdge = LineDraw.createFatLine([ ],{mat:this.getLineMat('guide')} );
  55321. verGuideEdge.visible = false;
  55322. this.verGuideEdge = verGuideEdge;
  55323. verGuideEdge.name = 'verGuideEdge';
  55324. var horGuideEdge = LineDraw.createFatLine([ ],{mat:this.getLineMat('guide')} );
  55325. horGuideEdge.visible = false;
  55326. horGuideEdge.name = 'horGuideEdge';
  55327. this.horGuideEdge = horGuideEdge;
  55328. this.add(this.verGuideEdge);
  55329. this.add(this.horGuideEdge);
  55330. //label:
  55331. this.verEdgeLabel = this.createEdgeLabel('verGuideEdge');
  55332. this.horEdgeLabel = this.createEdgeLabel('horGuideEdge');
  55333. }
  55334. createEdgeLabel(name, hasHoverEvent){
  55335. let inf = {
  55336. sizeInfo: labelSizeInfo, name:name||'edgeLabel',
  55337. };
  55338. if(name && name.includes('Guide')){
  55339. inf.fontsize = 12;
  55340. }
  55341. const edgeLabel = new TextSprite$2(
  55342. $.extend({}, hasHoverEvent ? mainLabelProp : subLabelProp, inf)
  55343. );
  55344. if(hasHoverEvent){
  55345. edgeLabel.addEventListener('mouseover',()=>{
  55346. this.setSelected(true, 'edgeLabel');
  55347. });
  55348. edgeLabel.addEventListener('mouseleave',()=>{
  55349. this.setSelected(false, 'edgeLabel');
  55350. });
  55351. edgeLabel.addEventListener('click',()=>{
  55352. this.isNew || viewer.focusOnObject(this, 'measure');
  55353. });
  55354. }
  55355. edgeLabel.visible = false;
  55356. edgeLabel.measure = this;
  55357. edgeLabel.sprite.material.depthTestWhenPick = true;
  55358. Potree.Utils.setObjectLayers(edgeLabel, 'measure' );
  55359. this.add(edgeLabel);
  55360. if(this.measureType == 'MulDistance'){
  55361. edgeLabel.visiMap = new Map();
  55362. }
  55363. return edgeLabel
  55364. }
  55365. createAreaLabel(){
  55366. const areaLabel = this.createCenterLabel('areaLabel');
  55367. return areaLabel;
  55368. }
  55369. createTotalDisLabel(){
  55370. const totalDisLabel = this.createCenterLabel('totalDisLabel');
  55371. return totalDisLabel;
  55372. }
  55373. createCenterLabel(name){
  55374. const centerLabel = new TextSprite$2(
  55375. $.extend({},mainLabelProp,{sizeInfo: labelSizeInfo, name, disToLine:0, fontsize:16*textSizeRatio} )
  55376. );
  55377. centerLabel.addEventListener('mouseover',()=>{
  55378. this.setSelected(true, 'centerLabel');
  55379. });
  55380. centerLabel.addEventListener('mouseleave',()=>{
  55381. this.setSelected(false, 'centerLabel');
  55382. });
  55383. centerLabel.addEventListener('click',()=>{
  55384. this.isNew || viewer.focusOnObject(this, 'measure');
  55385. });
  55386. Potree.Utils.setObjectLayers(centerLabel, 'measure' );
  55387. centerLabel.setVisible(false);
  55388. return centerLabel;
  55389. }
  55390. getMarkerMaterial(type) {
  55391. if(!markerMats){
  55392. markerMats = {
  55393. default: new DepthBasicMaterial($.extend({},lineDepthInfo,{
  55394. transparent: !0,
  55395. opacity: 1,
  55396. map: texLoader$2.load(Potree.resourcePath+'/textures/pic_point_s32.png' ),
  55397. useDepth:true ,
  55398. mapScale: markerMapShrink
  55399. })),
  55400. select: new MeshBasicMaterial({
  55401. transparent: !0,
  55402. opacity: 1,
  55403. depthTest:false,
  55404. map: texLoader$2.load(Potree.resourcePath+'/textures/pic_point32.png'/* , null, null, { antialias: false } */),
  55405. }),
  55406. };
  55407. Measure$1.markerMats = markerMats;
  55408. markerMats.select.map.repeat.set(1/markerMapShrink,1/markerMapShrink);
  55409. markerMats.select.map.offset.set((markerMapShrink-1)/2/markerMapShrink, (markerMapShrink-1)/2/markerMapShrink);
  55410. //markerMats.select.map.offset.set( -1.1 , -1.1 )
  55411. }
  55412. return markerMats[type]
  55413. }
  55414. getLineMat(type) {
  55415. if(!Measure$1.lineMats){
  55416. Measure$1.lineMats = {
  55417. edgeDefault: LineDraw.createFatLineMat($.extend({},lineDepthInfo,{
  55418. color: config$1.measure.default.color,
  55419. lineWidth: config$1.measure.lineWidth,
  55420. useDepth :true,
  55421. dashWithDepth :true, // 只在被遮住的部分显示虚线,因为实线容易挡住label
  55422. dashed :true,
  55423. dashSize : 0.04,
  55424. gapSize: 0.04,
  55425. transparent: true,
  55426. opacity: config$1.measure.default.opacity,
  55427. depthTestWhenPick:true,
  55428. })),
  55429. edgeSelect: LineDraw.createFatLineMat($.extend({},lineDepthInfo,{
  55430. color: config$1.measure.highlight.color,//'#f0ff00',
  55431. dashSize: 0.5,
  55432. gapSize: 0.2,
  55433. lineWidth: config$1.measure.lineWidth ,
  55434. transparent: true,
  55435. opacity: config$1.measure.highlight.opacity
  55436. })),
  55437. guide: LineDraw.createFatLineMat($.extend({},lineDepthInfo,{
  55438. color:config$1.measure.guide.color,
  55439. dashSize: 0.1,
  55440. gapSize: 0.02,
  55441. dashed: true,
  55442. lineWidth: config$1.measure.lineWidth/2
  55443. }))
  55444. };
  55445. }
  55446. return Measure$1.lineMats[type]
  55447. }
  55448. createAreaPlane(){
  55449. planeMats || (planeMats = {
  55450. default: new DepthBasicMaterial( $.extend({},lineDepthInfo,{
  55451. color:color,
  55452. side:DoubleSide,
  55453. opacity:0.2,
  55454. transparent:true,
  55455. useDepth:true
  55456. })),
  55457. selected: new MeshBasicMaterial({
  55458. color: color ,
  55459. side:DoubleSide,
  55460. opacity:0.3,
  55461. transparent:true,
  55462. })
  55463. },Measure$1.planeMats = planeMats);
  55464. return super.createAreaPlane(planeMats.default)
  55465. }
  55466. raycast (raycaster, intersects) {
  55467. for (let i = 0; i < this.points.length; i++) {
  55468. let marker = this.markers[i];
  55469. marker.raycast(raycaster, intersects);
  55470. }
  55471. // recalculate distances because they are not necessarely correct
  55472. // for scaled objects.
  55473. // see https://github.com/mrdoob/three.js/issues/5827
  55474. // TODO: remove this once the bug has been fixed
  55475. for (let i = 0; i < intersects.length; i++) {
  55476. let I = intersects[i];
  55477. I.distance = raycaster.ray.origin.distanceTo(I.point);
  55478. }
  55479. intersects.sort(function (a, b) { return a.distance - b.distance; });
  55480. };
  55481. getPointsPos2d(viewport, update){//获取屏幕上的二维坐标
  55482. let ps = this.pointsPos2d.get(viewport);
  55483. if(update || !ps){
  55484. let points = this.points.map(e=>{
  55485. let p = Potree.Utils.getPos2d(e, viewport, viewer.renderArea );
  55486. p.pos3d = e.clone(), p.object = this;
  55487. return p
  55488. });
  55489. this.pointsPos2d.set(viewport, points);
  55490. console.log('updatePointsPos2d',this.uuid,viewport.name);
  55491. }
  55492. return this.pointsPos2d.get(viewport)
  55493. }
  55494. transformData(prop){
  55495. if(prop.measureType == 'Point'){
  55496. prop.showCoordinates = true,
  55497. prop.closed = true,
  55498. prop.maxMarkers = 1,
  55499. prop.minMarkers = 1;
  55500. }else if(prop.measureType == 'Distance'){
  55501. prop.showDistances = true,
  55502. prop.showEdges = true,
  55503. prop.maxMarkers = 2,
  55504. prop.minMarkers = 2;
  55505. }else if(prop.measureType == 'MulDistance'){//new
  55506. prop.showDistances = true,
  55507. prop.showEdges = true,
  55508. prop.minMarkers = 2;
  55509. }else if(prop.measureType == 'Ver MulDistance'){
  55510. prop.showDistances = true,
  55511. prop.atPlane = true,
  55512. prop.showEdges = true,
  55513. prop.minMarkers = 2;
  55514. prop.faceDirection = "vertical";
  55515. prop.unableDragAtMap = true;
  55516. }else if(prop.measureType == 'Hor MulDistance'){
  55517. prop.showDistances = true,
  55518. prop.atPlane = true,
  55519. prop.showEdges = true,
  55520. prop.minMarkers = 2;
  55521. prop.faceDirection = "horizontal";
  55522. }else if(prop.measureType == 'Ver Distance'){
  55523. prop.showDistances = true,
  55524. prop.showEdges = true,
  55525. prop.maxMarkers = 2,
  55526. prop.minMarkers = 2,
  55527. prop.faceDirection = "vertical";
  55528. prop.unableDragAtMap = true;
  55529. }else if(prop.measureType == 'Hor Distance'){
  55530. prop.showDistances = true,
  55531. prop.showEdges = true,
  55532. prop.maxMarkers = 2,
  55533. prop.minMarkers = 2,
  55534. prop.faceDirection = "horizontal";
  55535. }else if(prop.measureType == 'Area'){
  55536. prop.showDistances = true,
  55537. prop.atPlane = true,
  55538. prop.showEdges = true,
  55539. prop.closed = true,
  55540. prop.minMarkers = 3;
  55541. }else if(prop.measureType == 'Hor Area'){
  55542. prop.showDistances = true,
  55543. prop.atPlane = true,
  55544. prop.showEdges = true,
  55545. prop.closed = true,
  55546. prop.minMarkers = 3;
  55547. prop.faceDirection = "horizontal";
  55548. }else if(prop.measureType == 'Ver Area'){
  55549. prop.showDistances = true,
  55550. prop.atPlane = true,
  55551. prop.showEdges = true,
  55552. prop.closed = true,
  55553. prop.minMarkers = 3;
  55554. prop.faceDirection = "vertical";
  55555. prop.unableDragAtMap = true;
  55556. }else if(prop.measureType == 'Rect Area'){
  55557. prop.showDistances = true,
  55558. prop.atPlane = true,
  55559. prop.showEdges = true,
  55560. prop.closed = true,
  55561. prop.minMarkers = 4;
  55562. prop.maxMarkers = 4;
  55563. }else if(prop.measureType == 'Hor Rect Area'){
  55564. prop.showDistances = true,
  55565. prop.atPlane = true,
  55566. prop.showEdges = true,
  55567. prop.closed = true,
  55568. prop.minMarkers = 4;
  55569. prop.maxMarkers = 4;
  55570. prop.isRect = true;
  55571. prop.faceDirection = "horizontal";
  55572. }else if(prop.measureType == 'Ver Rect Area'){
  55573. prop.showDistances = true,
  55574. prop.atPlane = true,
  55575. prop.showEdges = true,
  55576. prop.closed = true,
  55577. prop.minMarkers = 4;
  55578. prop.maxMarkers = 4;
  55579. prop.isRect = true;
  55580. prop.faceDirection = "vertical";
  55581. prop.unableDragAtMap = true;
  55582. }
  55583. if(prop.atPlane && prop.closed){ //atPlane在同一平面上
  55584. prop.showArea = true;
  55585. }
  55586. super.transformData(prop);
  55587. }
  55588. setUnitSystem(unitSystem){
  55589. //console.log(this.name +':' +this.unitSystem)
  55590. if(unitSystem != this.unitSystem){
  55591. if(unitSystem == "metric"){
  55592. }else if(unitSystem == 'imperial'){
  55593. }
  55594. this.unitSystem = unitSystem;
  55595. this.update();
  55596. }
  55597. }
  55598. reDraw(restMarkerCount=0){//重新开始画
  55599. super.reDraw(restMarkerCount);
  55600. if(this.measureType == 'Distance'){
  55601. this.shouldShowHorVerGuide = false;
  55602. this.setEdgesDisplay(false);
  55603. }
  55604. if(this.showArea){
  55605. this.area = {value:0};
  55606. this.areaLabel && this.areaLabel.setVisible(false);
  55607. }
  55608. if(this.showTotalDis){
  55609. this.totalDisLabel && this.totalDisLabel.setVisible(false);
  55610. }
  55611. viewer.inputHandler.dispatchEvent( {type:'measuring', v:true, cause:'reDraw',object:this, situation:'dragging'} );
  55612. }
  55613. }
  55614. function setLabelHightState(label, state){
  55615. if(state){
  55616. let color = new Color(Potree.config.measure.highlight.color);
  55617. //label.sprite.material.opacity = config.measure.highlight.opacity
  55618. //label.setBackgroundColor({r:255*color.r, g:255*color.g, b:255*color.b, a:config.measure.highlight.opacity})
  55619. label.sprite.material.useDepth = false;
  55620. //label.textColor = {r: this.color.r*255, g: this.color.g*255, b: this.color.b*255, a: 1}
  55621. }else {
  55622. //label.setBackgroundColor({r: this.color.r*255, g: this.color.g*255, b: this.color.b*255, a:config.measure.default.opacity})
  55623. label.sprite.material.useDepth = true;
  55624. //label.sprite.material.opacity = 0.98
  55625. //label.textColor = {r: 255, g: 255, b: 255, a: 1}
  55626. }
  55627. label.updateTexture();
  55628. }
  55629. /* function setLabelHightState(label, state){
  55630. if(state){
  55631. label.setBackgroundColor({r: highlightColor.r*255, g: highlightColor.g*255, b: highlightColor.b*255, a:config.measure.highlight.labelOpacity})
  55632. label.sprite.material.useDepth = false;
  55633. }else{
  55634. label.setBackgroundColor(mainLabelProp.backgroundColor)
  55635. label.sprite.material.useDepth = true
  55636. }
  55637. label.updateTexture()
  55638. //label.sprite.material.needsUpdate = true
  55639. }
  55640. */
  55641. function createCircleRadiusLabel$1(){
  55642. const circleRadiusLabel = new TextSprite$2("");
  55643. circleRadiusLabel.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  55644. circleRadiusLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  55645. circleRadiusLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  55646. circleRadiusLabel.fontsize = 16;
  55647. circleRadiusLabel.material.depthTest = false;
  55648. circleRadiusLabel.material.opacity = 1;
  55649. circleRadiusLabel.visible = false;
  55650. return circleRadiusLabel;
  55651. }
  55652. function createCircleRadiusLine$1(){
  55653. /* const lineGeometry = new LineGeometry();
  55654. lineGeometry.setPositions([
  55655. 0, 0, 0,
  55656. 0, 0, 0,
  55657. ]);
  55658. const lineMaterial = new LineMaterial({
  55659. color: 0xff0000,
  55660. lineWidth: 2,
  55661. resolution: new THREE.Vector2(1000, 1000),
  55662. gapSize: 1,
  55663. dashed: true,
  55664. });
  55665. lineMaterial.depthTest = false;
  55666. const circleRadiusLine = new Line2(lineGeometry, lineMaterial);*/
  55667. var circleRadiusLine = LineDraw.createFatLine([ ],{
  55668. color:0xff0000,
  55669. dashSize: 0.5,
  55670. gapSize: 0.2,
  55671. lineWidth: config$1.measure.lineWidth
  55672. });
  55673. circleRadiusLine.visible = false;
  55674. return circleRadiusLine;
  55675. }
  55676. function createCircleLine$1(){
  55677. const coordinates = [];
  55678. let n = 128;
  55679. for(let i = 0; i <= n; i++){
  55680. let u0 = 2 * Math.PI * (i / n);
  55681. let u1 = 2 * Math.PI * (i + 1) / n;
  55682. let p0 = new Vector3(
  55683. Math.cos(u0),
  55684. Math.sin(u0),
  55685. 0
  55686. );
  55687. let p1 = new Vector3(
  55688. Math.cos(u1),
  55689. Math.sin(u1),
  55690. 0
  55691. );
  55692. coordinates.push(
  55693. p0,
  55694. p1
  55695. );
  55696. }
  55697. /* const geometry = new LineGeometry();
  55698. geometry.setPositions(coordinates);
  55699. const material = new LineMaterial({
  55700. color: 0xff0000,
  55701. dashSize: 5,
  55702. gapSize: 2,
  55703. lineWidth: 2,
  55704. resolution: new THREE.Vector2(1000, 1000),
  55705. });
  55706. material.depthTest = false;
  55707. const circleLine = new Line2(geometry, material);
  55708. circleLine.visible = false;
  55709. circleLine.computeLineDistances();*/
  55710. var circleLine = LineDraw.createFatLine(coordinates,{
  55711. color: 0xff0000,
  55712. dashSize: 0.5,
  55713. gapSize: 0.2,
  55714. lineWidth: config$1.measure.lineWidth
  55715. });
  55716. return circleLine;
  55717. }
  55718. /* function createCircleCenter(){
  55719. const sg = new THREE.markerGeometry(1, 32, 32);
  55720. const sm = new THREE.MeshNormalMaterial();
  55721. const circleCenter = new THREE.Mesh(sg, sm);
  55722. circleCenter.visible = false;
  55723. return circleCenter;
  55724. } */
  55725. function createLine$1(){
  55726. const line = LineDraw.createFatLine([ ],{
  55727. color: 0xff0000,
  55728. dashSize: 0.5,
  55729. gapSize: 0.2,
  55730. lineWidth: config$1.measure.lineWidth
  55731. });
  55732. return line;
  55733. }
  55734. function createCircle$1(){
  55735. const coordinates = [];
  55736. let n = 128;
  55737. for(let i = 0; i <= n; i++){
  55738. let u0 = 2 * Math.PI * (i / n);
  55739. let u1 = 2 * Math.PI * (i + 1) / n;
  55740. let p0 = new Vector3(
  55741. Math.cos(u0),
  55742. Math.sin(u0),
  55743. 0
  55744. );
  55745. let p1 = new Vector3(
  55746. Math.cos(u1),
  55747. Math.sin(u1),
  55748. 0
  55749. );
  55750. coordinates.push(
  55751. p0,
  55752. p1
  55753. );
  55754. }
  55755. var line = LineDraw.createFatLine(coordinates,{
  55756. color: 0xff0000,
  55757. dashSize: 0.5,
  55758. gapSize: 0.2,
  55759. lineWidth: config$1.measure.lineWidth
  55760. });
  55761. return line;
  55762. }
  55763. /* function createAzimuth(){
  55764. const azimuth = {
  55765. label: null,
  55766. center: null,
  55767. target: null,
  55768. north: null,
  55769. centerToNorth: null,
  55770. centerToTarget: null,
  55771. centerToTargetground: null,
  55772. targetgroundToTarget: null,
  55773. circle: null,
  55774. node: null,
  55775. };
  55776. const sg = new THREE.markerGeometry(1, 32, 32);
  55777. const sm = new THREE.MeshNormalMaterial();
  55778. {
  55779. const label = new TextSprite("");
  55780. label.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  55781. label.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  55782. label.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  55783. label.fontsize = 16;
  55784. label.material.depthTest = false;
  55785. label.material.opacity = 1;
  55786. azimuth.label = label;
  55787. }
  55788. azimuth.center = new THREE.Mesh(sg, sm);
  55789. azimuth.target = new THREE.Mesh(sg, sm);
  55790. azimuth.north = new THREE.Mesh(sg, sm);
  55791. azimuth.centerToNorth = createLine();
  55792. azimuth.centerToTarget = createLine();
  55793. azimuth.centerToTargetground = createLine();
  55794. azimuth.targetgroundToTarget = createLine();
  55795. azimuth.circle = createCircle();
  55796. azimuth.node = new THREE.Object3D();
  55797. azimuth.node.add(
  55798. azimuth.centerToNorth,
  55799. azimuth.centerToTarget,
  55800. azimuth.centerToTargetground,
  55801. azimuth.targetgroundToTarget,
  55802. azimuth.circle,
  55803. azimuth.label,
  55804. azimuth.center,
  55805. azimuth.target,
  55806. azimuth.north,
  55807. );
  55808. return azimuth;
  55809. } */
  55810. /*
  55811. */
  55812. function updateAzimuth(viewer, measure){
  55813. if(!measure.showAzimuth)return
  55814. const azimuth = measure.azimuth;
  55815. const isOkay = measure.points.length === 2;
  55816. azimuth.node.visible = isOkay;
  55817. if(!azimuth.node.visible){
  55818. return;
  55819. }
  55820. const camera = viewer.scene.getActiveCamera();
  55821. const renderAreaSize = viewer.renderer.getSize(new Vector2());
  55822. const width = renderAreaSize.width;
  55823. const height = renderAreaSize.height;
  55824. const [p0, p1] = measure.points;
  55825. const r = p0.position.distanceTo(p1.position);
  55826. const northVec = Utils.getNorthVec(p0.position, r, viewer.getProjection());
  55827. const northPos = p0.position.clone().add(northVec);
  55828. azimuth.center.position.copy(p0.position);
  55829. azimuth.center.scale.set(2, 2, 2);
  55830. azimuth.center.visible = false;
  55831. // azimuth.target.visible = false;
  55832. { // north
  55833. azimuth.north.position.copy(northPos);
  55834. azimuth.north.scale.set(2, 2, 2);
  55835. let distance = azimuth.north.position.distanceTo(camera.position);
  55836. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  55837. let scale = (5 / pr);
  55838. azimuth.north.scale.set(scale, scale, scale);
  55839. }
  55840. { // target
  55841. azimuth.target.position.copy(p1.position);
  55842. azimuth.target.position.z = azimuth.north.position.z;
  55843. let distance = azimuth.target.position.distanceTo(camera.position);
  55844. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  55845. let scale = (5 / pr);
  55846. azimuth.target.scale.set(scale, scale, scale);
  55847. }
  55848. azimuth.circle.position.copy(p0.position);
  55849. azimuth.circle.scale.set(r, r, r);
  55850. azimuth.circle.material.resolution.set(width, height);
  55851. // to target
  55852. azimuth.centerToTarget.geometry.setPositions([
  55853. 0, 0, 0,
  55854. ...p1.position.clone().sub(p0.position).toArray(),
  55855. ]);
  55856. azimuth.centerToTarget.position.copy(p0.position);
  55857. azimuth.centerToTarget.geometry.verticesNeedUpdate = true;
  55858. azimuth.centerToTarget.geometry.computeBoundingSphere();
  55859. azimuth.centerToTarget.computeLineDistances();
  55860. azimuth.centerToTarget.material.resolution.set(width, height);
  55861. // to target ground
  55862. azimuth.centerToTargetground.geometry.setPositions([
  55863. 0, 0, 0,
  55864. p1.position.x - p0.position.x,
  55865. p1.position.y - p0.position.y,
  55866. 0,
  55867. ]);
  55868. azimuth.centerToTargetground.position.copy(p0.position);
  55869. azimuth.centerToTargetground.geometry.verticesNeedUpdate = true;
  55870. azimuth.centerToTargetground.geometry.computeBoundingSphere();
  55871. azimuth.centerToTargetground.computeLineDistances();
  55872. azimuth.centerToTargetground.material.resolution.set(width, height);
  55873. // to north
  55874. azimuth.centerToNorth.geometry.setPositions([
  55875. 0, 0, 0,
  55876. northPos.x - p0.position.x,
  55877. northPos.y - p0.position.y,
  55878. 0,
  55879. ]);
  55880. azimuth.centerToNorth.position.copy(p0.position);
  55881. azimuth.centerToNorth.geometry.verticesNeedUpdate = true;
  55882. azimuth.centerToNorth.geometry.computeBoundingSphere();
  55883. azimuth.centerToNorth.computeLineDistances();
  55884. azimuth.centerToNorth.material.resolution.set(width, height);
  55885. // label
  55886. const radians = Utils.computeAzimuth(p0.position, p1.position, viewer.getProjection());
  55887. let degrees = MathUtils.radToDeg(radians);
  55888. if(degrees < 0){
  55889. degrees = 360 + degrees;
  55890. }
  55891. const txtDegrees = `${degrees.toFixed(2)}°`;
  55892. const labelDir = northPos.clone().add(p1.position).multiplyScalar(0.5).sub(p0.position);
  55893. if(labelDir.length() > 0){
  55894. labelDir.z = 0;
  55895. labelDir.normalize();
  55896. const labelVec = labelDir.clone().multiplyScalar(r);
  55897. const labelPos = p0.position.clone().add(labelVec);
  55898. azimuth.label.position.copy(labelPos);
  55899. }
  55900. azimuth.label.setText(txtDegrees);
  55901. let distance = azimuth.label.position.distanceTo(camera.position);
  55902. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  55903. let scale = (70 / pr);
  55904. azimuth.label.scale.set(scale, scale, scale);
  55905. }
  55906. class MeasuringTool extends EventDispatcher{
  55907. constructor (viewer) {
  55908. super();
  55909. this.viewer = viewer;
  55910. this.renderer = viewer.renderer;
  55911. this.viewer.addEventListener('start_inserting_measurement', e => {
  55912. this.viewer.dispatchEvent({
  55913. type: 'cancel_insertions'
  55914. });
  55915. });
  55916. this.showLabels = true;
  55917. this.scene = new Scene();
  55918. this.scene.name = 'scene_measurement';
  55919. //this.light = new THREE.PointLight(0xffffff, 1.0);
  55920. //this.scene.add(this.light);
  55921. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  55922. //this.scene = viewer.overlay//
  55923. this.onRemove = (e) => { e.measurement.dispose();/* this.scene.remove(e.measurement); */};
  55924. this.onAdd = e => {this.scene.add(e.measurement);};
  55925. for(let measurement of viewer.scene.measurements){
  55926. this.onAdd({measurement: measurement});
  55927. }
  55928. viewer.addEventListener('camera_changed', this.update.bind(this),{importance:10});//优先级高于sprite
  55929. if(Potree.config.measure.mulLabelHideFaraway ){
  55930. viewer.addEventListener("raycaster", this.beforeDraw.bind(this),{importance:10}); //before render
  55931. viewer.addEventListener("render.begin", this.beforeDraw.bind(this),{importance:10}); //before render
  55932. viewer.addEventListener("render.begin2", this.beforeDraw.bind(this),{importance:10});
  55933. }
  55934. //viewer.addEventListener("update", this.update.bind(this));
  55935. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  55936. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  55937. viewer.scene.addEventListener('measurement_added', this.onAdd);
  55938. viewer.scene.addEventListener('measurement_removed', this.onRemove);
  55939. viewer.addEventListener('resize',this.setSize.bind(this));
  55940. }
  55941. onSceneChange(e){
  55942. if(e.oldScene){
  55943. e.oldScene.removeEventListener('measurement_added', this.onAdd);
  55944. e.oldScene.removeEventListener('measurement_removed', this.onRemove);
  55945. }
  55946. e.scene.addEventListener('measurement_added', this.onAdd);
  55947. e.scene.addEventListener('measurement_removed', this.onRemove);
  55948. }
  55949. createMeasureFromData(data){//add
  55950. const measure = new Measure$1(data);
  55951. if(measure.failBuilded){
  55952. return
  55953. }
  55954. viewer.scene.addMeasurement(measure);
  55955. if(measure.guideLine)measure.guideLine.visible = false;
  55956. return measure
  55957. }
  55958. beforeDraw(e){
  55959. if(e.viewport.name == 'mapViewport' && !viewer.mapViewer.attachedToViewer)return //no measures
  55960. viewer.scene.measurements.forEach(measure=>{
  55961. if(measure.measureType != 'MulDistance' || (measure.isNew ? measure.points.length<4 : measure.points.length<3)) return
  55962. let lastIndex = measure.points.length - 1;
  55963. for (let index = 0; index <= lastIndex; index++) {
  55964. if(!measure.closed && index == lastIndex)continue
  55965. let edgeLabel = measure.edgeLabels[index];
  55966. let v = edgeLabel.visiMap.get(e.viewport.camera);
  55967. if(v == void 0){
  55968. return measure.getEdgeLabelVisi(e.viewport)
  55969. }
  55970. Potree.Utils.updateVisible(edgeLabel, 'tooFar', v === false ? false : true);
  55971. }
  55972. });
  55973. }
  55974. update(e){
  55975. if(viewer.inputHandler.measuring && Potree.settings.adsorption){
  55976. viewer.scene.measurements.forEach(measure=>{
  55977. measure.getPointsPos2d(e.viewport, true);
  55978. });
  55979. }
  55980. if(Potree.config.measure.mulLabelHideFaraway){
  55981. if(e.changeInfo.projectionChanged || e.viewport.camera.type == 'PerspectiveCamera' && e.changeInfo.positionChanged){//for MulDistance
  55982. viewer.scene.measurements.forEach(measure=>{
  55983. if(measure.measureType != 'MulDistance' || (measure.isNew ? measure.points.length<4 : measure.points.length<3)) return
  55984. measure.getEdgeLabelVisi(e.viewport);
  55985. return
  55986. let lastIndex = measure.points.length - 1;
  55987. for (let index = 0; index <= lastIndex; index++) {
  55988. if(!measure.closed && index == lastIndex)continue
  55989. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  55990. let previousIndex = (index === 0) ? lastIndex : index - 1;
  55991. let point = measure.points[index];
  55992. let nextPoint = measure.points[nextIndex];
  55993. let previousPoint = measure.points[previousIndex];
  55994. let point2d = new Vector2().copy(pos2ds[index]);
  55995. let nextPoint2d = new Vector2().copy(pos2ds[nextIndex]);
  55996. if(measure.showDistances || measure.labelText){ // edge labels
  55997. let edgeLabel = measure.edgeLabels[index];
  55998. if(edgeLabel.visible){
  55999. measure.setEdgeLabelPos(edgeLabel, point, nextPoint );
  56000. }
  56001. }
  56002. }
  56003. });
  56004. }
  56005. }
  56006. return;
  56007. let camera = this.viewer.scene.getActiveCamera();
  56008. let domElement = this.renderer.domElement;
  56009. let measurements = this.viewer.scene.measurements;
  56010. // make size independant of distance
  56011. let mainLabels = [], subLabels = [];
  56012. for (let measure of measurements) {
  56013. measure.lengthUnit = this.viewer.lengthUnit;
  56014. measure.lengthUnitDisplay = this.viewer.lengthUnitDisplay;
  56015. //measure.update();
  56016. updateAzimuth(this.viewer, measure);
  56017. /* [...measure.markers, ...measure.edgeLabels, measure.areaLabel].forEach(e=>{
  56018. e && e.update()
  56019. }); */
  56020. // labels
  56021. /* let labels = measure.edgeLabels.concat(measure.angleLabels);
  56022. for(let label of labels){
  56023. label.update()
  56024. if(label.elem.hasClass('sub')){
  56025. subLabels.push(label)
  56026. }else{
  56027. mainLabels.push(label)
  56028. }
  56029. }
  56030. // coordinate labels
  56031. for (let j = 0; j < measure.coordinateLabels.length; j++) {
  56032. let label = measure.coordinateLabels[j];
  56033. label.update()
  56034. mainLabels.push(label)
  56035. }
  56036. if(measure.showArea){ // area label
  56037. let label = measure.areaLabel;
  56038. label.update()
  56039. mainLabels.push(label)
  56040. } */
  56041. /* if(measure.showCircle){ // radius label
  56042. let label = measure.circleRadiusLabel;
  56043. let distance = label.position.distanceTo(camera.position);
  56044. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  56045. let scale = (70 / pr);
  56046. label.scale.set(scale, scale, scale);
  56047. } */
  56048. if(!this.showLabels){
  56049. const labels = [
  56050. ...measure.sphereLabels,
  56051. ...measure.angleLabels,
  56052. measure.circleRadiusLabel,
  56053. ];
  56054. for(const label of labels){
  56055. label.visible = false;
  56056. }
  56057. }
  56058. }
  56059. //this.updateLabelZIndex([{labels:subLabels},{labels:mainLabels}])
  56060. }
  56061. setSize(e){ //e.resolution
  56062. /* if(Measure.lineMats){
  56063. for(var m in Measure.lineMats){
  56064. Measure.lineMats[m].resolution.set(e.canvasWidth, e.canvasHeight);
  56065. }
  56066. }
  56067. if(Measure.sphereMats){
  56068. for(var s in Measure.sphereMats){
  56069. Measure.sphereMats[s].uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  56070. }
  56071. }
  56072. for (let measure of this.viewer.scene.measurements) {
  56073. measure.edgeLabels.concat(measure.areaLabel).forEach(label=>{
  56074. label.sprite.material.uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  56075. })
  56076. } */
  56077. }
  56078. updateLabelZIndex(group){//[{labels:[]},{}] 顺序按照z-index低到高
  56079. group.forEach((e,i)=>{
  56080. e.base = group[i-1] ? group[i-1].base + group[i-1].labels.length : 0;
  56081. var labels = e.labels.sort((a,b)=>{
  56082. return b.pos2d.z - a.pos2d.z
  56083. });
  56084. labels.forEach((label,index)=>{
  56085. $(label.elem).css('z-index', e.base+index);
  56086. });
  56087. });
  56088. }
  56089. editStateChange(e){
  56090. //console.log("editStateChange" , e.state)
  56091. let state = e.state;
  56092. if(!state){
  56093. state = viewer.scene.measurements.some(e=>e.isEditing);
  56094. }
  56095. if(state){
  56096. viewer.dispatchEvent({type:"measureMovePoint"});//重新激活reticule状态
  56097. }else {
  56098. viewer.dispatchEvent({type:"endMeasureMove"});
  56099. }
  56100. //this.editing =
  56101. }
  56102. startInsertion (args = {}, callback, cancelFun) {
  56103. let domElement = this.viewer.renderer.domElement;
  56104. let measure = new Measure$1(args);
  56105. this.scene.add(measure);
  56106. measure.isNew = true;
  56107. this.viewer.dispatchEvent({
  56108. type: 'start_inserting_measurement',
  56109. measure: measure
  56110. });
  56111. measure.addEventListener('editStateChange', this.editStateChange.bind(this));
  56112. measure.editStateChange(true);
  56113. let timer;
  56114. let endDragFun = (e) => {
  56115. let length = measure.points.length;
  56116. if (e.button == MOUSE.LEFT || e.isTouch) {
  56117. if (length >= measure.maxMarkers) {
  56118. end({finish:true});
  56119. }else {
  56120. var marker = measure.addMarker({point:measure.points[length - 1].clone()});
  56121. if(args.isRect && measure.markers.length == 3){//marker全可见
  56122. measure.addMarker({point:measure.points[0].clone()});
  56123. }else {
  56124. measure.markers[length].visible = false;
  56125. measure.edges[length].visible = false;
  56126. }
  56127. measure.edges[length-1].visible = true;
  56128. measure.markers[length-1].visible = true;
  56129. marker.isDragging = true;
  56130. measure.continueDrag(marker, e);
  56131. }
  56132. } else if (e.button === MOUSE.RIGHT ) { //触屏怎么取消?
  56133. if(e.pressDistance < Potree.config.clickMaxDragDis){//非拖拽的话
  56134. var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d.slice(0,measure.point2dInfo.points2d.length-1));//检测除了最后一个点的相交情况
  56135. if(!isIntersectSelf)end(e);
  56136. else measure.continueDrag(null, e);
  56137. }else measure.continueDrag(null, e);
  56138. }
  56139. };
  56140. let end = (e={}) => {//确定、结束
  56141. if(!measure.isNew )return
  56142. if(args.minMarkers != void 0 ){
  56143. if(!e.finish && measure.markers.length<=args.minMarkers ){//右键 当个数不够时取消
  56144. //this.viewer.scene.removeMeasurement(measure)
  56145. //重新开始画
  56146. if(measure.markers.length>0){
  56147. measure.markers[0].removeEventListener('mousedown',end);
  56148. measure.reDraw();
  56149. this.viewer.addEventListener('global_click', click, {importance:10});
  56150. measure.editStateChange(true);
  56151. }
  56152. return
  56153. /* if(!Potree.settings.isOfficial) this.viewer.scene.removeMeasurement(measure)
  56154. else if(e.drag){ //正式版本不允许右键退出, 继续
  56155. continueDrag(e.drag.object)
  56156. measure.editStateChange(true)
  56157. return
  56158. } */
  56159. }
  56160. }
  56161. let lastMarker = measure.markers[measure.markers.length-1];
  56162. if (/* !e.finish&& */ measure.markers.length > args.minMarkers) {
  56163. measure.removeMarker(measure.points.length - 1);
  56164. measure.markers[0].removeEventListener('mouseover', mouseover);
  56165. measure.markers[0].removeEventListener('mouseleave', mouseleave);
  56166. measure.markers[0].removeEventListener('click'/* 'mousedown' */,Exit);
  56167. if(e.byClickMarker && measure.markers.length > args.minMarkers ){//通过点击第一个marker而结束的话,会多一个marker。但点击marker后可能会因为和它坐标一致而没有添加成功,就不删,根据添加的时间来判断。
  56168. let delta = Date.now() - lastMarker.createTime;
  56169. //console.log('delta',delta)
  56170. if(delta < 10){//刚生成的,说明点击后新增了一个marker
  56171. measure.removeMarker(measure.points.length - 1);
  56172. }
  56173. }
  56174. }
  56175. measure.isNew = false;
  56176. let length = measure.points.length;
  56177. if(length){
  56178. measure.markers[length-1].visible = true;
  56179. measure.edges[length-1].visible = !!measure.closed;
  56180. measure.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  56181. measure.edges.forEach(edge=>{edge.dispatchEvent('addHoverEvent'); });
  56182. measure.update();//update last edgeLabel
  56183. }
  56184. clearTimeout(timer);
  56185. this.viewer.removeEventListener('cancel_insertions', Exit);
  56186. //pressExit && this.viewer.inputHandler.removeEventListener('keydown', pressExit);
  56187. this.viewer.removeEventListener('global_click', click);
  56188. this.viewer.removeEventListener('global_mousemove', ifAtWrongPlace);
  56189. viewer.dispatchEvent({
  56190. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  56191. });
  56192. viewer.inputHandler.dispatchEvent({type:'measuring', v:false, cause:'stopInsertion', situation:'adding', object:measure} );
  56193. //var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d.slice(0,measure.point2dInfo.points2d.length-1))//检测除了最后一个点的相交情况
  56194. var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d);
  56195. if(isIntersectSelf) return cancelFun && cancelFun() //请求删除,不重建
  56196. e.remove || callback && callback();
  56197. /* this.viewer.dispatchEvent({
  56198. type: 'finish_inserting_measurement',
  56199. measure: measure
  56200. }); */
  56201. };
  56202. measure.addEventListener('finish', end); //完成
  56203. let Exit = (e)=>{//强制退出
  56204. if(e.measure && e.measure != measure || !viewer.scene.measurements.includes(measure) || !measure.isNew){
  56205. return;//若指定了退出的measure但和该measure不一致,就返回
  56206. }
  56207. if(e.remove){
  56208. viewer.scene.removeMeasurement(measure);
  56209. }
  56210. measure.editStateChange(false);
  56211. measure.cannotConfirmNormal = false; //一些dropMarker中的句子
  56212. measure.guideLine && (measure.guideLine.visible = false);
  56213. /*
  56214. if(this.viewer.inputHandler.drag && !e.remove ){//还未触发drop的话
  56215. this.viewer.inputHandler.drag.object.dispatchEvent({ //这句会导致又增一个marker
  56216. type: 'drop',
  56217. drag: this.viewer.inputHandler.drag,
  56218. viewer: this.viewer,
  56219. pressDistance:0,
  56220. button : THREE.MOUSE.RIGHT
  56221. });
  56222. } else {*///未结束时添加新的measure时会触发
  56223. end({finish:true, remove:e.remove, byClickMarker: e.type == 'click'});
  56224. //}
  56225. this.viewer.inputHandler.drag && (this.viewer.inputHandler.drag.object = null);
  56226. };
  56227. this.viewer.addEventListener('cancel_insertions', Exit);
  56228. /*let pressExit
  56229. if(!Potree.settings.isOfficial){
  56230. pressExit = (e)=>{
  56231. if(e.keyCode == 27){//Esc
  56232. //Exit()
  56233. //怎么模拟右键???//现由前端发出
  56234. }
  56235. }
  56236. this.viewer.inputHandler.addEventListener('keydown', pressExit)
  56237. } */
  56238. let mouseover = (e) => {
  56239. measure.setMarkerSelected(e.object, 'hover', 'single');
  56240. };
  56241. let mouseleave = (e) => {
  56242. measure.setMarkerSelected(e.object, 'unhover', 'single');
  56243. };
  56244. let click = (e)=>{//一旦点击就立刻增加两marker
  56245. if(ifAtWrongPlace(e))return
  56246. if(e.clickElement)return //如点击label时focusOnObject
  56247. if(e.button === MOUSE.RIGHT)return
  56248. //console.log('measure clicked33', !!e.intersectPoint)
  56249. //var I = e.intersectPoint && (e.intersectPoint.orthoIntersect || e.intersectPoint.location)
  56250. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  56251. if(!I){
  56252. return measure.dispatchEvent('intersectNoPointcloud')
  56253. }
  56254. var atMap = e.drag.dragViewport.name == 'mapViewport';
  56255. //在地图上测量的首个点按楼层高度(暂时先只按mainViewport相机高度吧,但navvis是按楼层,画在楼层的地面上,可能因为平面图显示的是楼层近地面),
  56256. if(atMap){
  56257. I = I.clone().setZ(viewer.mainViewport.camera.position.z );
  56258. }
  56259. var marker = measure.addMarker({point:I});
  56260. marker.isDragging = true;
  56261. this.viewer.inputHandler.startDragging(marker , {endDragFun, notPressMouse:true} ); //notPressMouse代表不是通过按下鼠标来拖拽
  56262. e.drag = this.viewer.inputHandler.drag;
  56263. e.drag.endDragFun = endDragFun;
  56264. e.drag.notPressMouse = true;
  56265. //if(!measure.dragMarker(e) || !measure.dropMarker(e))return
  56266. measure.dragMarker(e);
  56267. measure.dropMarker(e);
  56268. if(measure.maxMarkers > 1 ){
  56269. measure.markers[1].visible = false;
  56270. measure.edges[1].visible = false;
  56271. }
  56272. if(measure.closed && !measure.isRect){
  56273. measure.markers[0].addEventListener('mouseover', mouseover);
  56274. measure.markers[0].addEventListener('mouseleave', mouseleave);
  56275. measure.markers[0].addEventListener('click'/* 'mousedown' */,Exit); //点击到第一个marker就结束
  56276. }
  56277. this.viewer.removeEventListener('global_click', click);///* global_drop */
  56278. //console.log('measure clicked')
  56279. e.consume && e.consume();
  56280. return {stopContinue:true}//防止继续执行别的侦听,如flytopano
  56281. };
  56282. //点击第n下拥有n+1个marker, n>0
  56283. viewer.inputHandler.dispatchEvent({type: 'measuring', v: true, cause:'startInsertion', situation:'adding', object:measure});
  56284. this.viewer.addEventListener('global_click', click, {importance:10});//add importance
  56285. let ifAtWrongPlace = (e)=>{
  56286. if(measure.unableDragAtMap && e.hoverViewport.name == 'mapViewport' ){
  56287. if(e.isTouch){
  56288. viewer.dispatchEvent({type:'reticule_forbit', v:true});
  56289. }else {
  56290. viewer.dispatchEvent({
  56291. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  56292. });
  56293. }
  56294. return true
  56295. }else {
  56296. if(e.isTouch){
  56297. viewer.dispatchEvent({type:'reticule_forbit',v:false});
  56298. }else {
  56299. viewer.dispatchEvent({
  56300. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  56301. });
  56302. }
  56303. }
  56304. };
  56305. if(measure.unableDragAtMap){
  56306. this.viewer.addEventListener('global_mousemove', ifAtWrongPlace);
  56307. }
  56308. this.viewer.scene.addMeasurement(measure);
  56309. return measure;
  56310. }
  56311. render(o={}){
  56312. if(this.scene.children.filter(e=>e.visible).length == 0)return
  56313. Potree.Utils.setCameraLayers(o.camera, ['measure']);
  56314. /* if(o.screenshot && this.viewer.fxaaPass.enabled){ //抗锯齿
  56315. this.viewer.ssaaRenderPass.sampleLevel = 4
  56316. this.viewer.composer.render(this.scene, o.camera );
  56317. }else{ */
  56318. viewer.dispatchEvent({type: "render.begin2" , name:'measure', viewport:o.viewport });
  56319. this.viewer.renderer.render(this.scene, o.camera );
  56320. //}
  56321. }
  56322. };
  56323. class ProfileTool extends EventDispatcher$1 {
  56324. constructor (viewer) {
  56325. super();
  56326. this.viewer = viewer;
  56327. this.renderer = viewer.renderer;
  56328. this.addEventListener('start_inserting_profile', e => {
  56329. this.viewer.dispatchEvent({
  56330. type: 'cancel_insertions'
  56331. });
  56332. });
  56333. this.scene = new Scene();
  56334. this.scene.name = 'scene_profile';
  56335. this.light = new PointLight(0xffffff, 1.0);
  56336. this.scene.add(this.light);
  56337. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  56338. this.onRemove = e => this.scene.remove(e.profile);
  56339. this.onAdd = e => this.scene.add(e.profile);
  56340. for(let profile of viewer.scene.profiles){
  56341. this.onAdd({profile: profile});
  56342. }
  56343. viewer.addEventListener("update", this.update.bind(this));
  56344. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  56345. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  56346. viewer.scene.addEventListener('profile_added', this.onAdd);
  56347. viewer.scene.addEventListener('profile_removed', this.onRemove);
  56348. }
  56349. onSceneChange(e){
  56350. if(e.oldScene){
  56351. e.oldScene.removeEventListeners('profile_added', this.onAdd);
  56352. e.oldScene.removeEventListeners('profile_removed', this.onRemove);
  56353. }
  56354. e.scene.addEventListener('profile_added', this.onAdd);
  56355. e.scene.addEventListener('profile_removed', this.onRemove);
  56356. }
  56357. startInsertion (args = {}) {
  56358. let domElement = this.viewer.renderer.domElement;
  56359. let profile = new Profile();
  56360. profile.name = args.name || 'Profile';
  56361. this.dispatchEvent({
  56362. type: 'start_inserting_profile',
  56363. profile: profile
  56364. });
  56365. this.scene.add(profile);
  56366. let cancel = {
  56367. callback: null
  56368. };
  56369. let insertionCallback = (e) => {
  56370. if(e.button === MOUSE.LEFT){
  56371. if(profile.points.length <= 1){
  56372. let camera = this.viewer.scene.getActiveCamera();
  56373. let distance = camera.position.distanceTo(profile.points[0]);
  56374. let clientSize = this.viewer.renderer.getSize(new Vector2());
  56375. let pr = Utils.projectedRadius(1, camera, distance, clientSize.width, clientSize.height);
  56376. let width = (10 / pr);
  56377. profile.setWidth(width);
  56378. }
  56379. profile.addMarker(profile.points[profile.points.length - 1].clone());
  56380. this.viewer.inputHandler.startDragging(
  56381. profile.spheres[profile.spheres.length - 1]);
  56382. } else if (e.button === MOUSE.RIGHT) {
  56383. cancel.callback();
  56384. }
  56385. };
  56386. cancel.callback = e => {
  56387. profile.removeMarker(profile.points.length - 1);
  56388. domElement.removeEventListener('mouseup', insertionCallback, false);
  56389. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  56390. };
  56391. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  56392. domElement.addEventListener('mouseup', insertionCallback, false);
  56393. profile.addMarker(new Vector3(0, 0, 0));
  56394. this.viewer.inputHandler.startDragging(
  56395. profile.spheres[profile.spheres.length - 1]);
  56396. this.viewer.scene.addProfile(profile);
  56397. return profile;
  56398. }
  56399. update(){
  56400. let camera = this.viewer.scene.getActiveCamera();
  56401. let profiles = this.viewer.scene.profiles;
  56402. let renderAreaSize = this.viewer.renderer.getSize(new Vector2());
  56403. let clientWidth = renderAreaSize.width;
  56404. let clientHeight = renderAreaSize.height;
  56405. this.light.position.copy(camera.position);
  56406. // make size independant of distance
  56407. for(let profile of profiles){
  56408. for(let sphere of profile.spheres){
  56409. let distance = camera.position.distanceTo(sphere.getWorldPosition(new Vector3()));
  56410. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  56411. let scale = (15 / pr);
  56412. sphere.scale.set(scale, scale, scale);
  56413. }
  56414. }
  56415. }
  56416. render(){
  56417. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  56418. }
  56419. }
  56420. class ScreenBoxSelectTool extends EventDispatcher$1{
  56421. constructor(viewer){
  56422. super();
  56423. this.viewer = viewer;
  56424. this.scene = new Scene();
  56425. viewer.addEventListener("update", this.update.bind(this));
  56426. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  56427. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  56428. }
  56429. onSceneChange(scene){
  56430. console.log("scene changed");
  56431. }
  56432. startInsertion(){
  56433. let domElement = this.viewer.renderer.domElement;
  56434. let volume = new BoxVolume();
  56435. volume.position.set(12345, 12345, 12345);
  56436. volume.showVolumeLabel = false;
  56437. volume.visible = false;
  56438. volume.update();
  56439. this.viewer.scene.addVolume(volume);
  56440. this.importance = 10;
  56441. let selectionBox = $(`<div style="position: absolute; border: 2px solid white; pointer-events: none; border-style:dashed"></div>`);
  56442. $(domElement.parentElement).append(selectionBox);
  56443. selectionBox.css("right", "10px");
  56444. selectionBox.css("bottom", "10px");
  56445. let drag = e =>{
  56446. volume.visible = true;
  56447. let mStart = e.drag.start;
  56448. let mEnd = e.drag.end;
  56449. let box2D = new Box2();
  56450. box2D.expandByPoint(mStart);
  56451. box2D.expandByPoint(mEnd);
  56452. selectionBox.css("left", `${box2D.min.x}px`);
  56453. selectionBox.css("top", `${box2D.min.y}px`);
  56454. selectionBox.css("width", `${box2D.max.x - box2D.min.x}px`);
  56455. selectionBox.css("height", `${box2D.max.y - box2D.min.y}px`);
  56456. let camera = e.viewer.scene.getActiveCamera();
  56457. let size = e.viewer.renderer.getSize(new Vector2());
  56458. let frustumSize = new Vector2(
  56459. camera.right - camera.left,
  56460. camera.top - camera.bottom);
  56461. let screenCentroid = new Vector2().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  56462. let ray = Utils.mouseToRay(screenCentroid, camera, size.width, size.height);
  56463. let diff = new Vector2().subVectors(e.drag.end, e.drag.start);
  56464. diff.divide(size).multiply(frustumSize);
  56465. volume.position.copy(ray.origin);
  56466. volume.up.copy(camera.up);
  56467. volume.rotation.copy(camera.rotation);
  56468. volume.scale.set(diff.x, diff.y, 1000 * 100);
  56469. e.consume();
  56470. };
  56471. let drop = e => {
  56472. this.importance = 0;
  56473. $(selectionBox).remove();
  56474. this.viewer.inputHandler.deselectAll();
  56475. this.viewer.inputHandler.toggleSelection(volume);
  56476. let camera = e.viewer.scene.getActiveCamera();
  56477. let size = e.viewer.renderer.getSize(new Vector2());
  56478. let screenCentroid = new Vector2().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  56479. let ray = Utils.mouseToRay(screenCentroid, camera, size.width, size.height);
  56480. let line = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction));
  56481. this.removeEventListener("drag", drag);
  56482. this.removeEventListener("drop", drop);
  56483. let allPointsNear = [];
  56484. let allPointsFar = [];
  56485. // TODO support more than one point cloud
  56486. for(let pointcloud of this.viewer.scene.pointclouds){
  56487. if(!pointcloud.visible){
  56488. continue;
  56489. }
  56490. let volCam = camera.clone();
  56491. volCam.left = -volume.scale.x / 2;
  56492. volCam.right = +volume.scale.x / 2;
  56493. volCam.top = +volume.scale.y / 2;
  56494. volCam.bottom = -volume.scale.y / 2;
  56495. volCam.near = -volume.scale.z / 2;
  56496. volCam.far = +volume.scale.z / 2;
  56497. volCam.rotation.copy(volume.rotation);
  56498. volCam.position.copy(volume.position);
  56499. volCam.updateMatrix();
  56500. volCam.updateMatrixWorld();
  56501. volCam.updateProjectionMatrix();
  56502. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  56503. let ray = new Ray(volCam.getWorldPosition(new Vector3()), volCam.getWorldDirection(new Vector3()));
  56504. let rayInverse = new Ray(
  56505. ray.origin.clone().add(ray.direction.clone().multiplyScalar(volume.scale.z)),
  56506. ray.direction.clone().multiplyScalar(-1));
  56507. let pickerSettings = {
  56508. width: 8,
  56509. height: 8,
  56510. pickWindowSize: 8,
  56511. all: true,
  56512. pickClipped: true,
  56513. pointSizeType: PointSizeType.FIXED,
  56514. pointSize: 1};
  56515. let pointsNear = pointcloud.pick(viewer, volCam, ray, pickerSettings);
  56516. volCam.rotateX(Math.PI);
  56517. volCam.updateMatrix();
  56518. volCam.updateMatrixWorld();
  56519. volCam.updateProjectionMatrix();
  56520. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  56521. let pointsFar = pointcloud.pick(viewer, volCam, rayInverse, pickerSettings);
  56522. allPointsNear.push(...pointsNear);
  56523. allPointsFar.push(...pointsFar);
  56524. }
  56525. if(allPointsNear.length > 0 && allPointsFar.length > 0){
  56526. let viewLine = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction));
  56527. let closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  56528. let closest = closestOnLine.sort( (a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b))[0];
  56529. let farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  56530. let farthest = farthestOnLine.sort( (a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a))[0];
  56531. let distance = closest.distanceTo(farthest);
  56532. let centroid = new Vector3().addVectors(closest, farthest).multiplyScalar(0.5);
  56533. volume.scale.z = distance * 1.1;
  56534. volume.position.copy(centroid);
  56535. }
  56536. volume.clip = true;
  56537. };
  56538. this.addEventListener("drag", drag);
  56539. this.addEventListener("drop", drop);
  56540. viewer.inputHandler.addInputListener(this);
  56541. return volume;
  56542. }
  56543. update(e){
  56544. //console.log(e.delta)
  56545. }
  56546. render(){
  56547. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  56548. }
  56549. }
  56550. class SpotLightHelper$1 extends Object3D{
  56551. constructor(light, color){
  56552. super();
  56553. this.light = light;
  56554. this.color = color;
  56555. //this.up.set(0, 0, 1);
  56556. this.updateMatrix();
  56557. this.updateMatrixWorld();
  56558. { // SPHERE
  56559. let sg = new SphereGeometry(1, 32, 32);
  56560. let sm = new MeshNormalMaterial();
  56561. this.sphere = new Mesh(sg, sm);
  56562. this.sphere.scale.set(0.5, 0.5, 0.5);
  56563. this.add(this.sphere);
  56564. }
  56565. { // LINES
  56566. let positions = new Float32Array([
  56567. +0, +0, +0, +0, +0, -1,
  56568. +0, +0, +0, -1, -1, -1,
  56569. +0, +0, +0, +1, -1, -1,
  56570. +0, +0, +0, +1, +1, -1,
  56571. +0, +0, +0, -1, +1, -1,
  56572. -1, -1, -1, +1, -1, -1,
  56573. +1, -1, -1, +1, +1, -1,
  56574. +1, +1, -1, -1, +1, -1,
  56575. -1, +1, -1, -1, -1, -1,
  56576. ]);
  56577. let geometry = new BufferGeometry();
  56578. geometry.setAttribute("position", new BufferAttribute(positions, 3));
  56579. let material = new LineBasicMaterial();
  56580. this.frustum = new LineSegments(geometry, material);
  56581. this.add(this.frustum);
  56582. }
  56583. this.update();
  56584. }
  56585. update(){
  56586. this.light.updateMatrix();
  56587. this.light.updateMatrixWorld();
  56588. let position = this.light.position;
  56589. let target = new Vector3().addVectors(
  56590. this.light.position, this.light.getWorldDirection(new Vector3()).multiplyScalar(-1));
  56591. let quat = new Quaternion().setFromRotationMatrix(
  56592. new Matrix4().lookAt( position, target, new Vector3( 0, 0, 1 ) )
  56593. );
  56594. this.setRotationFromQuaternion(quat);
  56595. this.position.copy(position);
  56596. let coneLength = (this.light.distance > 0) ? this.light.distance : 1000;
  56597. let coneWidth = coneLength * Math.tan( this.light.angle * 0.5 );
  56598. this.frustum.scale.set(coneWidth, coneWidth, coneLength);
  56599. }
  56600. }
  56601. class History extends EventDispatcher{
  56602. constructor(o){
  56603. super();
  56604. this.undoList = [];
  56605. this.redoList = [];
  56606. this.applyData = o.applyData; //应用数据的方法
  56607. this.getData = o.getData; //获取数据的方法
  56608. this.dataBefore;
  56609. }
  56610. undo(){//回退
  56611. let length = this.undoList.length;
  56612. if(length>0){
  56613. let last = this.undoList.pop();
  56614. this.applyData && this.applyData(last.before);
  56615. this.redoList.push(last);
  56616. this.dispatchEvent('undo');
  56617. //console.log('undo',last)
  56618. }
  56619. }
  56620. redo(){//撤销回退
  56621. let length = this.undoList.length;
  56622. let last = this.redoList.pop();
  56623. if(last){
  56624. //注意:每行的顺序不能乱
  56625. this.undoList.push(last);
  56626. this.applyData && this.applyData(last.after);
  56627. this.dispatchEvent('redo');
  56628. //console.log('redo',last)
  56629. }
  56630. }
  56631. beforeChange(o){//在变化之前(可能执行好几次直到变化完,但只有第一次有效)。 o的内容完全根据getData怎么定义
  56632. if(!this.dataBefore){
  56633. let data = this.getData(o);
  56634. this.dataBefore = data;
  56635. }
  56636. }
  56637. afterChange(o){//变化结束,从beforeChange到此算一次操作。
  56638. if(this.dataBefore){
  56639. this.writeIn({before:this.dataBefore, after:this.getData(o)} ); //写入某物体变化前和变化后的状态
  56640. this.dataBefore = null;
  56641. }
  56642. }
  56643. writeIn(data ){
  56644. this.redoList.length = 0; //一旦录入新的操作,就不允许undo了
  56645. this.undoList.push(data );
  56646. //console.log('新增undo', data)
  56647. }
  56648. clear(){
  56649. this.redoList.length = 0;
  56650. this.undoList.length = 0;
  56651. this.dataBefore = null;
  56652. }
  56653. }
  56654. //问题:如何转换到世界坐标?(缩放方向有bug。)
  56655. //add-------------------------------------
  56656. const OpaWhenNotSelect = 0.6;
  56657. const ScaleRatio = 3;
  56658. const OutlineColor = 0x666666;
  56659. //----------------------------------------
  56660. const hideFocusHandles = true;//add
  56661. class TransformationTool extends EventDispatcher{
  56662. constructor(viewer ) {
  56663. super();
  56664. this.viewer = viewer;
  56665. this.modesEnabled = {};//add
  56666. this.style = 'singleMode'; //建mesh时按照singleModes建的
  56667. this.scene = new Scene();
  56668. this.selection = [];
  56669. this.pivot = new Vector3();
  56670. this.dragging = false;
  56671. this.showPickVolumes = false;
  56672. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  56673. this.viewer.inputHandler.addEventListener('selection_changed', (e) => {
  56674. /* for(let selected of this.selection){ //若不删除,应该会穿过选中的物体选到别的而不是取消选择
  56675. this.viewer.inputHandler.blacklist.delete(selected);
  56676. } */
  56677. this.selection = e.selection;
  56678. /* for(let selected of this.selection){
  56679. this.viewer.inputHandler.blacklist.add(selected);
  56680. } */
  56681. });
  56682. this.viewer.addEventListener('global_touchstart',(e)=>{ //add
  56683. this.update();
  56684. });
  56685. this.viewer.addEventListener('global_mousemove',(e)=>{ //add
  56686. this.onPointerMove();
  56687. });
  56688. let red = Potree.config.axis.x.color;
  56689. let green = Potree.config.axis.y.color;
  56690. let blue = Potree.config.axis.z.color;
  56691. let white = Potree.config.axis.xyz.color;
  56692. this.activeHandle = null;
  56693. this.scaleHandles = {
  56694. "scale.x+": {name: "scale.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0]},
  56695. "scale.x-": {name: "scale.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0]},
  56696. "scale.y+": {name: "scale.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0]},
  56697. "scale.y-": {name: "scale.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0]},
  56698. "scale.z+": {name: "scale.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1]},
  56699. "scale.z-": {name: "scale.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1]},
  56700. "lines": {name:'lines', node: new Object3D(), dontScale:true }//add
  56701. };
  56702. this.focusHandles = {
  56703. "focus.x+": {name: "focus.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0]},
  56704. "focus.x-": {name: "focus.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0]},
  56705. "focus.y+": {name: "focus.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0]},
  56706. "focus.y-": {name: "focus.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0]},
  56707. "focus.z+": {name: "focus.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1]},
  56708. "focus.z-": {name: "focus.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1]},
  56709. };
  56710. this.translationHandles = {
  56711. "translation.x": {name: "translation.x", node: new Object3D(), color: red, alignment: [1, 0, 0]},
  56712. "translation.y": {name: "translation.y", node: new Object3D(), color: green, alignment: [0, 1, 0]},
  56713. "translation.z": {name: "translation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1]},
  56714. //add
  56715. 'translation.xyz':{name: "translation.xyz", node: new Object3D(),color: white, alignment: [0, 0, 0], alignment2: [1, 1, 1]},
  56716. 'translation.plane.xy':{name: "translation.plane.xy", node: new Object3D(),color: blue,alignment: [0, 0, 1], alignment2: [1, 1, 0]},
  56717. 'translation.plane.yz':{name: "translation.plane.yz", node: new Object3D(),color: red, alignment: [1, 0, 0], alignment2: [0, 1, 1]},
  56718. 'translation.plane.xz':{name: "translation.plane.xz", node: new Object3D(),color: green, alignment: [0, 1, 0], alignment2: [1, 0, 1]},
  56719. };
  56720. this.rotationHandles = {
  56721. "rotation.x": {name: "rotation.x", node: new Object3D(), color: red, alignment: [1, 0, 0]},
  56722. "rotation.y": {name: "rotation.y", node: new Object3D(), color: green, alignment: [0, 1, 0]},
  56723. "rotation.z": {name: "rotation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1]},
  56724. };
  56725. this.handles = Object.assign({}, this.scaleHandles, hideFocusHandles?{}:this.focusHandles, this.translationHandles, this.rotationHandles);
  56726. this.pickVolumes = [];
  56727. this.initializeScaleHandles();
  56728. this.initializeFocusHandles();
  56729. this.initializeTranslationHandles();
  56730. this.initializeRotationHandles();
  56731. let boxFrameGeometry = new Geometry();
  56732. {
  56733. // bottom
  56734. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  56735. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  56736. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  56737. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  56738. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  56739. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  56740. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  56741. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  56742. // top
  56743. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  56744. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  56745. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  56746. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  56747. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  56748. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  56749. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  56750. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  56751. // sides
  56752. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  56753. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  56754. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  56755. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  56756. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  56757. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  56758. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  56759. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  56760. }
  56761. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({color: 0xffff00}));
  56762. this.scene.add(this.frame);
  56763. //------------------add-----------------------
  56764. this.setModeEnable(['scale','translation','rotation']);
  56765. Potree.Utils.setObjectLayers(this.scene, 'transformationTool' );
  56766. this.scene.traverse(e=>{
  56767. e.pickDontCheckDis = true; //pick时不需要识别是否在点云之上
  56768. });
  56769. {
  56770. let exist = (object)=>{//是否没被删除(暂时不考虑换了parent)
  56771. while(object.parent){
  56772. object = object.parent;
  56773. }
  56774. if(object instanceof Scene){
  56775. return true
  56776. }
  56777. };
  56778. this.history = new History({ //也可以写到全局,但需要加个判断物品是否存在的函数
  56779. applyData: (data)=>{
  56780. if(exist(data.object)){//viewer.scene.volumes.includes(data.box) //或许还要识别是否matrixAuto
  56781. data.matrix.decompose( data.object.position, data.object.quaternion, data.object.scale );
  56782. }else {
  56783. this.history.undo();//找不到就回退下一个。(直接写这?)
  56784. }
  56785. } ,
  56786. getData:(data)=>{
  56787. return data
  56788. }
  56789. });
  56790. this.addEventListener('transformed', (e)=>{
  56791. let object = viewer.transformationTool.selection[0];
  56792. this.history.beforeChange({object, matrix:e.matrixBefore.clone()} );
  56793. this.viewer.dispatchEvent('content_changed');
  56794. });
  56795. this.addEventListener('stopDrag', (e)=>{
  56796. let object = viewer.transformationTool.selection[0];
  56797. object && this.history.afterChange({object, matrix:object.matrix.clone()} );
  56798. });
  56799. viewer.inputHandler.addEventListener('keydown', (e)=>{
  56800. if(e.keyCode == 90 && e.event.ctrlKey){//Z
  56801. this.history.undo();
  56802. }else if(e.keyCode == 89 && e.event.ctrlKey){//Y
  56803. this.history.redo();
  56804. }
  56805. });
  56806. }
  56807. }
  56808. setModeEnable(enableModes=[] ){//xzw add
  56809. let length=0;
  56810. ['translation','scale','rotation'].forEach(mode=>{
  56811. let handels = this[mode + 'Handles'];
  56812. let enable = enableModes.includes(mode);
  56813. for(let o in handels){
  56814. Potree.Utils.updateVisible(handels[o].node,'modeForce', !!enable);
  56815. }
  56816. this.modesEnabled[mode] = !!enable;
  56817. enable && length++;
  56818. });
  56819. if(this.style == 'singleMode' && length > 1){
  56820. this.changeStyle('mixedModes');
  56821. }else if(this.style == 'mixedModes' && length == 1){
  56822. this.changeStyle('singleMode');
  56823. }
  56824. }
  56825. changeStyle(style){// 切换单个mode & 多个mode混合 风格(因多个混合比较拥挤,需要做调整)
  56826. ['x','y','z'].forEach(axis=>{
  56827. this.translationHandles['translation.'+axis].node.children.forEach(mesh=>{
  56828. if(mesh.name.includes('arrow')){
  56829. Potree.Utils.updateVisible(mesh, 'modeStyle', style == 'singleMode');
  56830. }else if(mesh.name.includes('handle')){
  56831. mesh.material.lineWidth = style == 'singleMode' ? 5 : 8;
  56832. }
  56833. });
  56834. });
  56835. ['xy','yz','xz'].forEach(axis=>{
  56836. let handle = this.translationHandles['translation.plane.'+axis];
  56837. let s = style == 'singleMode' ? 15 : 12;
  56838. handle.node.children[0].scale.set(s,s,s);
  56839. handle.node.children[0].position.fromArray(handle.alignment2).multiplyScalar(s*1.5);
  56840. });
  56841. Potree.Utils.updateVisible(this.scaleHandles['lines'].node, 'modeStyle', style == 'singleMode');
  56842. this.style = style;
  56843. }
  56844. initializeTranslationHandles(){//大改
  56845. let boxGeometry = new BoxGeometry(1, 1, 1);
  56846. let length = 100 , arrowRadius = 4, arrowHeight = 10;
  56847. let arrowGeometry = new CylinderBufferGeometry( 0, arrowRadius, arrowHeight, 12, 1, false );//add 箭头朝(0,1,0)
  56848. let arrowInitialQua = new Quaternion().setFromAxisAngle(new Vector3(1,0,0), -Math.PI/2 );//先将qua旋转到朝向0,0,-1, 因为一般quaternion不设置时默认表示朝向0,0,-1,
  56849. let octahedronGeometry = new OctahedronBufferGeometry( 5, 0 );
  56850. let planeGeometry = new PlaneBufferGeometry( 1, 1 );
  56851. for(let handleName of Object.keys(this.translationHandles)){
  56852. let handle = this.handles[handleName];
  56853. let node = handle.node;
  56854. this.scene.add(node);
  56855. node.name = handleName;//add
  56856. let alignment = new Vector3(...handle.alignment);
  56857. let geometry , mesh, pickVolume, meshScale, pickScale, rotation, position, lookAtPoint, hasPick = true, meshPickable = false, renderOrder;
  56858. let matProp = {
  56859. color: handle.color,
  56860. opacity: OpaWhenNotSelect,
  56861. transparent: true,
  56862. side: handleName.includes('plane') ? DoubleSide : FrontSide
  56863. };
  56864. let material = new MeshBasicMaterial(matProp);
  56865. let pickMaterial = new MeshNormalMaterial({
  56866. opacity: 0.2,
  56867. transparent: true,
  56868. visible: this.showPickVolumes
  56869. });
  56870. if(handleName.includes('xyz') ){
  56871. geometry = octahedronGeometry;
  56872. meshPickable = true;
  56873. renderOrder = 12;
  56874. }else if(handleName.includes('plane') ){
  56875. geometry = planeGeometry;
  56876. meshPickable = true;
  56877. position = new Vector3(...handle.alignment2);
  56878. lookAtPoint = alignment;
  56879. if(handleName.includes('xy') ) {
  56880. }else if(handleName.includes('yz')){
  56881. }else if(handleName.includes('xz')){
  56882. }
  56883. }else {
  56884. geometry = boxGeometry;
  56885. let point = new Vector3(0,0,length/2);//new THREE.Vector3().copy(alignment).multiplyScalar(length/2)
  56886. mesh = LineDraw.createFatLine([point, point.clone().negate()],{lineWidth:5, mat : new LineDraw.createFatLineMat(matProp)});
  56887. lookAtPoint = alignment;
  56888. renderOrder = 10;
  56889. pickScale = new Vector3(4, 4, length+arrowHeight*2); //pickScale = new THREE.Vector3(4, 4, 1.2)
  56890. {
  56891. let arrow = new Mesh(arrowGeometry, material);
  56892. arrow.name = `${handleName}.arrow`;
  56893. arrow.renderOrder = 11;
  56894. arrow.position.set( ...handle.alignment).multiplyScalar(length/2+arrowHeight/2);
  56895. arrow.lookAt(0,0,0);
  56896. node.add(arrow);
  56897. let arrow2 = arrow.clone();
  56898. arrow2.position.negate();
  56899. arrow2.lookAt(0,0,0);
  56900. node.add(arrow2);
  56901. arrow.quaternion.multiply(arrowInitialQua); //乘上初始旋转
  56902. arrow2.quaternion.multiply(arrowInitialQua);
  56903. }
  56904. }
  56905. mesh || (mesh = new Mesh(geometry,material));
  56906. mesh.name = `${handleName}.handle`;
  56907. node.add(mesh);
  56908. renderOrder && (mesh.renderOrder = renderOrder);
  56909. meshScale && mesh.scale.copy(meshScale);
  56910. rotation && mesh.rotation.copy(rotation);
  56911. lookAtPoint && mesh.lookAt(lookAtPoint);
  56912. position && mesh.position.copy(position);
  56913. if(!meshPickable && hasPick){
  56914. pickVolume = new Mesh(geometry, pickMaterial);
  56915. pickScale && pickVolume.scale.copy(pickScale);
  56916. }else if(hasPick && meshPickable){
  56917. pickVolume = mesh;
  56918. }
  56919. if(pickVolume){
  56920. if(mesh != pickVolume){
  56921. mesh.add(pickVolume);
  56922. pickVolume.name = `${handleName}.pick_volume`;
  56923. }else {
  56924. pickVolume.name += ' & pick_volume';
  56925. }
  56926. pickVolume.handle = handleName;
  56927. this.pickVolumes.push(pickVolume);
  56928. }
  56929. node.setOpacity = (target) => {
  56930. if(handleName.includes('plane')){
  56931. let more = 1.5; //减掉更多,使min更低,max还是1
  56932. target = 1 - (1-target)*more;
  56933. }
  56934. let opacity = {x: material.opacity};
  56935. let t = new TWEEN.Tween(opacity).to({x: target}, 0);
  56936. t.onUpdate(() => {
  56937. mesh.visible = opacity.x > 0;
  56938. pickVolume && (pickVolume.visible = opacity.x > 0);
  56939. material.opacity = opacity.x;
  56940. mesh.material.opacity = opacity.x;
  56941. //outlineMaterial.opacity = opacity.x;
  56942. pickMaterial.opacity = opacity.x * 0.5;
  56943. });
  56944. t.start();
  56945. };
  56946. pickVolume.addEventListener("drag", (e) => {this.dragTranslationHandle(e);});
  56947. pickVolume.addEventListener("drop", (e) => {this.dropTranslationHandle(e);});
  56948. }
  56949. }
  56950. initializeScaleHandles(){
  56951. let sgSphere = new SphereGeometry(1, 32, 32);
  56952. let sgLowPolySphere = new SphereGeometry(1, 16, 16);
  56953. for(let handleName of Object.keys(this.scaleHandles)){
  56954. let handle = this.scaleHandles[handleName];
  56955. let node = handle.node;
  56956. node.name = handleName;//add
  56957. this.scene.add(node);
  56958. if(handleName == 'lines'){ //add
  56959. ['x','y','z'].forEach(axis=>{
  56960. let handle1_ = this.scaleHandles['scale.'+axis+'+'];
  56961. let handle2_ = this.scaleHandles['scale.'+axis+'-'];
  56962. let line = LineDraw.createFatLine([
  56963. new Vector3().fromArray(handle1_.alignment).multiplyScalar(0.5),
  56964. new Vector3().fromArray(handle2_.alignment).multiplyScalar(0.5) ],
  56965. {color:handle1_.color, lineWidth:4} // , dontAlwaysSeen:true
  56966. );
  56967. node.add(line);
  56968. });
  56969. node.setOpacity = (opacity) => {
  56970. opacity *= 0.6;
  56971. node.children.forEach(e=>e.material.opacity = opacity);
  56972. };
  56973. continue;
  56974. }
  56975. node.position.set(...handle.alignment).multiplyScalar(0.5);
  56976. let material = new MeshBasicMaterial({
  56977. color: handle.color,
  56978. side:DoubleSide,//xzw add
  56979. opacity: OpaWhenNotSelect,
  56980. transparent: true
  56981. });
  56982. let outlineMaterial = new MeshBasicMaterial({
  56983. color: OutlineColor,
  56984. side: BackSide,
  56985. opacity: OpaWhenNotSelect,
  56986. transparent: true});
  56987. let pickMaterial = new MeshNormalMaterial({
  56988. opacity: 0.2,
  56989. transparent: true,
  56990. side:DoubleSide,//xzw add for orthoCam, 缩小画面时因球体放大导致到相机背面去了而看不到球体正面
  56991. visible: this.showPickVolumes});
  56992. let sphere = new Mesh(sgSphere, material);
  56993. sphere.scale.set(5, 5, 5 );
  56994. sphere.name = `${handleName}.handle`;
  56995. node.add(sphere);
  56996. sphere.renderOrder = 10;
  56997. /* let outline = new THREE.Mesh(sgSphere, outlineMaterial);
  56998. outline.scale.set(1.1, 1.1, 1.1);
  56999. outline.name = `${handleName}.outline`;
  57000. sphere.add(outline); */
  57001. let pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  57002. pickSphere.name = `${handleName}.pick_volume`;
  57003. pickSphere.scale.set(1.5, 1.5, 1.5);
  57004. sphere.add(pickSphere);
  57005. pickSphere.handle = handleName;
  57006. this.pickVolumes.push(pickSphere);
  57007. node.setOpacity = (target) => {
  57008. let opacity = {x: material.opacity};
  57009. let t = new TWEEN.Tween(opacity).to({x: target}, 0); //xzw改 原100毫秒,因为太慢容易选错
  57010. t.onUpdate(() => {
  57011. sphere.visible = opacity.x > 0;
  57012. pickSphere.visible = opacity.x > 0;
  57013. material.opacity = opacity.x;
  57014. outlineMaterial.opacity = opacity.x;
  57015. pickSphere.material.opacity = opacity.x * 0.5;
  57016. });
  57017. t.start();
  57018. };
  57019. pickSphere.addEventListener("drag", (e) => this.dragScaleHandle(e));
  57020. pickSphere.addEventListener("drop", (e) => this.dropScaleHandle(e));
  57021. pickSphere.addEventListener("mouseover", e => {
  57022. //node.setOpacity(1);
  57023. });
  57024. pickSphere.addEventListener("click", e => {
  57025. //e.consume();
  57026. });
  57027. pickSphere.addEventListener("mouseleave", e => {
  57028. //node.setOpacity(OpaWhenNotSelect);
  57029. });
  57030. }
  57031. }
  57032. initializeRotationHandles(){
  57033. let boldAdjust = 2.5;
  57034. let torusGeometry = new TorusGeometry(1.4, boldAdjust * 0.015, 8, 64, Math.PI / 2);
  57035. //let outlineGeometry = new THREE.TorusGeometry(1, boldAdjust * 0.018, 8, 64, Math.PI / 2);
  57036. let pickGeometry = new TorusGeometry(1.4, boldAdjust * 0.06, 6, 4, Math.PI / 2);
  57037. for(let handleName of Object.keys(this.rotationHandles)){
  57038. let handle = this.handles[handleName];
  57039. let node = handle.node;
  57040. this.scene.add(node);
  57041. node.name = handleName;//add
  57042. let material = new MeshBasicMaterial({
  57043. color: handle.color,
  57044. opacity: OpaWhenNotSelect,
  57045. transparent: true
  57046. });
  57047. /* let outlineMaterial = new THREE.MeshBasicMaterial({
  57048. color: OutlineColor,
  57049. side: THREE.BackSide,
  57050. opacity: OpaWhenNotSelect,
  57051. transparent: true
  57052. }); */
  57053. let pickMaterial = new MeshNormalMaterial({
  57054. opacity: 0.2,
  57055. transparent: true,
  57056. visible: this.showPickVolumes
  57057. });
  57058. let box = new Mesh(torusGeometry, material);
  57059. box.name = `${handleName}.handle`;
  57060. box.scale.set(30, 30, 30);
  57061. box.lookAt(new Vector3(...handle.alignment));
  57062. node.add(box);
  57063. handle.translateNode = box;
  57064. /* let outline = new THREE.Mesh(outlineGeometry, outlineMaterial);
  57065. outline.name = `${handleName}.outline`;
  57066. outline.scale.set(1, 1, 1);
  57067. outline.renderOrder = 0;
  57068. box.add(outline);
  57069. */
  57070. let pickVolume = new Mesh(pickGeometry, pickMaterial);
  57071. pickVolume.name = `${handleName}.pick_volume`;
  57072. pickVolume.scale.set(1, 1, 1);
  57073. pickVolume.handle = handleName;
  57074. box.add(pickVolume);
  57075. this.pickVolumes.push(pickVolume);
  57076. node.setOpacity = (target) => {
  57077. let opacity = {x: material.opacity};
  57078. let t = new TWEEN.Tween(opacity).to({x: target}, 0);
  57079. t.onUpdate(() => {
  57080. box.visible = opacity.x > 0;
  57081. pickVolume.visible = opacity.x > 0;
  57082. material.opacity = opacity.x;
  57083. //outlineMaterial.opacity = opacity.x;
  57084. pickMaterial.opacity = opacity.x * 0.5;
  57085. });
  57086. t.start();
  57087. };
  57088. //pickVolume.addEventListener("mouseover", (e) => {
  57089. // //let a = this.viewer.scene.getActiveCamera().getWorldDirection(new THREE.Vector3()).dot(pickVolume.getWorldDirection(new THREE.Vector3()));
  57090. // console.log(pickVolume.getWorldDirection(new THREE.Vector3()));
  57091. //});
  57092. pickVolume.addEventListener("drag", (e) => {this.dragRotationHandle(e);});
  57093. pickVolume.addEventListener("drop", (e) => {this.dropRotationHandle(e);});
  57094. }
  57095. }
  57096. initializeFocusHandles(){
  57097. if(hideFocusHandles)return//add
  57098. //let sgBox = new THREE.BoxGeometry(1, 1, 1);
  57099. let sgPlane = new PlaneGeometry(4, 4, 1, 1);
  57100. let sgLowPolySphere = new SphereGeometry(1, 16, 16);
  57101. let texture = new TextureLoader().load(`${exports.resourcePath}/icons/eye_2.png`);
  57102. for(let handleName of Object.keys(this.focusHandles)){
  57103. let handle = this.focusHandles[handleName];
  57104. let node = handle.node;
  57105. this.scene.add(node);
  57106. let align = handle.alignment;
  57107. node.name = handleName;//add
  57108. //node.lookAt(new THREE.Vector3().addVectors(node.position, new THREE.Vector3(...align)));
  57109. node.lookAt(new Vector3(...align));
  57110. let off = 0.8;
  57111. if(align[0] === 1){
  57112. node.position.set(1, off, -off).multiplyScalar(0.5);
  57113. node.rotation.z = Math.PI / 2;
  57114. }else if(align[0] === -1){
  57115. node.position.set(-1, -off, -off).multiplyScalar(0.5);
  57116. node.rotation.z = Math.PI / 2;
  57117. }else if(align[1] === 1){
  57118. node.position.set(-off, 1, -off).multiplyScalar(0.5);
  57119. node.rotation.set(Math.PI / 2, Math.PI, 0.0);
  57120. }else if(align[1] === -1){
  57121. node.position.set(off, -1, -off).multiplyScalar(0.5);
  57122. node.rotation.set(Math.PI / 2, 0.0, 0.0);
  57123. }else if(align[2] === 1){
  57124. node.position.set(off, off, 1).multiplyScalar(0.5);
  57125. }else if(align[2] === -1){
  57126. node.position.set(-off, off, -1).multiplyScalar(0.5);
  57127. }
  57128. let material = new MeshBasicMaterial({
  57129. color: handle.color,
  57130. opacity: 0,
  57131. transparent: true,
  57132. map: texture
  57133. });
  57134. //let outlineMaterial = new THREE.MeshBasicMaterial({
  57135. // color: 0x000000,
  57136. // side: THREE.BackSide,
  57137. // opacity: 0,
  57138. // transparent: true});
  57139. let pickMaterial = new MeshNormalMaterial({
  57140. //opacity: 0,
  57141. transparent: true,
  57142. visible: this.showPickVolumes});
  57143. let box = new Mesh(sgPlane, material);
  57144. box.name = `${handleName}.handle`;
  57145. box.scale.set(1.5, 1.5, 1.5);
  57146. box.position.set(0, 0, 0);
  57147. box.visible = false;
  57148. node.add(box);
  57149. //handle.focusNode = box;
  57150. //let outline = new THREE.Mesh(sgPlane, outlineMaterial);
  57151. //outline.scale.set(1.4, 1.4, 1.4);
  57152. //outline.name = `${handleName}.outline`;
  57153. //box.add(outline);
  57154. let pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  57155. pickSphere.name = `${handleName}.pick_volume`;
  57156. pickSphere.scale.set(2, 2, 2);
  57157. box.add(pickSphere);
  57158. pickSphere.handle = handleName;
  57159. this.pickVolumes.push(pickSphere);
  57160. node.setOpacity = (target) => {
  57161. let opacity = {x: material.opacity};
  57162. let t = new TWEEN.Tween(opacity).to({x: target}, 0);
  57163. t.onUpdate(() => {
  57164. pickSphere.visible = opacity.x > 0;
  57165. box.visible = opacity.x > 0;
  57166. material.opacity = opacity.x;
  57167. //outlineMaterial.opacity = opacity.x;
  57168. pickSphere.material.opacity = opacity.x * 0.5;
  57169. });
  57170. t.start();
  57171. };
  57172. //pickSphere.addEventListener("drag", e => {});
  57173. pickSphere.addEventListener("mouseup", e => {
  57174. //e.consume();
  57175. });
  57176. pickSphere.addEventListener("mousedown", e => {
  57177. //e.consume();
  57178. });
  57179. pickSphere.addEventListener("click", e => {
  57180. //e.consume();
  57181. let selected = this.selection[0];
  57182. let maxScale = Math.max(...selected.scale.toArray());
  57183. let minScale = Math.min(...selected.scale.toArray());
  57184. let handleLength = Math.abs(selected.scale.dot(new Vector3(...handle.alignment)));
  57185. let alignment = new Vector3(...handle.alignment).multiplyScalar(2 * maxScale / handleLength);
  57186. alignment.applyMatrix4(selected.matrixWorld);
  57187. let newCamPos = alignment;
  57188. let newCamTarget = selected.getWorldPosition(new Vector3());
  57189. Utils.moveTo(this.viewer.scene, newCamPos, newCamTarget);
  57190. });
  57191. pickSphere.addEventListener("mouseover", e => {
  57192. //box.setOpacity(1);
  57193. });
  57194. pickSphere.addEventListener("mouseleave", e => {
  57195. //box.setOpacity(OpaWhenNotSelect);
  57196. });
  57197. }
  57198. }
  57199. dragRotationHandle(e){
  57200. let drag = e.drag;
  57201. let handle = this.activeHandle;
  57202. let camera = this.viewer.mainViewport.camera;//this.viewer.scene.getActiveCamera();
  57203. if(!handle){
  57204. return
  57205. };
  57206. let localNormal = new Vector3(...handle.alignment);
  57207. let n = new Vector3();
  57208. n.copy(new Vector4(...localNormal.toArray(), 0).applyMatrix4(handle.node.matrixWorld));
  57209. n.normalize();
  57210. if (!drag.intersectionStart){
  57211. //this.viewer.scene.scene.remove(this.debug);
  57212. //this.debug = new THREE.Object3D();
  57213. //this.viewer.scene.scene.add(this.debug);
  57214. //Utils.debugSphere(this.debug, drag.location, 3, 0xaaaaaa);
  57215. //let debugEnd = drag.location.clone().add(n.clone().multiplyScalar(20));
  57216. //Utils.debugLine(this.debug, drag.location, debugEnd, 0xff0000);
  57217. drag.intersectionStart = drag.location;
  57218. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  57219. drag.handle = handle;
  57220. let plane = new Plane().setFromNormalAndCoplanarPoint(n, drag.intersectionStart);
  57221. drag.dragPlane = plane;
  57222. drag.pivot = drag.intersectionStart;
  57223. }else {
  57224. handle = drag.handle;
  57225. }
  57226. if(!drag.dragPlane)return//xzw add 因有时候没有
  57227. this.dragging = true;
  57228. let pointer = this.viewer.inputHandler.pointer;
  57229. let domElement = this.viewer.renderer.domElement;
  57230. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  57231. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  57232. if (I) {
  57233. let center = this.scene.getWorldPosition(new Vector3());
  57234. let from = drag.pivot;
  57235. let to = I;
  57236. let v1 = from.clone().sub(center).normalize();
  57237. let v2 = to.clone().sub(center).normalize();
  57238. let angle = Math.acos(v1.dot(v2));
  57239. let sign = Math.sign(v1.cross(v2).dot(n));
  57240. angle = angle * sign;
  57241. if (Number.isNaN(angle)) {
  57242. return;
  57243. }
  57244. let matrixBefore = this.selection[0].matrix.clone();
  57245. let normal = new Vector3(...handle.alignment);
  57246. for (let selection of this.selection) {
  57247. selection.rotateOnAxis(normal, angle);
  57248. selection.dispatchEvent({
  57249. type: "orientation_changed",
  57250. object: selection
  57251. });
  57252. }
  57253. this.dispatchEvent({type:'transformed', changeType: ['orientation'], matrixBefore });//add
  57254. drag.pivot = I;
  57255. }
  57256. }
  57257. dropRotationHandle(e){
  57258. this.dragging = false;
  57259. this.setActiveHandle(null);
  57260. this.dispatchEvent({type:'stopDrag', handle:'rotation'});//add
  57261. }
  57262. dragTranslationHandle(e){//---大改,参考transformControls,为了加上xyz xy yz xz 这四个方向的变换。 (但感觉好像plane上有丢丢延迟?是因为drag延迟还是worldmatrix没更新)
  57263. let drag = e.drag;
  57264. let handle = this.activeHandle;
  57265. let camera = this.viewer.mainViewport.camera;//this.viewer.scene.getActiveCamera();
  57266. if(handle && this.selection[0]){
  57267. let posWorld = this.selection[0].getWorldPosition(new Vector3()); //是需要世界坐标吗
  57268. if(!drag.intersectionStart){
  57269. drag.intersectionStart = drag.location;
  57270. drag.worldPositionStart = posWorld;
  57271. drag.objectQua = this.selection[0].quaternion.clone();//不考虑父级
  57272. drag.objectQuaInv = drag.objectQua.clone().invert();
  57273. this.dragging = true;
  57274. }
  57275. if(drag.intersectionStart){
  57276. let pointer = this.viewer.inputHandler.pointer;
  57277. let ray = Utils.mouseToRay(pointer, camera);
  57278. let normal = viewer.mainViewport.view.direction;
  57279. drag.dragPlane = new Plane().setFromNormalAndCoplanarPoint(normal, posWorld/* drag.worldPositionStart */);//过center的与视线垂直的平面
  57280. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  57281. if (I) {
  57282. let offset = new Vector3().subVectors( I , drag.worldPositionStart );
  57283. //let offset = new THREE.Vector3().subVectors(iOnLine, drag.worldPositionStart);
  57284. if(!drag.pointStart){
  57285. drag.pointStart = offset;
  57286. }else {
  57287. drag.pointEnd = offset;
  57288. let diff = new Vector3().subVectors(drag.pointEnd, drag.pointStart);
  57289. diff.applyQuaternion(drag.objectQuaInv); // 得到在该物体local空间上的offset
  57290. if(!handle.name.includes('x')) diff.x = 0;
  57291. if(!handle.name.includes('y')) diff.y = 0;
  57292. if(!handle.name.includes('z')) diff.z = 0;
  57293. //恢复为world offset
  57294. diff.applyQuaternion(drag.objectQua);
  57295. //-------------
  57296. let matrixBefore = this.selection[0].matrix.clone();
  57297. this.selection[0].position.copy( diff ).add( drag.worldPositionStart );
  57298. for (let selection of this.selection) {
  57299. selection.dispatchEvent({
  57300. type: "position_changed",
  57301. object: selection
  57302. });
  57303. }
  57304. this.dispatchEvent({type:'transformed', changeType: ['position'], matrixBefore});//add
  57305. }
  57306. }
  57307. }
  57308. }
  57309. }
  57310. dropTranslationHandle(e){
  57311. this.dragging = false;
  57312. this.setActiveHandle(null);
  57313. this.dispatchEvent({type:'stopDrag', handle:'translation'});//add
  57314. }
  57315. dropScaleHandle(e){
  57316. this.dragging = false;
  57317. this.setActiveHandle(null);
  57318. this.dispatchEvent({type:'stopDrag', handle:'scale'});//add
  57319. }
  57320. dragScaleHandle(e){
  57321. let drag = e.drag;
  57322. let handle = this.activeHandle;
  57323. if(!handle)return
  57324. let camera = this.viewer.mainViewport.camera;//this.viewer.scene.getActiveCamera();
  57325. if(!drag.intersectionStart){
  57326. drag.intersectionStart = drag.location;
  57327. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  57328. drag.handle = handle;
  57329. let start = drag.intersectionStart;
  57330. let dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld);
  57331. let end = new Vector3().addVectors(start, dir);
  57332. let line = new Line3(start.clone(), end.clone());
  57333. drag.line = line;
  57334. let normal;
  57335. if(camera.type == 'OrthographicCamera'){//xzw add
  57336. normal = new Vector3(0,0,-1).applyQuaternion(camera.quaternion);
  57337. }else {
  57338. let camOnLine = line.closestPointToPoint(camera.position, false, new Vector3());
  57339. normal = new Vector3().subVectors(camera.position, camOnLine);
  57340. }
  57341. let plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart); //过轴线的一个能铺满屏幕的平面
  57342. drag.dragPlane = plane;
  57343. drag.pivot = drag.intersectionStart;
  57344. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  57345. }else {
  57346. handle = drag.handle;
  57347. }
  57348. this.dragging = true;
  57349. if(drag.dragPlane){//xzw add 因有时候没有
  57350. let pointer = this.viewer.inputHandler.pointer;
  57351. let domElement = this.viewer.renderer.domElement;
  57352. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  57353. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  57354. if (I) {
  57355. let iOnLine = drag.line.closestPointToPoint(I, false, new Vector3());
  57356. let direction = handle.alignment.reduce( (a, v) => a + v, 0);
  57357. let toObjectSpace = this.selection[0].matrixWorld.clone().invert();
  57358. let iOnLineOS = iOnLine.clone().applyMatrix4(toObjectSpace);
  57359. let pivotOS = drag.pivot.clone().applyMatrix4(toObjectSpace);
  57360. let diffOS = new Vector3().subVectors(iOnLineOS, pivotOS);
  57361. let dragDirectionOS = diffOS.clone().normalize();
  57362. if(iOnLine.distanceTo(drag.pivot) === 0){
  57363. dragDirectionOS.set(0, 0, 0);
  57364. }
  57365. let dragDirection = dragDirectionOS.dot(new Vector3(...handle.alignment));
  57366. let diff = new Vector3().subVectors(iOnLine, drag.pivot);
  57367. let diffScale = new Vector3(...handle.alignment).multiplyScalar(diff.length() * direction * dragDirection);
  57368. let diffPosition = diff.clone().multiplyScalar(0.5);
  57369. let matrixBefore = this.selection[0].matrix.clone();
  57370. for (let selection of this.selection) {
  57371. //xzw 改:否则不跟手
  57372. let diffScale_ = diffScale.clone().divide(selection.boundingBox.getSize(new Vector3));
  57373. selection.scale.add(diffScale_);
  57374. //selection.scale.add(diffScale);
  57375. selection.scale.x = Math.max(0.1, selection.scale.x);
  57376. selection.scale.y = Math.max(0.1, selection.scale.y);
  57377. selection.scale.z = Math.max(0.1, selection.scale.z);
  57378. selection.position.add(diffPosition);
  57379. selection.dispatchEvent({
  57380. type: "position_changed",
  57381. object: selection
  57382. });
  57383. selection.dispatchEvent({
  57384. type: "scale_changed",
  57385. object: selection
  57386. });
  57387. this.dispatchEvent({type:'transformed', changeType: ['position','scale'], matrixBefore});//add
  57388. }
  57389. drag.pivot.copy(iOnLine);
  57390. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  57391. }
  57392. }
  57393. }
  57394. setActiveHandle(handle){
  57395. if(this.dragging){
  57396. return;
  57397. }
  57398. if(this.activeHandle === handle){
  57399. return;
  57400. }
  57401. this.activeHandle = handle;
  57402. if(handle === null){
  57403. for(let handleName of Object.keys(this.handles)){
  57404. let handle = this.handles[handleName];
  57405. handle.node.setOpacity(0);
  57406. }
  57407. }
  57408. viewer.dispatchEvent({type:'CursorChange', action: this.activeHandle ? 'add' : 'remove', name:'hoverTranHandle'});
  57409. if(!hideFocusHandles){
  57410. for(let handleName of Object.keys(this.focusHandles)){
  57411. let handle = this.focusHandles[handleName];
  57412. if(this.activeHandle === handle){
  57413. handle.node.setOpacity(1.0);
  57414. }else {
  57415. handle.node.setOpacity(OpaWhenNotSelect);
  57416. }
  57417. }
  57418. }
  57419. for(let handleName of Object.keys(this.translationHandles)){
  57420. let handle = this.translationHandles[handleName];
  57421. if(this.activeHandle === handle){
  57422. handle.node.setOpacity(1.0);
  57423. }else {
  57424. handle.node.setOpacity(OpaWhenNotSelect);
  57425. }
  57426. }
  57427. for(let handleName of Object.keys(this.rotationHandles)){
  57428. let handle = this.rotationHandles[handleName];
  57429. //if(this.activeHandle === handle){
  57430. // handle.node.setOpacity(1.0);
  57431. //}else{
  57432. // handle.node.setOpacity(OpaWhenNotSelect)
  57433. //}
  57434. handle.node.setOpacity(OpaWhenNotSelect);
  57435. }
  57436. for(let handleName of Object.keys(this.scaleHandles)){
  57437. let handle = this.scaleHandles[handleName];
  57438. if(this.activeHandle === handle){
  57439. handle.node.setOpacity(1.0);
  57440. if(!hideFocusHandles){
  57441. let relatedFocusHandle = this.focusHandles[handle.name.replace("scale", "focus")];
  57442. let relatedFocusNode = relatedFocusHandle.node;
  57443. relatedFocusNode.setOpacity(OpaWhenNotSelect);
  57444. }
  57445. for(let translationHandleName of Object.keys(this.translationHandles)){
  57446. let translationHandle = this.translationHandles[translationHandleName];
  57447. translationHandle.node.setOpacity(OpaWhenNotSelect);
  57448. }
  57449. //let relatedTranslationHandle = this.translationHandles[
  57450. // handle.name.replace("scale", "translation").replace(/[+-]/g, "")];
  57451. //let relatedTranslationNode = relatedTranslationHandle.node;
  57452. //relatedTranslationNode.setOpacity(OpaWhenNotSelect);
  57453. }else {
  57454. handle.node.setOpacity(OpaWhenNotSelect);
  57455. }
  57456. }
  57457. if(handle){
  57458. handle.node.setOpacity(1.0);
  57459. }
  57460. viewer.dispatchEvent('content_changed');
  57461. }
  57462. update () {
  57463. if(this.selection.length === 1){
  57464. this.scene.visible = true;
  57465. this.scene.updateMatrix();
  57466. this.scene.updateMatrixWorld();
  57467. let selected = this.selection[0];
  57468. let world = selected.matrixWorld;
  57469. let camera = this.viewer.mainViewport.camera;//this.viewer.scene.getActiveCamera();
  57470. let domElement = this.viewer.renderer.domElement;
  57471. let center = selected.boundingBox.getCenter(new Vector3()).clone().applyMatrix4(selected.matrixWorld);
  57472. this.scene.scale.copy(selected.boundingBox.getSize(new Vector3()).multiply(selected.scale));
  57473. this.scene.position.copy(center);
  57474. this.scene.rotation.copy(selected.rotation); //这里只考虑当前子级的scale rotation
  57475. //如果是世界坐标 (缩放方向有bug。)
  57476. /*
  57477. let boundingBox = selected.boundingBox.clone().applyMatrix4(selected.matrixWorld);
  57478. let center = boundingBox.getCenter(new THREE.Vector3())
  57479. this.scene.position.copy(center);
  57480. this.scene.scale.copy(boundingBox.getSize(new THREE.Vector3()));
  57481. */
  57482. this.scene.updateMatrixWorld();
  57483. {
  57484. // adjust rotation handles
  57485. if(!this.dragging){
  57486. if(this.modesEnabled.rotation || this.modesEnabled.translation){
  57487. let tWorld = this.scene.matrixWorld;
  57488. let tObject = tWorld.clone().invert();
  57489. let camObjectPos = camera.getWorldPosition(new Vector3()).applyMatrix4(tObject);
  57490. if(this.modesEnabled.translation){//add
  57491. ['xy','yz','xz'].forEach(axis=>{
  57492. let handle = this.translationHandles["translation.plane."+axis];
  57493. let pos = handle.node.children[0].position;
  57494. camObjectPos.x && (pos.x = Math.sign(camObjectPos.x) * Math.abs(pos.x));
  57495. camObjectPos.y && (pos.y = Math.sign(camObjectPos.y) * Math.abs(pos.y));
  57496. camObjectPos.z && (pos.z = Math.sign(camObjectPos.z) * Math.abs(pos.z));
  57497. });
  57498. }
  57499. if(this.modesEnabled.rotation){
  57500. let above = camObjectPos.z > 0;
  57501. let below = !above;
  57502. let PI_HALF = Math.PI / 2;
  57503. let x = this.rotationHandles["rotation.x"].node.rotation;
  57504. let y = this.rotationHandles["rotation.y"].node.rotation;
  57505. let z = this.rotationHandles["rotation.z"].node.rotation;
  57506. x.order = "ZYX";
  57507. y.order = "ZYX";
  57508. if(above){
  57509. if(camObjectPos.x > 0 && camObjectPos.y > 0){
  57510. x.x = 1 * PI_HALF;
  57511. y.y = 3 * PI_HALF;
  57512. z.z = 0 * PI_HALF;
  57513. }else if(camObjectPos.x < 0 && camObjectPos.y > 0){
  57514. x.x = 1 * PI_HALF;
  57515. y.y = 2 * PI_HALF;
  57516. z.z = 1 * PI_HALF;
  57517. }else if(camObjectPos.x < 0 && camObjectPos.y < 0){
  57518. x.x = 2 * PI_HALF;
  57519. y.y = 2 * PI_HALF;
  57520. z.z = 2 * PI_HALF;
  57521. }else if(camObjectPos.x > 0 && camObjectPos.y < 0){
  57522. x.x = 2 * PI_HALF;
  57523. y.y = 3 * PI_HALF;
  57524. z.z = 3 * PI_HALF;
  57525. }
  57526. }else if(below){
  57527. if(camObjectPos.x > 0 && camObjectPos.y > 0){
  57528. x.x = 0 * PI_HALF;
  57529. y.y = 0 * PI_HALF;
  57530. z.z = 0 * PI_HALF;
  57531. }else if(camObjectPos.x < 0 && camObjectPos.y > 0){
  57532. x.x = 0 * PI_HALF;
  57533. y.y = 1 * PI_HALF;
  57534. z.z = 1 * PI_HALF;
  57535. }else if(camObjectPos.x < 0 && camObjectPos.y < 0){
  57536. x.x = 3 * PI_HALF;
  57537. y.y = 1 * PI_HALF;
  57538. z.z = 2 * PI_HALF;
  57539. }else if(camObjectPos.x > 0 && camObjectPos.y < 0){
  57540. x.x = 3 * PI_HALF;
  57541. y.y = 0 * PI_HALF;
  57542. z.z = 3 * PI_HALF;
  57543. }
  57544. }
  57545. }
  57546. }
  57547. }
  57548. // adjust scale of components
  57549. for(let handleName of Object.keys(this.handles)){
  57550. let handle = this.handles[handleName];
  57551. let node = handle.node;
  57552. //xzw add:---- -当该轴正对相机时隐藏。(主要针对ortho类型camera。
  57553. if(!Potree.Utils.getObjVisiByReason(node,'modeForce') )continue;
  57554. let alignment = handle.alignment;
  57555. if(alignment && (!handleName.includes('rotation') || camera.type == 'OrthographicCamera')){//旋转的话正常都应该显示
  57556. let normal;
  57557. let dir = new Vector3(...alignment).applyQuaternion(this.scene.quaternion);
  57558. if(camera.type == 'OrthographicCamera'){
  57559. normal = new Vector3(0,0,-1).applyQuaternion(camera.quaternion);
  57560. }else {
  57561. normal = new Vector3().subVectors(center, camera.position).normalize();
  57562. }
  57563. let ifOnLine;
  57564. if(handleName.includes('rotation') || handleName.includes('plane')){ // 旋转轴和视线垂直时隐藏
  57565. ifOnLine = Math.abs(dir.dot(normal)) < 0.1;
  57566. }else {
  57567. ifOnLine = Math.abs(dir.dot(normal)) > 0.995;
  57568. }
  57569. Potree.Utils.updateVisible(node, 'faceToCamHide', !ifOnLine);
  57570. }else {
  57571. Potree.Utils.updateVisible(node, 'faceToCamHide', true);
  57572. }
  57573. if(!node.visible)continue;
  57574. //------------------------------------------------------------------------
  57575. if(handle.dontScale)continue; //add
  57576. let handlePos = node.getWorldPosition(new Vector3());
  57577. let distance = handlePos.distanceTo(camera.position);
  57578. let pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  57579. let ws = node.parent.getWorldScale(new Vector3());
  57580. let s = (ScaleRatio / pr);
  57581. let scale = new Vector3(s, s, s).divide(ws);
  57582. let rot = new Matrix4().makeRotationFromEuler(node.rotation); //需要使用到旋转,所以我把设置scale的移到旋转后了,否则在视图上下旋转的分界线处rotateHandel会被拉长从而闪烁。
  57583. let rotInv = rot.clone().invert();
  57584. scale.applyMatrix4(rotInv);
  57585. scale.x = Math.abs(scale.x);
  57586. scale.y = Math.abs(scale.y);
  57587. scale.z = Math.abs(scale.z);
  57588. node.scale.copy(scale);
  57589. }
  57590. }
  57591. }else {
  57592. this.scene.visible = false;
  57593. }
  57594. }
  57595. onPointerMove(){
  57596. let pointer = this.viewer.inputHandler.pointer;
  57597. let camera = this.viewer.mainViewport.camera;
  57598. if( this.selection.length === 1 && !this.dragging ){ //xzw 添加dragging条件
  57599. let ray = Utils.mouseToRay(pointer, camera );
  57600. let raycaster = new Raycaster(ray.origin, ray.direction);
  57601. raycaster.layers.enableAll();//add
  57602. let pickVolumes = this.pickVolumes.filter(v=>{
  57603. let mode = v.handle.split('.')[0];
  57604. if(!this.modesEnabled[mode])return
  57605. return v.parent.parent.visible //可能被隐藏该轴
  57606. });
  57607. let intersects = raycaster.intersectObjects(pickVolumes, true);
  57608. intersects = intersects.sort(function(a,b){
  57609. let order2 = b.object.renderOrder || 0;
  57610. let order1 = a.object.renderOrder || 0;
  57611. return order2-order1
  57612. }); // 降序
  57613. if(intersects.length > 0){
  57614. let I = intersects[0];
  57615. let handleName = I.object.handle;
  57616. //console.log(handleName)
  57617. this.setActiveHandle(this.handles[handleName]);
  57618. }else {
  57619. this.setActiveHandle(null);
  57620. }
  57621. }
  57622. }
  57623. };
  57624. /*
  57625. note:
  57626. transformationTool.scene会跟随选中物体,其scale就是boundingbox的大小。因此transformationTool.frame这个框也会跟着缩放
  57627. */
  57628. const boxOpacity = {
  57629. hovered : 0.1,
  57630. selected : 0.2
  57631. };
  57632. const LineOpacity = {
  57633. default : 0.6,
  57634. selected: 1,
  57635. };
  57636. const colors = {
  57637. 2: 0x2ee4ce,//0x00ff80, //可见
  57638. 3: 0xffc23b,//0xff3158, //不可见
  57639. 4: 0xffffff, //
  57640. };
  57641. class Volume$1 extends Object3D {
  57642. constructor (args = {}) {
  57643. super();
  57644. if(this.constructor.name === "Volume"){
  57645. console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead.");
  57646. }
  57647. this._clip = args.clip || false;
  57648. this._visible = true;
  57649. //this.showVolumeLabel = true;
  57650. this._modifiable = args.modifiable || true;
  57651. { // event listeners
  57652. this.addEventListener('select', e => {
  57653. //console.log('select')
  57654. this.setSelected(true);
  57655. });
  57656. this.addEventListener('deselect', e => {
  57657. //console.log('deselect')
  57658. this.setSelected(false);
  57659. });
  57660. this.addEventListener('mouseover', e => {
  57661. this.hovered = true;
  57662. this.update();
  57663. });
  57664. this.addEventListener('mouseleave', e => {
  57665. this.hovered = false;
  57666. this.update();
  57667. });
  57668. }
  57669. }
  57670. setSelected(state){//add
  57671. this.selected = !!state;
  57672. this.update();
  57673. }
  57674. get visible(){
  57675. return this._visible;
  57676. }
  57677. set visible(value){
  57678. if(this._visible !== value){
  57679. this._visible = value;
  57680. this.dispatchEvent({type: "visibility_changed", object: this});
  57681. }
  57682. }
  57683. getVolume () {
  57684. console.warn("override this in subclass");
  57685. }
  57686. update () {
  57687. };
  57688. raycast (raycaster, intersects) {
  57689. }
  57690. get clip () {
  57691. return this._clip;
  57692. }
  57693. set clip (value) {
  57694. if(this._clip !== value){
  57695. this._clip = value;
  57696. this.update();
  57697. this.dispatchEvent({
  57698. type: "clip_changed",
  57699. object: this
  57700. });
  57701. }
  57702. }
  57703. get modifieable () {
  57704. return this._modifiable;
  57705. }
  57706. set modifieable (value) {
  57707. this._modifiable = value;
  57708. this.update();
  57709. }
  57710. };
  57711. class BoxVolume$1 extends Volume$1{
  57712. constructor(args = {}){
  57713. super(args);
  57714. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  57715. this.name = 'box_' + this.constructor.counter;
  57716. this.clipTask = args.clipTask || Potree.ClipTask.SHOW_INSIDE; //add
  57717. this.showBox = true;
  57718. let boxGeometry = new BoxGeometry(1, 1, 1);
  57719. boxGeometry.computeBoundingBox();
  57720. let boxFrameGeometry = new Geometry();
  57721. let Vector3$1 = Vector3;
  57722. {
  57723. boxFrameGeometry.vertices.push(
  57724. // bottom
  57725. new Vector3$1(-0.5, -0.5, 0.5),
  57726. new Vector3$1(0.5, -0.5, 0.5),
  57727. new Vector3$1(0.5, -0.5, 0.5),
  57728. new Vector3$1(0.5, -0.5, -0.5),
  57729. new Vector3$1(0.5, -0.5, -0.5),
  57730. new Vector3$1(-0.5, -0.5, -0.5),
  57731. new Vector3$1(-0.5, -0.5, -0.5),
  57732. new Vector3$1(-0.5, -0.5, 0.5),
  57733. // top
  57734. new Vector3$1(-0.5, 0.5, 0.5),
  57735. new Vector3$1(0.5, 0.5, 0.5),
  57736. new Vector3$1(0.5, 0.5, 0.5),
  57737. new Vector3$1(0.5, 0.5, -0.5),
  57738. new Vector3$1(0.5, 0.5, -0.5),
  57739. new Vector3$1(-0.5, 0.5, -0.5),
  57740. new Vector3$1(-0.5, 0.5, -0.5),
  57741. new Vector3$1(-0.5, 0.5, 0.5),
  57742. // sides
  57743. new Vector3$1(-0.5, -0.5, 0.5),
  57744. new Vector3$1(-0.5, 0.5, 0.5),
  57745. new Vector3$1(0.5, -0.5, 0.5),
  57746. new Vector3$1(0.5, 0.5, 0.5),
  57747. new Vector3$1(0.5, -0.5, -0.5),
  57748. new Vector3$1(0.5, 0.5, -0.5),
  57749. new Vector3$1(-0.5, -0.5, -0.5),
  57750. new Vector3$1(-0.5, 0.5, -0.5),
  57751. );
  57752. }
  57753. this.material = new DepthBasicMaterial({
  57754. color: colors[this.clipTask],
  57755. side:DoubleSide,
  57756. transparent: true,
  57757. opacity: boxOpacity.hovered,
  57758. depthTest: true,
  57759. depthWrite: false,
  57760. useDepth:true,
  57761. clipDistance : 2,//消失距离
  57762. occlusionDistance: 0.1,//变为backColor距离
  57763. maxClipFactor: 0.9,
  57764. });
  57765. this.box = new Mesh(boxGeometry, this.material);
  57766. this.box.geometry.computeBoundingBox();
  57767. this.boundingBox = this.box.geometry.boundingBox;
  57768. this.add(this.box);
  57769. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: colors[this.clipTask], opacity:LineOpacity.default/* 0xff2050 */}));
  57770. this.frame = LineDraw.createFatLine(
  57771. boxFrameGeometry.vertices,
  57772. { color: colors[this.clipTask], opacity:LineOpacity.default, lineWidth:1, dontAlwaysSeen:true} );
  57773. // this.frame.mode = THREE.Lines;
  57774. this.add(this.frame);
  57775. this.update();
  57776. }
  57777. update(){
  57778. this.boundingBox = this.box.geometry.boundingBox;
  57779. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  57780. Potree.Utils.updateVisible(this.box, 'selected', (this.selected || this.hovered) && this.showBox);
  57781. this.box.material.opacity = this.selected ? boxOpacity.selected : boxOpacity.hovered;
  57782. this.box.material.color.set(colors[this.clipTask]);
  57783. this.frame.material.color.set(colors[this.clipTask]);
  57784. this.frame.material.opacity = this.selected ? LineOpacity.selected : LineOpacity.default;
  57785. this.frame.material.lineWidth = this.selected ? 2 : 1;
  57786. }
  57787. raycast (raycaster, intersects) {
  57788. let is = [];
  57789. this.box.raycast(raycaster, is);
  57790. if (is.length > 0) {
  57791. let I = is[0];
  57792. intersects.push({
  57793. distance: I.distance,
  57794. object: this,
  57795. point: I.point.clone()
  57796. });
  57797. }
  57798. }
  57799. getVolume(){
  57800. return Math.abs(this.scale.x * this.scale.y * this.scale.z);
  57801. }
  57802. };
  57803. class SphereVolume$2 extends Volume$1{
  57804. constructor(args = {}){
  57805. super(args);
  57806. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  57807. this.name = 'sphere_' + this.constructor.counter;
  57808. let sphereGeometry = new SphereGeometry(1, 32, 32);
  57809. sphereGeometry.computeBoundingBox();
  57810. this.material = new MeshBasicMaterial({
  57811. color: 0x00ff00,
  57812. transparent: true,
  57813. opacity: 0.3,
  57814. depthTest: true,
  57815. depthWrite: false});
  57816. this.sphere = new Mesh(sphereGeometry, this.material);
  57817. this.sphere.visible = false;
  57818. this.sphere.geometry.computeBoundingBox();
  57819. this.boundingBox = this.sphere.geometry.boundingBox;
  57820. this.add(this.sphere);
  57821. this.label.visible = false;
  57822. let frameGeometry = new Geometry();
  57823. {
  57824. let steps = 64;
  57825. let uSegments = 8;
  57826. let vSegments = 5;
  57827. let r = 1;
  57828. for(let uSegment = 0; uSegment < uSegments; uSegment++){
  57829. let alpha = (uSegment / uSegments) * Math.PI * 2;
  57830. let dirx = Math.cos(alpha);
  57831. let diry = Math.sin(alpha);
  57832. for(let i = 0; i <= steps; i++){
  57833. let v = (i / steps) * Math.PI * 2;
  57834. let vNext = v + 2 * Math.PI / steps;
  57835. let height = Math.sin(v);
  57836. let xyAmount = Math.cos(v);
  57837. let heightNext = Math.sin(vNext);
  57838. let xyAmountNext = Math.cos(vNext);
  57839. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  57840. frameGeometry.vertices.push(vertex);
  57841. let vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext);
  57842. frameGeometry.vertices.push(vertexNext);
  57843. }
  57844. }
  57845. // creates rings at poles, just because it's easier to implement
  57846. for(let vSegment = 0; vSegment <= vSegments + 1; vSegment++){
  57847. //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1
  57848. let uh = (vSegment / (vSegments + 1)); // -1 to 1
  57849. uh = (1 - uh) * (-Math.PI / 2) + uh *(Math.PI / 2);
  57850. let height = Math.sin(uh);
  57851. console.log(uh, height);
  57852. for(let i = 0; i <= steps; i++){
  57853. let u = (i / steps) * Math.PI * 2;
  57854. let uNext = u + 2 * Math.PI / steps;
  57855. let dirx = Math.cos(u);
  57856. let diry = Math.sin(u);
  57857. let dirxNext = Math.cos(uNext);
  57858. let diryNext = Math.sin(uNext);
  57859. let xyAmount = Math.sqrt(1 - height * height);
  57860. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  57861. frameGeometry.vertices.push(vertex);
  57862. let vertexNext = new Vector3(dirxNext * xyAmount, diryNext * xyAmount, height);
  57863. frameGeometry.vertices.push(vertexNext);
  57864. }
  57865. }
  57866. }
  57867. this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({color: 0x000000}));
  57868. this.add(this.frame);
  57869. let frameMaterial = new MeshBasicMaterial({wireframe: true, color: 0x000000});
  57870. this.frame = new Mesh(sphereGeometry, frameMaterial);
  57871. //this.add(this.frame);
  57872. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000}));
  57873. // this.frame.mode = THREE.Lines;
  57874. //this.add(this.frame);
  57875. this.update();
  57876. }
  57877. update(){
  57878. this.boundingBox = this.sphere.geometry.boundingBox;
  57879. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  57880. //if (this._clip) {
  57881. // this.sphere.visible = false;
  57882. // this.label.visible = false;
  57883. //} else {
  57884. // this.sphere.visible = true;
  57885. // this.label.visible = this.showVolumeLabel;
  57886. //}
  57887. }
  57888. raycast (raycaster, intersects) {
  57889. let is = [];
  57890. this.sphere.raycast(raycaster, is);
  57891. if (is.length > 0) {
  57892. let I = is[0];
  57893. intersects.push({
  57894. distance: I.distance,
  57895. object: this,
  57896. point: I.point.clone()
  57897. });
  57898. }
  57899. }
  57900. // see https://en.wikipedia.org/wiki/Ellipsoid#Volume
  57901. getVolume(){
  57902. return (4 / 3) * Math.PI * this.scale.x * this.scale.y * this.scale.z;
  57903. }
  57904. };
  57905. const renderOrders = {
  57906. line: 0 ,
  57907. spot: 15, //高过模型
  57908. };
  57909. const planeGeo = new PlaneGeometry(1,1);
  57910. let texLoader$3 = new TextureLoader();
  57911. let lineMat = new LineBasicMaterial({
  57912. color: '#ffffff',
  57913. });
  57914. let spotMat;
  57915. const defaultLineLength = 0.6;
  57916. const defaultSpotScale = 0.4;
  57917. class Tag extends Object3D{
  57918. constructor(o){
  57919. super();
  57920. this.lineLength = o.lineLength != void 0 ? o.lineLength : defaultLineLength;
  57921. this.position.copy(o.position);
  57922. this.normal = o.normal != void 0 ? o.normal : new Vector3(0,0,-1);
  57923. this.root = o.root;
  57924. //this.matrixAutoUpdate = false
  57925. this.build();
  57926. /* this.spot.addEventListener('mouseover',()=>{
  57927. }) */
  57928. }
  57929. build(){
  57930. if(!spotMat){
  57931. spotMat = new MeshBasicMaterial({
  57932. transparent:true,
  57933. map: texLoader$3.load(Potree.resourcePath+'/textures/spot_default.png' ),
  57934. });
  57935. }
  57936. let endPos = this.normal.clone().multiplyScalar(this.lineLength);
  57937. this.line = LineDraw.createLine([
  57938. new Vector3(0,0,0),
  57939. endPos
  57940. ], {mat:lineMat});
  57941. let group = new Object3D();
  57942. this.spot = new Mesh(planeGeo, spotMat);
  57943. this.spot.scale.set(defaultSpotScale,defaultSpotScale,defaultSpotScale);
  57944. this.titleLabel = new TextSprite$2({root: group, text:'1', sizeInfo:{width2d:200},
  57945. textColor:{r:255,g:255,b:255,a:1.0},
  57946. backgroundColor:{r:0,g:0,b:0,a:0.8},
  57947. borderRadius: 6,
  57948. fontsize:13, fontWeight:'',//thick
  57949. renderOrder : renderOrders.spot, pickOrder:renderOrders.spot,
  57950. }); //更新sprite时,实际更新的是root: spot的矩阵
  57951. this.spot.renderOrder = renderOrders.spot;
  57952. /* const mainLabelProp = {
  57953. backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity},
  57954. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  57955. fontsize:16,
  57956. useDepth : true ,
  57957. renderOrder : 5, pickOrder:5,
  57958. } */
  57959. this.titleLabel.position.set(0,0.4,0);
  57960. this.titleLabel.sprite.material.depthTest = this.titleLabel.sprite.material.depthWrite = true;
  57961. group.position.copy(endPos);
  57962. group.add(this.spot);
  57963. group.add(this.titleLabel);
  57964. this.add(group);
  57965. this.add(this.line);
  57966. viewer.scene.tags.add(this);
  57967. }
  57968. changeTitle(title){
  57969. this.titleLabel.changeText(title);
  57970. }
  57971. updateMatrixWorld(force){ //重写,只为了将root当做parent
  57972. this.updateMatrix();
  57973. this.matrixWorld.multiplyMatrices( this.root.matrixWorld, this.matrix );
  57974. const children = this.children;
  57975. for ( let i = 0, l = children.length; i < l; i ++ ) {
  57976. children[ i ].updateMatrixWorld( force );
  57977. }
  57978. }
  57979. updateWorldMatrix( updateParents, updateChildren ) {//重写,只为了将root当做parent
  57980. if ( updateParents === true && this.root !== null ) {
  57981. this.root.updateWorldMatrix( true, false );
  57982. }
  57983. if ( this.matrixAutoUpdate ) this.updateMatrix();
  57984. this.matrixWorld.multiplyMatrices( this.root.matrixWorld, this.matrix );
  57985. if ( updateChildren === true ) {
  57986. const children = this.children;
  57987. for ( let i = 0, l = children.length; i < l; i ++ ) {
  57988. children[ i ].updateWorldMatrix( false, true );
  57989. }
  57990. }
  57991. }
  57992. dispose(){
  57993. this.parent.remove(this);
  57994. this.titleLabel.dispatchEvent({type:'dispose'});
  57995. }
  57996. }
  57997. class TagTool extends EventDispatcher{
  57998. constructor (viewer) {
  57999. super();
  58000. this.viewer = viewer;
  58001. this.viewer.addEventListener('start_inserting_tag', e => {
  58002. this.viewer.dispatchEvent({
  58003. type: 'cancel_insertions'
  58004. });
  58005. });
  58006. }
  58007. createTagFromData(data){
  58008. let tag = new Tag({
  58009. title: data.title, position: data.position, normal: data.normal,
  58010. root: data.root //e.intersect.pointcloud || e.intersect.object
  58011. });
  58012. return tag
  58013. }
  58014. startInsertion (args = {}, callback, cancelFun) {
  58015. let deferred = $.Deferred();
  58016. this.viewer.dispatchEvent({
  58017. type: 'start_inserting_tag'
  58018. });
  58019. this.adding = true;
  58020. let cancel = ()=>{
  58021. end();
  58022. };
  58023. let end = ()=>{
  58024. this.adding = false;
  58025. viewer.dispatchEvent({type:"endTagMove"});
  58026. this.viewer.removeEventListener('global_click', click);
  58027. };
  58028. let click = (e)=>{
  58029. var worldPos = e.intersect && (/* e.intersect.orthoIntersect || */e.intersect.location);
  58030. if(!worldPos){
  58031. return
  58032. }
  58033. let localPos = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:e.intersect.pointcloud, object:e.intersect.object, position:worldPos });
  58034. let tag = new Tag({
  58035. title: '1', position: localPos, normal:e.intersect.normal,
  58036. root: e.intersect.pointcloud || e.intersect.object
  58037. });
  58038. //pointcloud里加一个normal 的非float32
  58039. end();
  58040. e.consume && e.consume();
  58041. deferred.resolve(tag);
  58042. return {stopContinue:true}
  58043. };
  58044. this.viewer.addEventListener('global_click', click, {importance:10});
  58045. return deferred.promise()
  58046. }
  58047. }
  58048. const initDir = new Vector3(0,1,0);//指南针模型的北方向 向屏幕里
  58049. class Compass extends EventDispatcher{
  58050. constructor(dom, viewport){
  58051. super();
  58052. this.angle = 0;
  58053. this.show = false;
  58054. if(dom){
  58055. this.dom = $(dom);
  58056. }
  58057. this.viewport = viewport;
  58058. this.init();
  58059. }
  58060. init(){
  58061. var width = 100, height = 100;
  58062. if(!this.dom){
  58063. this.dom = $('<div name="compass"></div>');
  58064. $(viewer.renderArea).append(this.dom);
  58065. }
  58066. this.dom.css({ display:"none", position:"absolute",right:"1%",top: "60px",width:width+"px",height:height+"px", "z-index":100,"pointer-events":"none" });
  58067. let child = $("<div class='dirText north'><span>"+/* (config.lang=='zh'? */'北'/* :'N') */+"</span></div><div class='center'></div>");
  58068. this.dom.append(child);
  58069. this.dom.find(".dirText").css({textAlign:"center","font-size":"10px","position":"absolute",
  58070. width: "100%",
  58071. height: "25px",
  58072. "line-height": "25px"});
  58073. this.dom.find(".north").css({"color":"#02a0e9","top":"0"});
  58074. this.dom.find(".south").css({"color":"#ff1414","bottom":"0"});
  58075. this.dom.find(".center").css({
  58076. //"background":`url(${config.getStaticResource('img')}/dire.png)`,
  58077. width: width/2+"px",
  58078. height: height/2+"px",
  58079. "background-size": "contain",
  58080. "background-position": "center",
  58081. left: "50%",
  58082. top: "50%",
  58083. transform: "translate(-50%,-50%)",
  58084. position: "absolute"
  58085. });
  58086. this.dom.find(".dirText").css({
  58087. "text-align": "center",
  58088. "font-size": "10px",
  58089. "color": "rgb(255, 255, 255)",
  58090. "position": "absolute",
  58091. "top": "50%",
  58092. "left": "50%",
  58093. "width": "45%",
  58094. "height": "0px",
  58095. "transform-origin": "left center",
  58096. });
  58097. this.dom.find(".dirText span").css({
  58098. display: "block",
  58099. position: "absolute",
  58100. right: "5px",
  58101. top: "0",
  58102. width: "20px",
  58103. height: "20px",
  58104. "line-height": "20px",
  58105. // "font-size": ".75rem ",
  58106. "margin-top": "-10px",
  58107. });
  58108. try {
  58109. this.renderer = new WebGLRenderer({ antialias: true, alpha:true });//许钟文 添加个抗锯齿,否则添加的线条锯齿严重,
  58110. this.renderer.autoClear = !0;
  58111. this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1);
  58112. this.renderer.domElement.setAttribute('name','compass');
  58113. this.renderer.setClearAlpha(0.0);
  58114. //xst修改
  58115. //this.renderer.setSize(width/2, height/2, false, window.devicePixelRatio ? window.devicePixelRatio : 1);
  58116. //xst修改
  58117. //this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1);
  58118. //this.renderer.setSize(width/2, height/2);
  58119. //xst修改
  58120. this.renderer.setDrawingBufferSize( width/2, height/2, window.devicePixelRatio ? window.devicePixelRatio : 1 );
  58121. //this.emit(SceneRendererEvents.ContextCreated)
  58122. } catch (e) {
  58123. viewer.dispatchEvent('webglError', {msg:e});
  58124. }
  58125. this.dom.find(".center")[0].appendChild(this.renderer.domElement);
  58126. this.renderer.domElement.style.width = this.renderer.domElement.style.height = '100%';
  58127. this.camera = new PerspectiveCamera;
  58128. this.camera.fov = 50;
  58129. this.camera.updateProjectionMatrix();
  58130. this.scene = new Scene,
  58131. this.scene.add(this.camera);
  58132. this.createCompass();
  58133. viewer.addEventListener('camera_changed', e => {
  58134. if (e.viewport == this.viewport && (e.changeInfo.positionChanged || e.changeInfo.quaternionChanged)) {
  58135. this.update();
  58136. }
  58137. });
  58138. this.setDomPos();
  58139. if(this.viewport)this.setDisplay(true);
  58140. }
  58141. createCompass(){
  58142. //ConeBufferGeometry(radius : Float, height : Float, radialSegments : Integer, heightSegments : Integer, openEnded : Boolean, thetaStart : Float, thetaLength : Float)
  58143. const height = 2;
  58144. const geometry1 = new ConeBufferGeometry( 0.7, height, 4, true );
  58145. const geometry2 = new ConeBufferGeometry( 0.7, height, 4, true );
  58146. const material = new MeshBasicMaterial({
  58147. vertexColors :true
  58148. });
  58149. //指南针由两个四棱锥拼成,为了渐变颜色,采用指定vertexColor的方式。
  58150. var setColor = function(geometry, color1,color2){
  58151. const colors = [];
  58152. for ( let i = 0, n = geometry.attributes.position.count; i < n; ++ i ) {
  58153. colors.push( 1, 1, 1 );
  58154. }
  58155. var set = function(index, color){//设置第index个点的颜色
  58156. colors[index*3+0] = color[0];
  58157. colors[index*3+1] = color[1];
  58158. colors[index*3+2] = color[2];
  58159. };
  58160. var mid = [(color1[0]+color2[0])/2, (color1[1]+color2[1])/2, (color1[2]+color2[2])/2 ];
  58161. set(1,color1); set(5,color1);set(6,color1);
  58162. set(2,mid); set(3,mid);set(7,mid);
  58163. set(4,color2); set(8,color2);set(9,color2);
  58164. geometry.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3));
  58165. };
  58166. var blue1 = [1/255,238/255,245/255]; //逐渐变深
  58167. var blue2 = [20/255,146/255,170/255];
  58168. var blue3 = [40/255,60/255,103/255];
  58169. setColor(geometry1, blue1,blue2);
  58170. setColor(geometry2, blue2,blue3);
  58171. /* 朝箭头方向看点构成如下 虽然geometry.attributes.position.count = 19 只有1-9设置的颜色是有效的 另外为什么7决定了上下两边的颜色呢…… 5、9可将其分成上下两个颜色
  58172. 6
  58173. /|\
  58174. / | \
  58175. 7 /_2|1_\ 5
  58176. \ 3|4 / 9
  58177. \ | /
  58178. \|/
  58179. 8
  58180. */
  58181. const cone = new Mesh( geometry1, material );
  58182. cone.position.setY(height/2);
  58183. geometry1.computeVertexNormals();//computeFaceNormals
  58184. geometry2.computeVertexNormals();
  58185. const cones = new Object3D();
  58186. cones.add(cone);
  58187. let cone2 = new Mesh( geometry2, material );
  58188. cone2.rotation.x = Math.PI;
  58189. cone2.position.setY(-height/2);
  58190. cones.add(cone2);
  58191. //cones.rotation.x = Math.PI / 2;//转向initDir的方向
  58192. //cones.rotation.z = Math.PI / 2;
  58193. cones.rotation.z = Math.PI ;//转向initDir的方向
  58194. cones.scale.set(0.7,0.7,0.7);
  58195. this.scene.add(cones);
  58196. this.cones = cones;
  58197. }
  58198. setNorth(){ //设置北方向,这决定了指南针自身的朝向。
  58199. const floors = store.getters['scene/houstFloor'].floors;
  58200. if(!floors || !floors.length){
  58201. return
  58202. }
  58203. const floor = floors[0];
  58204. const metadata = app.store.getters['scene/metadata'] || {};
  58205. this.angle = (floor && floor.dire || 0) + MathUtils.radToDeg(parseFloat(metadata.floorPlanAngle || 0)); //基础朝向
  58206. this.cones.rotation.y = Math.PI / 2 - MathUtils.degToRad(this.angle);
  58207. //console.log("dir:"+floor.dire+", floorPlanAngle:"+metadata.floorPlanAngle)
  58208. this.update();
  58209. }
  58210. update(quaternion){
  58211. if(!this.show)return;
  58212. if(!quaternion) quaternion = this.viewport.camera.quaternion.clone();
  58213. this.updateCamera(quaternion);
  58214. this.updateLabel(quaternion);
  58215. this.render();
  58216. }
  58217. /*updateLabel(quaternion){//更新北标签
  58218. var dir = viewer.mainViewport.view.direction;
  58219. var oriDir = initDir.clone() //指南针最初始时的北方向
  58220. var extraQua
  58221. if(objects.player.mode == "transitioning"){//当transitioning时,相机的quaternion不是用control的lookAt算出来,而是直接由一个quaternion过渡到另一个,这样相机将会是歪的,投影面也就不会是原先的水平面。
  58222. var tempCamera = new THREE.Camera(); //借用camera的lookAt算出如果正视同样的target, quaternion会是什么值。 将它乘以当前相机quaternion,得到的就是相机歪的旋转值。
  58223. tempCamera.position.copy(this.camera.position);
  58224. tempCamera.lookAt(tempCamera.position.clone().add(dir))
  58225. var q = tempCamera.quaternion.inverse()
  58226. extraQua = q.premultiply(quaternion) //歪掉的额外旋转值
  58227. }
  58228. //北标签的方向为指南针轮盘方向,也就是要将camera的方向投影到水平面上。 但是如果相机歪了,看到的世界都会歪一定角度,投影面也要歪一定角度。
  58229. var up = new THREE.Vector3(0,0,1) //投影水平面的法线,也是相机的摆正的up方向
  58230. extraQua && up.applyQuaternion(extraQua)
  58231. dir.projectOnPlane(up) //将方向投影到水平面上; 如果相机不是正视(extraQua不为0001),就要将水平面也转动
  58232. oriDir.projectOnPlane(up)//为什么initDir投影了和没有投影angle结果一样
  58233. var angle = dir.angleTo(oriDir)
  58234. if(dir.cross(oriDir).y > 0)angle = -angle
  58235. var deg = this.angle - 90 + THREE.Math.radToDeg(angle) //因为css写的样式初始是指向右方,和initDir差了90°,所以减去。
  58236. this.dom.find(".dirText").css( "transform","rotate("+deg+"deg)" )
  58237. this.dom.find(".dirText span").css("transform","rotate("+(-deg)+"deg)")
  58238. } */
  58239. updateLabel(quaternion){//更新北标签
  58240. let deg = MathUtils.radToDeg(this.viewport.view.yaw) - 90;
  58241. this.dom.find(".dirText").css( "transform","rotate("+deg+"deg)" );
  58242. this.dom.find(".dirText span").css("transform","rotate("+(-deg)+"deg)");
  58243. }
  58244. updateCamera(quaternion){ //更新canvas中的指南针表现,也就是更新相机,和场景中的相机朝向一致。
  58245. const radius = 5; //相机距离
  58246. this.camera.quaternion.copy(quaternion);
  58247. var dir = this.viewport.view.direction; //相机朝向
  58248. this.camera.position.copy(dir.multiplyScalar(radius).negate()); //相机绕着指南针中心(000)转动
  58249. }
  58250. changeViewport(viewport){
  58251. this.viewport = viewport;
  58252. this.update(); //因相机更新了
  58253. }
  58254. render(){
  58255. this.renderer.render(this.scene, this.camera);
  58256. }
  58257. setDisplay(state){
  58258. this.show = !!state;
  58259. if(this.show){
  58260. this.update();
  58261. this.dom.fadeIn(100);
  58262. }else {
  58263. this.dom.fadeOut(100);
  58264. }
  58265. }
  58266. autoJudgeDisplay(){
  58267. }
  58268. setDomPos(){
  58269. if(!this.viewport)return
  58270. let right = this.viewport.left + this.viewport.width;
  58271. this.dom.css({'right':((1-right)*100 + 1) + '%'});
  58272. }
  58273. }
  58274. // Copied from three.js: WebGLRenderer.js
  58275. function paramThreeToGL$1(_gl, p) {
  58276. let extension;
  58277. if (p === RepeatWrapping) return _gl.REPEAT;
  58278. if (p === ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  58279. if (p === MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  58280. if (p === NearestFilter) return _gl.NEAREST;
  58281. if (p === NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  58282. if (p === NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  58283. if (p === LinearFilter) return _gl.LINEAR;
  58284. if (p === LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  58285. if (p === LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  58286. if (p === UnsignedByteType) return _gl.UNSIGNED_BYTE;
  58287. if (p === UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  58288. if (p === UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  58289. if (p === UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  58290. if (p === ByteType) return _gl.BYTE;
  58291. if (p === ShortType) return _gl.SHORT;
  58292. if (p === UnsignedShortType) return _gl.UNSIGNED_SHORT;
  58293. if (p === IntType) return _gl.INT;
  58294. if (p === UnsignedIntType) return _gl.UNSIGNED_INT;
  58295. if (p === FloatType) return _gl.FLOAT;
  58296. if (p === HalfFloatType) {
  58297. extension = extensions.get('OES_texture_half_float');
  58298. if (extension !== null) return extension.HALF_FLOAT_OES;
  58299. }
  58300. if (p === AlphaFormat) return _gl.ALPHA;
  58301. if (p === RGBFormat) return _gl.RGB;
  58302. if (p === RGBAFormat) return _gl.RGBA;
  58303. if (p === LuminanceFormat) return _gl.LUMINANCE;
  58304. if (p === LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  58305. if (p === DepthFormat) return _gl.DEPTH_COMPONENT;
  58306. if (p === DepthStencilFormat) return _gl.DEPTH_STENCIL;
  58307. if (p === AddEquation) return _gl.FUNC_ADD;
  58308. if (p === SubtractEquation) return _gl.FUNC_SUBTRACT;
  58309. if (p === ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  58310. if (p === ZeroFactor) return _gl.ZERO;
  58311. if (p === OneFactor) return _gl.ONE;
  58312. if (p === SrcColorFactor) return _gl.SRC_COLOR;
  58313. if (p === OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  58314. if (p === SrcAlphaFactor) return _gl.SRC_ALPHA;
  58315. if (p === OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  58316. if (p === DstAlphaFactor) return _gl.DST_ALPHA;
  58317. if (p === OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  58318. if (p === DstColorFactor) return _gl.DST_COLOR;
  58319. if (p === OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  58320. if (p === SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  58321. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  58322. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  58323. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  58324. if (extension !== null) {
  58325. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  58326. if (p === RGBA_S3TC_DXT1_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  58327. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  58328. if (p === RGBA_S3TC_DXT5_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  58329. }
  58330. }
  58331. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  58332. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  58333. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  58334. if (extension !== null) {
  58335. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  58336. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  58337. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  58338. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  58339. }
  58340. }
  58341. if (p === RGB_ETC1_Format) {
  58342. extension = extensions.get('WEBGL_compressed_texture_etc1');
  58343. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  58344. }
  58345. if (p === MinEquation || p === MaxEquation) {
  58346. extension = extensions.get('EXT_blend_minmax');
  58347. if (extension !== null) {
  58348. if (p === MinEquation) return extension.MIN_EXT;
  58349. if (p === MaxEquation) return extension.MAX_EXT;
  58350. }
  58351. }
  58352. if (p === UnsignedInt248Type) {
  58353. extension = extensions.get('WEBGL_depth_texture');
  58354. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  58355. }
  58356. return 0;
  58357. };
  58358. let attributeLocations$1 = {
  58359. "position": {name: "position", location: 0},
  58360. "color": {name: "color", location: 1},
  58361. "rgba": {name: "color", location: 1},
  58362. "intensity": {name: "intensity", location: 2},
  58363. "classification": {name: "classification", location: 3},
  58364. "returnNumber": {name: "returnNumber", location: 4},
  58365. "return number": {name: "returnNumber", location: 4},
  58366. "returns": {name: "returnNumber", location: 4},
  58367. "numberOfReturns": {name: "numberOfReturns", location: 5},
  58368. "number of returns": {name: "numberOfReturns", location: 5},
  58369. "pointSourceID": {name: "pointSourceID", location: 6},
  58370. "source id": {name: "pointSourceID", location: 6},
  58371. "point source id": {name: "pointSourceID", location: 6},
  58372. "indices": {name: "indices", location: 7},
  58373. "normal": {name: "normal", location: 8},
  58374. "spacing": {name: "spacing", location: 9},
  58375. "gps-time": {name: "gpsTime", location: 10},
  58376. "aExtra": {name: "aExtra", location: 11},
  58377. };
  58378. class Shader$1 {
  58379. constructor(gl, name, vsSource, fsSource) {
  58380. this.gl = gl;
  58381. this.name = name;
  58382. this.vsSource = vsSource;
  58383. this.fsSource = fsSource;
  58384. this.cache = new Map();
  58385. this.vs = null;
  58386. this.fs = null;
  58387. this.program = null;
  58388. this.uniformLocations = {};
  58389. this.attributeLocations = {};
  58390. this.uniformBlockIndices = {};
  58391. this.uniformBlocks = {};
  58392. this.uniforms = {};
  58393. this.update(vsSource, fsSource);
  58394. }
  58395. update(vsSource, fsSource) {
  58396. this.vsSource = vsSource;
  58397. this.fsSource = fsSource;
  58398. this.linkProgram();
  58399. }
  58400. compileShader(shader, source){
  58401. let gl = this.gl;
  58402. gl.shaderSource(shader, source);
  58403. gl.compileShader(shader);
  58404. let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  58405. if (!success) {
  58406. let info = gl.getShaderInfoLog(shader);
  58407. let numberedSource = source.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n");
  58408. throw `could not compile shader ${this.name}: ${info}, \n${numberedSource}`;
  58409. }
  58410. }
  58411. linkProgram() {
  58412. const tStart = performance.now();
  58413. let gl = this.gl;
  58414. this.uniformLocations = {};
  58415. this.attributeLocations = {};
  58416. this.uniforms = {};
  58417. gl.useProgram(null);
  58418. let cached = this.cache.get(`${this.vsSource}, ${this.fsSource}`);
  58419. if (cached) {
  58420. this.program = cached.program;
  58421. this.vs = cached.vs;
  58422. this.fs = cached.fs;
  58423. this.attributeLocations = cached.attributeLocations;
  58424. this.uniformLocations = cached.uniformLocations;
  58425. this.uniformBlocks = cached.uniformBlocks;
  58426. this.uniforms = cached.uniforms;
  58427. return;
  58428. } else {
  58429. this.vs = gl.createShader(gl.VERTEX_SHADER);
  58430. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  58431. this.program = gl.createProgram();
  58432. if( !gl.isProgram(this.program )){//创建失败 开启多个页面可能会,原因是webglcontextlost
  58433. //console.error('创建program失败');
  58434. viewer.dispatchEvent('webglError', {msg: 'potreeRenderer创建program失败'});
  58435. console.log(this.vs);
  58436. console.log(this.fs);
  58437. return;
  58438. }
  58439. for(let name of Object.keys(attributeLocations$1)){
  58440. let location = attributeLocations$1[name].location;
  58441. let glslName = attributeLocations$1[name].name;
  58442. gl.bindAttribLocation(this.program, location, glslName);
  58443. }
  58444. this.compileShader(this.vs, this.vsSource);
  58445. this.compileShader(this.fs, this.fsSource);
  58446. let program = this.program;
  58447. gl.attachShader(program, this.vs);
  58448. gl.attachShader(program, this.fs);
  58449. gl.linkProgram(program);
  58450. gl.detachShader(program, this.vs);
  58451. gl.detachShader(program, this.fs);
  58452. // 检测当前程序链接状态
  58453. let success = gl.getProgramParameter(program, gl.LINK_STATUS);
  58454. if (!success) {
  58455. let info = gl.getProgramInfoLog(program);
  58456. throw `could not link program ${this.name}: ${info}`;
  58457. }
  58458. { // attribute locations
  58459. let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  58460. for (let i = 0; i < numAttributes; i++) {
  58461. let attribute = gl.getActiveAttrib(program, i);
  58462. let location = gl.getAttribLocation(program, attribute.name);
  58463. this.attributeLocations[attribute.name] = location;
  58464. }
  58465. }
  58466. { // uniform locations
  58467. let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  58468. for (let i = 0; i < numUniforms; i++) {
  58469. let uniform = gl.getActiveUniform(program, i);
  58470. let location = gl.getUniformLocation(program, uniform.name);
  58471. this.uniformLocations[uniform.name] = location;
  58472. this.uniforms[uniform.name] = {
  58473. location: location,
  58474. value: null,
  58475. };
  58476. }
  58477. }
  58478. // uniform blocks
  58479. if( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext){ //WebGL2RenderingContext在mac的safari14以下是没有定义的
  58480. let numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  58481. for (let i = 0; i < numBlocks; i++) {
  58482. let blockName = gl.getActiveUniformBlockName(program, i);
  58483. let blockIndex = gl.getUniformBlockIndex(program, blockName);
  58484. this.uniformBlockIndices[blockName] = blockIndex;
  58485. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  58486. let dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  58487. let uBuffer = gl.createBuffer();
  58488. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  58489. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  58490. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  58491. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  58492. this.uniformBlocks[blockName] = {
  58493. name: blockName,
  58494. index: blockIndex,
  58495. dataSize: dataSize,
  58496. buffer: uBuffer
  58497. };
  58498. }
  58499. }
  58500. let cached = {
  58501. program: this.program,
  58502. vs: this.vs,
  58503. fs: this.fs,
  58504. attributeLocations: this.attributeLocations,
  58505. uniformLocations: this.uniformLocations,
  58506. uniforms: this.uniforms,
  58507. uniformBlocks: this.uniformBlocks,
  58508. };
  58509. this.cache.set(`${this.vsSource}, ${this.fsSource}`, cached);
  58510. }
  58511. const tEnd = performance.now();
  58512. const duration = tEnd - tStart;
  58513. //console.log(`shader compile duration: ${duration.toFixed(3)}`);
  58514. }
  58515. setUniformMatrix4(name, value) {
  58516. const gl = this.gl;
  58517. const location = this.uniformLocations[name];
  58518. if (location == null) {
  58519. return;
  58520. }
  58521. let tmp = new Float32Array(value.elements);
  58522. gl.uniformMatrix4fv(location, false, tmp);
  58523. }
  58524. setUniform1f(name, value) {
  58525. const gl = this.gl;
  58526. const uniform = this.uniforms[name];
  58527. if (uniform === undefined) {
  58528. return;
  58529. }
  58530. if(uniform.value === value){
  58531. return;
  58532. }
  58533. uniform.value = value;
  58534. gl.uniform1f(uniform.location, value);
  58535. }
  58536. setUniformBoolean(name, value) {
  58537. const gl = this.gl;
  58538. const uniform = this.uniforms[name];
  58539. if (uniform === undefined) {
  58540. return;
  58541. }
  58542. if(uniform.value === value){
  58543. return;
  58544. }
  58545. uniform.value = value;
  58546. gl.uniform1i(uniform.location, value);
  58547. }
  58548. setUniformTexture(name, value) {
  58549. const gl = this.gl;
  58550. const location = this.uniformLocations[name];
  58551. if (location == null) {
  58552. return;
  58553. }
  58554. gl.uniform1i(location, value);
  58555. }
  58556. setUniform2f(name, value) {
  58557. const gl = this.gl;
  58558. const location = this.uniformLocations[name];
  58559. if (location == null) {
  58560. return;
  58561. }
  58562. gl.uniform2f(location, value[0], value[1]);
  58563. }
  58564. setUniform3f(name, value) {
  58565. const gl = this.gl;
  58566. const location = this.uniformLocations[name];
  58567. if (location == null) {
  58568. return;
  58569. }
  58570. gl.uniform3f(location, value[0], value[1], value[2]);
  58571. }
  58572. setUniform(name, value) {
  58573. if (value.constructor === Matrix4) {
  58574. this.setUniformMatrix4(name, value);
  58575. } else if (typeof value === "number") {
  58576. this.setUniform1f(name, value);
  58577. } else if (typeof value === "boolean") {
  58578. this.setUniformBoolean(name, value);
  58579. } else if (value instanceof WebGLTexture$1) {
  58580. this.setUniformTexture(name, value);
  58581. } else if (value instanceof Array) {
  58582. if (value.length === 2) {
  58583. this.setUniform2f(name, value);
  58584. } else if (value.length === 3) {
  58585. this.setUniform3f(name, value);
  58586. }
  58587. } else {
  58588. console.error("unhandled uniform type: ", name, value);
  58589. }
  58590. }
  58591. setUniform1i(name, value) {
  58592. let gl = this.gl;
  58593. let location = this.uniformLocations[name];
  58594. if (location == null) {
  58595. return;
  58596. }
  58597. gl.uniform1i(location, value);
  58598. }
  58599. };
  58600. class WebGLTexture$1 {
  58601. constructor(gl, texture) {
  58602. this.gl = gl;
  58603. this.texture = texture;
  58604. this.id = gl.createTexture();
  58605. this.target = gl.TEXTURE_2D;
  58606. this.version = -1;
  58607. this.update(texture);
  58608. }
  58609. update() {
  58610. if (!this.texture.image) {
  58611. this.version = this.texture.version;
  58612. return;
  58613. }
  58614. let gl = this.gl;
  58615. let texture = this.texture;
  58616. if (this.version === texture.version) {
  58617. return;
  58618. }
  58619. this.target = gl.TEXTURE_2D;
  58620. gl.bindTexture(this.target, this.id);
  58621. let level = 0;
  58622. let internalFormat = paramThreeToGL$1(gl, texture.format);
  58623. let width = texture.image.width;
  58624. let height = texture.image.height;
  58625. let border = 0;
  58626. let srcFormat = internalFormat;
  58627. let srcType = paramThreeToGL$1(gl, texture.type);
  58628. let data;
  58629. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  58630. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  58631. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  58632. if (texture instanceof DataTexture) {
  58633. data = texture.image.data;
  58634. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  58635. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  58636. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL$1(gl, texture.magFilter));
  58637. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL$1(gl, texture.minFilter));
  58638. gl.texImage2D(this.target, level, internalFormat,
  58639. width, height, border, srcFormat, srcType,
  58640. data);
  58641. } else if ((texture instanceof CanvasTexture) || (texture instanceof Texture)) {
  58642. data = texture.image;
  58643. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL$1(gl, texture.wrapS));
  58644. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL$1(gl, texture.wrapT));
  58645. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL$1(gl, texture.magFilter));
  58646. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL$1(gl, texture.minFilter));
  58647. gl.texImage2D(this.target, level, internalFormat,
  58648. internalFormat, srcType, data);
  58649. if (texture instanceof Texture) {gl.generateMipmap(gl.TEXTURE_2D);}
  58650. }
  58651. gl.bindTexture(this.target, null);
  58652. this.version = texture.version;
  58653. }
  58654. };
  58655. class WebGLBuffer$1 {
  58656. constructor() {
  58657. this.numElements = 0;
  58658. this.vao = null;
  58659. this.vbos = new Map();
  58660. }
  58661. };
  58662. class Renderer$1 {
  58663. constructor(threeRenderer) {
  58664. this.threeRenderer = threeRenderer;
  58665. this.gl = this.threeRenderer.getContext();
  58666. this.buffers = new Map();
  58667. this.shaders = new Map();
  58668. this.textures = new Map();
  58669. this.glTypeMapping = new Map();
  58670. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  58671. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  58672. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  58673. this.toggle = 0;
  58674. }
  58675. deleteBuffer(geometry) {
  58676. let gl = this.gl;
  58677. let webglBuffer = this.buffers.get(geometry);
  58678. if (webglBuffer != null) {
  58679. for (let attributeName in geometry.attributes) {
  58680. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  58681. }
  58682. this.buffers.delete(geometry);
  58683. }
  58684. }
  58685. createBuffer(geometry){
  58686. let gl = this.gl;
  58687. let webglBuffer = new WebGLBuffer$1();
  58688. webglBuffer.vao = gl.createVertexArray();
  58689. webglBuffer.numElements = geometry.attributes.position.count;
  58690. gl.bindVertexArray(webglBuffer.vao);
  58691. for(let attributeName in geometry.attributes){
  58692. let bufferAttribute = geometry.attributes[attributeName];
  58693. let vbo = gl.createBuffer();
  58694. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  58695. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  58696. let normalized = bufferAttribute.normalized;
  58697. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  58698. if(attributeLocations$1[attributeName] === undefined){
  58699. //attributeLocation = attributeLocations["aExtra"];
  58700. }else {
  58701. let attributeLocation = attributeLocations$1[attributeName].location;
  58702. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  58703. gl.enableVertexAttribArray(attributeLocation);
  58704. }
  58705. webglBuffer.vbos.set(attributeName, {
  58706. handle: vbo,
  58707. name: attributeName,
  58708. count: bufferAttribute.count,
  58709. itemSize: bufferAttribute.itemSize,
  58710. type: geometry.attributes.position.array.constructor,
  58711. version: 0
  58712. });
  58713. }
  58714. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  58715. gl.bindVertexArray(null);
  58716. let disposeHandler = (event) => {
  58717. this.deleteBuffer(geometry);
  58718. geometry.removeEventListener("dispose", disposeHandler);
  58719. };
  58720. geometry.addEventListener("dispose", disposeHandler);
  58721. return webglBuffer;
  58722. }
  58723. updateBuffer(geometry){
  58724. let gl = this.gl;
  58725. let webglBuffer = this.buffers.get(geometry);
  58726. gl.bindVertexArray(webglBuffer.vao);
  58727. for(let attributeName in geometry.attributes){
  58728. let bufferAttribute = geometry.attributes[attributeName];
  58729. let normalized = bufferAttribute.normalized;
  58730. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  58731. let vbo = null;
  58732. if(!webglBuffer.vbos.has(attributeName)){
  58733. vbo = gl.createBuffer();
  58734. webglBuffer.vbos.set(attributeName, {
  58735. handle: vbo,
  58736. name: attributeName,
  58737. count: bufferAttribute.count,
  58738. itemSize: bufferAttribute.itemSize,
  58739. type: geometry.attributes.position.array.constructor,
  58740. version: bufferAttribute.version
  58741. });
  58742. }else {
  58743. vbo = webglBuffer.vbos.get(attributeName).handle;
  58744. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  58745. }
  58746. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  58747. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  58748. if(attributeLocations$1[attributeName] === undefined){
  58749. //attributeLocation = attributeLocations["aExtra"];
  58750. }else {
  58751. let attributeLocation = attributeLocations$1[attributeName].location;
  58752. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  58753. gl.enableVertexAttribArray(attributeLocation);
  58754. }
  58755. }
  58756. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  58757. gl.bindVertexArray(null);
  58758. }
  58759. traverse(scene) {
  58760. let octrees = [];
  58761. let stack = [scene];
  58762. while (stack.length > 0) {
  58763. let node = stack.pop();
  58764. if (node instanceof PointCloudTree) {
  58765. octrees.push(node);
  58766. continue;
  58767. }
  58768. let visibleChildren = node.children.filter(c => c.visible);
  58769. stack.push(...visibleChildren);
  58770. }
  58771. let result = {
  58772. octrees: octrees
  58773. };
  58774. return result;
  58775. }
  58776. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  58777. viewer.addTimeMark('renderNodes','start');
  58778. let gl = this.gl;
  58779. let material = params.material ? params.material : octree.material;
  58780. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  58781. let view = camera.matrixWorldInverse;
  58782. if(params.viewOverride){
  58783. view = params.viewOverride;
  58784. }
  58785. let worldView = new Matrix4();
  58786. let mat4holder = new Float32Array(16);
  58787. let i = 0;
  58788. //---------从renderOctree搬到这----
  58789. shader.setUniform1f("size", material.usePanoMap ? Potree.config.material.absolutePanoramaSize * Math.min(window.devicePixelRatio,2) : material.size);//usePanoMap时控制在不大不小的范围内感觉较好,考虑到有的点云稀疏,用大一点的点
  58790. shader.setUniform1f("uOpacity", material.usePanoMap ? 1: material.opacity);
  58791. shader.setUniform3f("uColor", material.color.toArray());
  58792. /* let currentTextureBindingPoint = params.currentTextureBindingPoint
  58793. if (material.pointSizeType >= 0 && window.needvisibilityTexture) {
  58794. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  58795. material.activeAttributeName === "level of detail") {
  58796. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  58797. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  58798. const vnt = material.visibleNodesTexture;
  58799. const data = vnt.image.data;
  58800. data.set(visibilityTextureData.data);
  58801. vnt.needsUpdate = true;
  58802. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture); //不知道为什么这段从renderOctree中移过来,会崩溃。暂时不移动了
  58803. if(vnWebGLTexture){
  58804. shader.setUniform1i("visibleNodes", currentTextureBindingPoint);
  58805. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  58806. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  58807. currentTextureBindingPoint++;
  58808. }
  58809. }
  58810. } */
  58811. let transparent = false;
  58812. if(params.transparent !== undefined){
  58813. transparent = params.transparent && material.opacity < 1;
  58814. }else {
  58815. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  58816. }
  58817. if (transparent){
  58818. gl.enable(gl.BLEND);
  58819. if(params.notAdditiveBlending){
  58820. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending
  58821. /* gl.enable(gl.DEPTH_TEST);
  58822. gl.depthMask(true); //如果不开启depthWrite, 深度会错乱。 */ //无解
  58823. gl.disable(gl.DEPTH_TEST);
  58824. gl.depthMask(true);
  58825. }else {
  58826. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  58827. gl.disable(gl.DEPTH_TEST);
  58828. gl.depthMask(false);
  58829. }
  58830. } else {
  58831. gl.disable(gl.BLEND);
  58832. gl.depthMask(true);
  58833. gl.enable(gl.DEPTH_TEST);
  58834. }
  58835. if(params.blendFunc !== undefined){
  58836. gl.enable(gl.BLEND);
  58837. gl.blendFunc(...params.blendFunc);
  58838. }
  58839. if(params.depthTest !== undefined){
  58840. if(params.depthTest === true){
  58841. gl.enable(gl.DEPTH_TEST);
  58842. }else {
  58843. gl.disable(gl.DEPTH_TEST);
  58844. }
  58845. }
  58846. if(params.depthWrite !== undefined){
  58847. if(params.depthWrite === true){
  58848. gl.depthMask(true);
  58849. }else {
  58850. gl.depthMask(false);
  58851. }
  58852. }
  58853. //---------------------------------
  58854. for (let node of nodes) {
  58855. if(exports.debug.allowedNodes !== undefined){
  58856. if(!exports.debug.allowedNodes.includes(node.name)){
  58857. continue;
  58858. }
  58859. }
  58860. let world = node.sceneNode.matrixWorld;
  58861. worldView.multiplyMatrices(view, world);
  58862. if (visibilityTextureData) {
  58863. let vnStart = visibilityTextureData.offsets.get(node);
  58864. console.log('vnStart',vnStart);
  58865. shader.setUniform1f("uVNStart", vnStart);
  58866. }
  58867. let level = node.getLevel();
  58868. if(node.debug){
  58869. shader.setUniform("uDebug", true);
  58870. }else {
  58871. shader.setUniform("uDebug", false);
  58872. }
  58873. // let isLeaf = false;
  58874. // if(node instanceof PointCloudOctreeNode){
  58875. // isLeaf = Object.keys(node.children).length === 0;
  58876. // }else if(node instanceof PointCloudArena4DNode){
  58877. // isLeaf = node.geometryNode.isLeaf;
  58878. // }
  58879. // shader.setUniform("uIsLeafNode", isLeaf);
  58880. // let isLeaf = node.children.filter(n => n != null).length === 0;
  58881. // if(!isLeaf){
  58882. // continue;
  58883. // }
  58884. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  58885. const lModel = shader.uniformLocations["modelMatrix"];
  58886. if (lModel) {
  58887. mat4holder.set(world.elements);
  58888. gl.uniformMatrix4fv(lModel, false, mat4holder);
  58889. }
  58890. const lModelView = shader.uniformLocations["modelViewMatrix"];
  58891. //mat4holder.set(worldView.elements);
  58892. // faster then set in chrome 63
  58893. for(let j = 0; j < 16; j++){
  58894. mat4holder[j] = worldView.elements[j];
  58895. }
  58896. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  58897. { // Clip Polygons
  58898. if(material.clipPolygons && material.clipPolygons.length > 0){
  58899. let clipPolygonVCount = [];
  58900. let worldViewProjMatrices = [];
  58901. for(let clipPolygon of material.clipPolygons){
  58902. let view = clipPolygon.viewMatrix;
  58903. let proj = clipPolygon.projMatrix;
  58904. let worldViewProj = proj.clone().multiply(view).multiply(world);
  58905. clipPolygonVCount.push(clipPolygon.markers.length);
  58906. worldViewProjMatrices.push(worldViewProj);
  58907. }
  58908. let flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  58909. let flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  58910. for(let i = 0; i < material.clipPolygons.length; i++){
  58911. let clipPolygon = material.clipPolygons[i];
  58912. for(let j = 0; j < clipPolygon.markers.length; j++){
  58913. flattenedVertices[i * 24 + (j * 3 + 0)] = clipPolygon.markers[j].position.x;
  58914. flattenedVertices[i * 24 + (j * 3 + 1)] = clipPolygon.markers[j].position.y;
  58915. flattenedVertices[i * 24 + (j * 3 + 2)] = clipPolygon.markers[j].position.z;
  58916. }
  58917. }
  58918. const lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  58919. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  58920. const lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  58921. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  58922. const lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  58923. gl.uniform3fv(lClipPolygons, flattenedVertices);
  58924. }
  58925. }
  58926. //shader.setUniformMatrix4("modelMatrix", world);
  58927. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  58928. shader.setUniform1f("uLevel", level);
  58929. shader.setUniform1f("levelPercent", octree.nodeMaxLevel ? level / octree.nodeMaxLevel : 0.5);//xzw add
  58930. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  58931. shader.setUniform1f("uPCIndex", i);
  58932. // uBBSize
  58933. if (shadowMaps.length > 0) {
  58934. const lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  58935. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  58936. let bindingStart = 5;
  58937. let bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => (a + i));
  58938. gl.uniform1iv(lShadowMap, bindingPoints);
  58939. for (let i = 0; i < shadowMaps.length; i++) {
  58940. let shadowMap = shadowMaps[i];
  58941. let bindingPoint = bindingPoints[i];
  58942. let glTexture = this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  58943. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  58944. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  58945. }
  58946. {
  58947. let worldViewMatrices = shadowMaps
  58948. .map(sm => sm.camera.matrixWorldInverse)
  58949. .map(view => new Matrix4().multiplyMatrices(view, world));
  58950. let flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  58951. const lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  58952. gl.uniformMatrix4fv(lWorldView, false, flattenedMatrices);
  58953. }
  58954. {
  58955. let flattenedMatrices = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  58956. const lProj = shader.uniformLocations["uShadowProj[0]"];
  58957. gl.uniformMatrix4fv(lProj, false, flattenedMatrices);
  58958. }
  58959. }
  58960. const geometry = node.geometryNode.geometry;
  58961. if(geometry.attributes["gps-time"]){
  58962. const bufferAttribute = geometry.attributes["gps-time"];
  58963. const attGPS = octree.getAttribute("gps-time");
  58964. let initialRange = attGPS.initialRange;
  58965. let initialRangeSize = initialRange[1] - initialRange[0];
  58966. let globalRange = attGPS.range;
  58967. let globalRangeSize = globalRange[1] - globalRange[0];
  58968. let scale = initialRangeSize / globalRangeSize;
  58969. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  58970. scale = Number.isNaN(scale) ? 1 : scale;
  58971. offset = Number.isNaN(offset) ? 0 : offset;
  58972. shader.setUniform1f("uGpsScale", scale);
  58973. shader.setUniform1f("uGpsOffset", offset);
  58974. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  58975. let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  58976. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  58977. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  58978. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  58979. let normalizedClipRange = [
  58980. (uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize,
  58981. (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize,
  58982. ];
  58983. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  58984. // // ranges in full gps coordinate system
  58985. // const globalRange = attGPS.range;
  58986. // const bufferRange = bufferAttribute.potree.range;
  58987. // // ranges in [0, 1]
  58988. // // normalizedGlobalRange = [0, 1]
  58989. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  58990. // const globalWidth = globalRange[1] - globalRange[0];
  58991. // const normalizedBufferRange = [
  58992. // (bufferRange[0] - globalRange[0]) / globalWidth,
  58993. // (bufferRange[1] - globalRange[0]) / globalWidth,
  58994. // ];
  58995. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  58996. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  58997. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  58998. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  58999. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  59000. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  59001. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  59002. }
  59003. {
  59004. let uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  59005. let uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  59006. let uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  59007. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  59008. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  59009. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  59010. }
  59011. let webglBuffer = null;
  59012. if(!this.buffers.has(geometry)){
  59013. webglBuffer = this.createBuffer(geometry);
  59014. this.buffers.set(geometry, webglBuffer);
  59015. }else {
  59016. webglBuffer = this.buffers.get(geometry);
  59017. for(let attributeName in geometry.attributes){
  59018. let attribute = geometry.attributes[attributeName];
  59019. if(attribute.version > webglBuffer.vbos.get(attributeName).version){
  59020. this.updateBuffer(geometry);
  59021. }
  59022. }
  59023. }
  59024. gl.bindVertexArray(webglBuffer.vao);
  59025. let isExtraAttribute =
  59026. attributeLocations$1[material.activeAttributeName] === undefined
  59027. && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  59028. if(isExtraAttribute){
  59029. const attributeLocation = attributeLocations$1["aExtra"].location;
  59030. for(const attributeName in geometry.attributes){
  59031. const bufferAttribute = geometry.attributes[attributeName];
  59032. const vbo = webglBuffer.vbos.get(attributeName);
  59033. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  59034. gl.disableVertexAttribArray(attributeLocation);
  59035. }
  59036. const attName = material.activeAttributeName;
  59037. const bufferAttribute = geometry.attributes[attName];
  59038. const vbo = webglBuffer.vbos.get(attName);
  59039. if(bufferAttribute !== undefined && vbo !== undefined){
  59040. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  59041. let normalized = bufferAttribute.normalized;
  59042. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  59043. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  59044. gl.enableVertexAttribArray(attributeLocation);
  59045. }
  59046. {
  59047. const attExtra = octree.pcoGeometry.pointAttributes.attributes
  59048. .find(a => a.name === attName);
  59049. let range = material.getRange(attName);
  59050. if(!range){
  59051. range = attExtra.range;
  59052. }
  59053. if(!range){
  59054. range = [0, 1];
  59055. }
  59056. let initialRange = attExtra.initialRange;
  59057. let initialRangeSize = initialRange[1] - initialRange[0];
  59058. let globalRange = range;
  59059. let globalRangeSize = globalRange[1] - globalRange[0];
  59060. let scale = initialRangeSize / globalRangeSize;
  59061. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  59062. scale = Number.isNaN(scale) ? 1 : scale;
  59063. offset = Number.isNaN(offset) ? 0 : offset;
  59064. shader.setUniform1f("uExtraScale", scale);
  59065. shader.setUniform1f("uExtraOffset", offset);
  59066. }
  59067. }else {
  59068. for(const attributeName in geometry.attributes){
  59069. const bufferAttribute = geometry.attributes[attributeName];
  59070. const vbo = webglBuffer.vbos.get(attributeName);
  59071. if(attributeLocations$1[attributeName] !== undefined){
  59072. const attributeLocation = attributeLocations$1[attributeName].location;
  59073. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  59074. let normalized = bufferAttribute.normalized;
  59075. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  59076. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  59077. gl.enableVertexAttribArray(attributeLocation);
  59078. }
  59079. }
  59080. }
  59081. let numPoints = webglBuffer.numElements;
  59082. gl.drawArrays(gl.POINTS, 0, numPoints);
  59083. //gl.drawArrays(gl.TRIANGLES, 0, numPoints);
  59084. i++;
  59085. }
  59086. gl.bindVertexArray(null);
  59087. viewer.addTimeMark('renderNodes','end');
  59088. }
  59089. renderOctree(octrees, nodes, camera, target, params = {}){
  59090. viewer.addTimeMark('renderOctree','start');
  59091. let octree;
  59092. if(octrees instanceof Array){
  59093. octree = octrees[0];
  59094. }else {
  59095. octree = octrees; octrees = [octree];
  59096. }
  59097. let gl = this.gl;
  59098. let material = params.material ? params.material : octree.material;
  59099. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  59100. let view = camera.matrixWorldInverse;
  59101. let viewInv = camera.matrixWorld;
  59102. if(params.viewOverride){
  59103. view = params.viewOverride;
  59104. viewInv = view.clone().invert();
  59105. }
  59106. let proj = camera.projectionMatrix;
  59107. let projInv = proj.clone().invert();
  59108. //let worldView = new THREE.Matrix4();
  59109. let shader = null;
  59110. let visibilityTextureData = null;
  59111. let currentTextureBindingPoint = 0;
  59112. if (material.pointSizeType >= 0) {//最好搬到renderNodes
  59113. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  59114. material.activeAttributeName === "level of detail") {
  59115. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  59116. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  59117. const vnt = material.visibleNodesTexture;
  59118. const data = vnt.image.data;
  59119. data.set(visibilityTextureData.data);
  59120. vnt.needsUpdate = true;
  59121. }
  59122. }
  59123. { // UPDATE SHADER AND TEXTURES
  59124. if (!this.shaders.has(material)) {
  59125. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  59126. let shader = new Shader$1(gl, "pointcloud", vs, fs);
  59127. this.shaders.set(material, shader);
  59128. }
  59129. shader = this.shaders.get(material);
  59130. if(material.shaderNeedsUpdate)
  59131. {
  59132. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  59133. let numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  59134. let num_in_clipboxes = (material.clipBoxes_in && material.clipBoxes_in.length) ? material.clipBoxes_in.length : 0;
  59135. let num_out_clipboxes = (material.clipBoxes_out && material.clipBoxes_out.length) ? material.clipBoxes_out.length : 0;
  59136. let num_highlightBox = (material.highlightBoxes && material.highlightBoxes.length) ? material.highlightBoxes.length : 0;
  59137. let numClipSpheres = (params.clipSpheres && params.clipSpheres.length) ? params.clipSpheres.length : 0;
  59138. let numClipPolygons = (material.clipPolygons && material.clipPolygons.length) ? material.clipPolygons.length : 0;
  59139. let defines = [
  59140. `#define num_shadowmaps ${shadowMaps.length}`,
  59141. `#define num_snapshots ${numSnapshots}`,
  59142. `#define num_in_clipboxes ${num_in_clipboxes}`, //改
  59143. `#define num_out_clipboxes ${num_out_clipboxes}`, //改
  59144. `#define num_highlightBox ${num_highlightBox}`, //改
  59145. `#define num_clipspheres ${numClipSpheres}`,
  59146. ];
  59147. //add:-----------
  59148. if(material.bigClipInBox ){//裁剪下载
  59149. defines.push('#define bigClipInBox');
  59150. }
  59151. if(material.usePanoMap){
  59152. defines.push("#define usePanoMap");
  59153. }
  59154. if(material.useFilterByNormal){
  59155. defines.push("#define use_filter_by_normal");
  59156. //Potree.settings.editType == 'pano' ? defines.push("#define attenuated_opacity2") : defines.push("#define attenuated_opacity");
  59157. }
  59158. //---------------
  59159. if(octree.pcoGeometry.root.isLoaded()){
  59160. let attributes = octree.pcoGeometry.root.geometry.attributes;
  59161. if(attributes["gps-time"]){
  59162. defines.push("#define clip_gps_enabled");
  59163. }
  59164. if(attributes["return number"]){
  59165. defines.push("#define clip_return_number_enabled");
  59166. }
  59167. if(attributes["number of returns"]){
  59168. defines.push("#define clip_number_of_returns_enabled");
  59169. }
  59170. if(attributes["source id"] || attributes["point source id"]){
  59171. defines.push("#define clip_point_source_id_enabled");
  59172. }
  59173. }
  59174. let definesString = defines.join("\n");
  59175. let vsVersionIndex = vs.indexOf("#version ");
  59176. let fsVersionIndex = fs.indexOf("#version ");
  59177. if(vsVersionIndex >= 0){
  59178. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  59179. }else {
  59180. vs = `${definesString}\n${vs}`;
  59181. }
  59182. if(fsVersionIndex >= 0){
  59183. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  59184. }else {
  59185. fs = `${definesString}\n${fs}`;
  59186. }
  59187. shader.update(vs, fs);
  59188. material.shaderNeedsUpdate = false;
  59189. }
  59190. for (let uniformName of Object.keys(material.uniforms)) {
  59191. let uniform = material.uniforms[uniformName];
  59192. if (uniform.type == "t") {
  59193. let texture = uniform.value;
  59194. if (!texture) {
  59195. continue;
  59196. }
  59197. //add
  59198. if(uniformName == 'pano0Map' || uniformName == 'pano1Map' ){ //属于cubeTex,另外设置
  59199. continue
  59200. }
  59201. if (!this.textures.has(texture)) {
  59202. let webglTexture = new WebGLTexture$1(gl, texture);
  59203. this.textures.set(texture, webglTexture);
  59204. }
  59205. let webGLTexture = this.textures.get(texture);
  59206. webGLTexture.update();
  59207. }
  59208. }
  59209. }
  59210. gl.useProgram(shader.program);
  59211. /* let transparent = false;
  59212. if(params.transparent !== undefined){
  59213. transparent = params.transparent && material.opacity < 1;
  59214. }else{
  59215. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  59216. }
  59217. if (transparent){
  59218. gl.enable(gl.BLEND);
  59219. if(params.notAdditiveBlending){
  59220. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending
  59221. gl.enable(gl.DEPTH_TEST);
  59222. gl.depthMask(true); //如果不开启depthWrite,深度会错乱。
  59223. }else{
  59224. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  59225. gl.disable(gl.DEPTH_TEST);
  59226. gl.depthMask(false);
  59227. }
  59228. } else {
  59229. gl.disable(gl.BLEND);
  59230. gl.depthMask(true);
  59231. gl.enable(gl.DEPTH_TEST);
  59232. }
  59233. if(params.blendFunc !== undefined){
  59234. gl.enable(gl.BLEND);
  59235. gl.blendFunc(...params.blendFunc);
  59236. }
  59237. if(params.depthTest !== undefined){
  59238. if(params.depthTest === true){
  59239. gl.enable(gl.DEPTH_TEST);
  59240. }else{
  59241. gl.disable(gl.DEPTH_TEST);
  59242. }
  59243. }
  59244. if(params.depthWrite !== undefined){
  59245. if(params.depthWrite === true){
  59246. gl.depthMask(true);
  59247. }else{
  59248. gl.depthMask(false);
  59249. }
  59250. } */
  59251. { // UPDATE UNIFORMS
  59252. shader.setUniformMatrix4("projectionMatrix", proj);
  59253. shader.setUniformMatrix4("viewMatrix", view);
  59254. shader.setUniformMatrix4("uViewInv", viewInv);
  59255. shader.setUniformMatrix4("uProjInv", projInv);
  59256. /* let screenWidth = target ? target.width : material.screenWidth;
  59257. let screenHeight = target ? target.height : material.screenHeight;
  59258. shader.setUniform1f("uScreenWidth", screenWidth);
  59259. shader.setUniform1f("uScreenHeight", screenHeight); */
  59260. shader.setUniform2f('resolution', material.resolution.toArray());
  59261. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  59262. shader.setUniform1f("near", camera.near);
  59263. shader.setUniform1f("far", camera.far);
  59264. if(camera instanceof OrthographicCamera){
  59265. shader.setUniform("uUseOrthographicCamera", true);
  59266. shader.setUniform("uOrthoWidth", (camera.right - camera.left) / camera.zoom); //改
  59267. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  59268. }else {
  59269. shader.setUniform("uUseOrthographicCamera", false);
  59270. }
  59271. /* if(material.clipBoxes.length + material.clipPolygons.length === 0){//改
  59272. shader.setUniform1i("clipTask", ClipTask.NONE);
  59273. }else{
  59274. shader.setUniform1i("clipTask", material.clipTask);
  59275. }
  59276. shader.setUniform1i("clipMethod", material.clipMethod);*/
  59277. //改
  59278. if (material.clipBoxes_in && material.clipBoxes_in.length > 0) {
  59279. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  59280. const lClipBoxes = shader.uniformLocations["clipBoxes_in[0]"];
  59281. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes_in.value);
  59282. }
  59283. if (material.clipBoxes_out && material.clipBoxes_out.length > 0) {//add
  59284. const lClipBoxes2 = shader.uniformLocations["clipBoxes_out[0]"];
  59285. gl.uniformMatrix4fv(lClipBoxes2, false, material.uniforms.clipBoxes_out.value);
  59286. }
  59287. if (material.highlightBoxes && material.highlightBoxes.length > 0) {//add
  59288. const boxes_highlight = shader.uniformLocations["boxes_highlight[0]"];
  59289. gl.uniformMatrix4fv(boxes_highlight, false, material.uniforms.boxes_highlight.value);
  59290. }
  59291. if (material.bigClipInBox ) {//add
  59292. shader.setUniformMatrix4("clipBoxBig_in", material.uniforms.clipBoxBig_in.value);
  59293. }
  59294. // TODO CLIPSPHERES
  59295. if(params.clipSpheres && params.clipSpheres.length > 0){
  59296. let clipSpheres = params.clipSpheres;
  59297. let matrices = [];
  59298. for(let clipSphere of clipSpheres){
  59299. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  59300. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  59301. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  59302. let clipToWorld = clipSphere.matrixWorld;
  59303. let viewToWorld = camera.matrixWorld;
  59304. let worldToClip = clipToWorld.clone().invert();
  59305. let viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  59306. matrices.push(viewToClip);
  59307. }
  59308. let flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  59309. const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  59310. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  59311. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  59312. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  59313. }
  59314. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  59315. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  59316. // uniform float uPCIndex
  59317. shader.setUniform1f("uOctreeSpacing", material.spacing);
  59318. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  59319. shader.setUniform2f("elevationRange", material.elevationRange);
  59320. shader.setUniform2f("intensityRange", material.intensityRange);
  59321. shader.setUniform3f("uIntensity_gbc", [
  59322. material.intensityGamma,
  59323. material.intensityBrightness,
  59324. material.intensityContrast
  59325. ]);
  59326. shader.setUniform3f("uRGB_gbc", [
  59327. material.rgbGamma,
  59328. material.rgbBrightness,
  59329. material.rgbContrast
  59330. ]);
  59331. shader.setUniform1f("uTransition", material.transition);
  59332. shader.setUniform1f("wRGB", material.weightRGB);
  59333. shader.setUniform1f("wIntensity", material.weightIntensity);
  59334. shader.setUniform1f("wElevation", material.weightElevation);
  59335. shader.setUniform1f("wClassification", material.weightClassification);
  59336. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  59337. shader.setUniform1f("wSourceID", material.weightSourceID);
  59338. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  59339. //==========================
  59340. //gl.TEXTURE_CUBE_MAP: 34067
  59341. //gl.TEXTURE0=33984 , vnWebGLTexture.target=gl.TEXTURE_2D = 3353
  59342. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);//最好搬到renderNodes
  59343. if(vnWebGLTexture){
  59344. shader.setUniform1i("visibleNodes", currentTextureBindingPoint); //为何之前写的是"visibleNodesTexture",但和"visibleNodes"效果相同?可shader里只有"visibleNodes"
  59345. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  59346. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  59347. currentTextureBindingPoint++;
  59348. }
  59349. let gradientTexture = this.textures.get(material.gradientTexture);
  59350. shader.setUniform1i("gradient", currentTextureBindingPoint);
  59351. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  59352. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  59353. currentTextureBindingPoint++;
  59354. const repeat = material.elevationGradientRepeat;
  59355. if(repeat === ElevationGradientRepeat.REPEAT){
  59356. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  59357. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  59358. }else if(repeat === ElevationGradientRepeat.MIRRORED_REPEAT){
  59359. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  59360. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  59361. }else {
  59362. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  59363. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  59364. }
  59365. currentTextureBindingPoint++;
  59366. let classificationTexture = this.textures.get(material.classificationTexture);
  59367. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  59368. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  59369. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  59370. currentTextureBindingPoint++;
  59371. /* let matcapTexture = this.textures.get(material.matcapTexture);
  59372. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  59373. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  59374. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  59375. currentTextureBindingPoint++; */
  59376. if (material.snapEnabled === true) {
  59377. {
  59378. const lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  59379. const lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  59380. let bindingStart = currentTextureBindingPoint;
  59381. let lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => (a + i));
  59382. let lSnapshotDepthBindingPoints = new Array(5)
  59383. .fill(1 + Math.max(...lSnapshotBindingPoints))
  59384. .map((a, i) => (a + i));
  59385. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  59386. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  59387. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  59388. for (let i = 0; i < 5; i++) {
  59389. let texture = material.uniforms[`uSnapshot`].value[i];
  59390. let textureDepth = material.uniforms[`uSnapshotDepth`].value[i];
  59391. if (!texture) {
  59392. break;
  59393. }
  59394. let snapTexture = this.threeRenderer.properties.get(texture).__webglTexture;
  59395. let snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  59396. let bindingPoint = lSnapshotBindingPoints[i];
  59397. let depthBindingPoint = lSnapshotDepthBindingPoints[i];
  59398. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  59399. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  59400. gl.activeTexture(gl[`TEXTURE${depthBindingPoint}`]);
  59401. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  59402. }
  59403. }
  59404. {
  59405. let flattenedMatrices = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  59406. const lSnapView = shader.uniformLocations["uSnapView[0]"];
  59407. gl.uniformMatrix4fv(lSnapView, false, flattenedMatrices);
  59408. }
  59409. {
  59410. let flattenedMatrices = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  59411. const lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  59412. gl.uniformMatrix4fv(lSnapProj, false, flattenedMatrices);
  59413. }
  59414. {
  59415. let flattenedMatrices = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  59416. const lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  59417. gl.uniformMatrix4fv(lSnapProjInv, false, flattenedMatrices);
  59418. }
  59419. {
  59420. let flattenedMatrices = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  59421. const lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  59422. gl.uniformMatrix4fv(lSnapViewInv, false, flattenedMatrices);
  59423. }
  59424. }
  59425. //=============add===========
  59426. if(material.usePanoMap){//为什么pointsize失效
  59427. shader.setUniform1f("progress", material.uniforms.progress.value);
  59428. shader.setUniform1f("easeInOutRatio", material.uniforms.easeInOutRatio.value);
  59429. shader.setUniform3f("pano0Position", material.uniforms.pano0Position.value.toArray());
  59430. shader.setUniform3f("pano1Position", material.uniforms.pano1Position.value.toArray());
  59431. shader.setUniform('pano0Matrix', material.uniforms.pano0Matrix.value);
  59432. shader.setUniform('pano1Matrix', material.uniforms.pano1Matrix.value);
  59433. let pano0Map = material.uniforms.pano0Map.value;
  59434. if(pano0Map){
  59435. this.threeRenderer._textures.safeSetTextureCube( pano0Map, ++currentTextureBindingPoint );
  59436. shader.setUniform1i('pano0Map', currentTextureBindingPoint);
  59437. }
  59438. let pano1Map = material.uniforms.pano1Map.value;
  59439. if(pano1Map){
  59440. this.threeRenderer._textures.safeSetTextureCube( pano1Map, ++currentTextureBindingPoint );
  59441. shader.setUniform1i('pano1Map', currentTextureBindingPoint);
  59442. }
  59443. //注: three.js我添加了个 _textures, safeSetTextureCube里主要就是activeTexture和bindTexture
  59444. }
  59445. }
  59446. viewer.addTimeMark('renderOctree','end');
  59447. params.currentTextureBindingPoint = currentTextureBindingPoint;
  59448. octrees.forEach(octree=>{
  59449. this.renderNodes(octree, nodes || octree.visibleNodes, visibilityTextureData, camera, target, shader, params);
  59450. });
  59451. gl.activeTexture(gl.TEXTURE2);
  59452. gl.bindTexture(gl.TEXTURE_2D, null);
  59453. gl.activeTexture(gl.TEXTURE0);
  59454. //gl.bindTexture(gl.TEXTURE_2D, null); //add
  59455. //add 恢复为不透明(否则renderToCubeMap时的贴图会被渲染成高亮的颜色)
  59456. gl.disable(gl.BLEND);
  59457. gl.depthMask(true);
  59458. gl.enable(gl.DEPTH_TEST);
  59459. //DEPTH_TEST等需要恢复吗
  59460. }
  59461. render(scene, camera, target = null, params = {}) {
  59462. const gl = this.gl;
  59463. // PREPARE
  59464. if (target != null) {
  59465. this.threeRenderer.setRenderTarget(target);
  59466. }
  59467. //camera.updateProjectionMatrix();
  59468. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  59469. const traversalResult = this.traverse(scene);
  59470. //排序
  59471. if(params.notAdditiveBlending){//add
  59472. traversalResult.octrees.forEach(tree=>{
  59473. if(tree.material.opacity==1){
  59474. tree._z = Infinity; //不透明的先渲染
  59475. }else {
  59476. let center = tree.boundCenter ? tree.boundCenter.clone() : tree.boundingBox.getCenter(tree.boundCenter).applyMatrix4(tree.matrixWorld);
  59477. center.project(camera);
  59478. tree._z = center.z;
  59479. }
  59480. });
  59481. traversalResult.octrees.sort((tree1,tree2)=>{
  59482. return tree2._z - tree1._z //降序 (-1 朝外)。 离屏幕近的后渲染
  59483. });
  59484. }
  59485. // RENDER
  59486. let mat = traversalResult.octrees[0].material;
  59487. if(Potree.settings.cloudSameMat && viewer.scene.volumes.length == 0 && mat.pointSizeType != PointSizeType.ADAPTIVE && mat.activeAttributeName != "level of detail"){
  59488. this.renderOctree(traversalResult.octrees, null, camera, target, params); //所有点云除了个别属性需要在shader中更新,其他都使用第一个点云的材质
  59489. }else for (const octree of traversalResult.octrees) {
  59490. for (const octree of traversalResult.octrees) {
  59491. this.renderOctree(octree, octree.visibleNodes, camera, target, params);
  59492. }
  59493. }
  59494. //if (octree material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") {
  59495. // CLEANUP
  59496. gl.activeTexture(gl.TEXTURE1);
  59497. gl.bindTexture(gl.TEXTURE_2D, null);
  59498. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  59499. gl.bindVertexArray(null);
  59500. this.threeRenderer.resetState();
  59501. }
  59502. };
  59503. /*
  59504. 中东的链接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
  59505. geometry: 有的attributes: 属性是:
  59506. classification:
  59507. color:
  59508. indices:
  59509. normal:
  59510. position:
  59511. 最好有个spacing
  59512. */
  59513. //
  59514. // Algorithm by Christian Boucheny
  59515. // shader code taken and adapted from CloudCompare
  59516. //
  59517. // see
  59518. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  59519. // http://www.kitware.com/source/home/post/9
  59520. // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french)
  59521. class ExtendEyeDomeLightingMaterial extends EyeDomeLightingMaterial{
  59522. constructor(parameters = {}){
  59523. super(parameters);
  59524. delete this.uniforms.screenWidth;
  59525. delete this.uniforms.screenHeight;
  59526. this.uniforms.resolution = { type: 'v2', value: new Vector2()};
  59527. this.uniforms.useEDL = { type: 'i', value: 1 };
  59528. this.vertexShader = this.getDefines() + Shaders['edl_new.vs']; //改
  59529. this.fragmentShader = this.getDefines() + Shaders['edl_new.fs']; //改
  59530. }
  59531. }
  59532. const copyShader = {
  59533. uniforms: {
  59534. tDiffuse: {
  59535. type: "t",
  59536. value: null
  59537. },
  59538. opacity: {
  59539. type: "f",
  59540. value: 1
  59541. },
  59542. depthTex: {
  59543. type: "t",
  59544. value: null
  59545. }
  59546. },
  59547. vertexShader: `
  59548. varying vec2 vUv;
  59549. void main() {
  59550. vUv = uv;
  59551. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  59552. }
  59553. `,
  59554. fragmentShader: `
  59555. #extension GL_EXT_frag_depth : enable
  59556. uniform float opacity;
  59557. uniform sampler2D tDiffuse;
  59558. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  59559. uniform sampler2D depthTex;
  59560. #endif
  59561. varying vec2 vUv;
  59562. void main() {
  59563. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  59564. float depth = texture2D(depthTex, vUv).r;
  59565. /* if(depth >= 1.0){ //超级远(但是在modelTex里我把天空距离超出far了,所以不删)
  59566. discard;
  59567. } */
  59568. gl_FragDepthEXT = depth;
  59569. #endif
  59570. vec4 texel = texture2D( tDiffuse, vUv );
  59571. gl_FragColor = opacity * texel;
  59572. }
  59573. `
  59574. };
  59575. //import DepthTexSampler from "../custom/utils/DepthTexSampler.js";
  59576. class EDLRenderer{//Eye-Dome Lighting 眼罩照明
  59577. constructor(viewer){
  59578. this.viewer = viewer;
  59579. this.edlMaterial = null;
  59580. //this.rtRegular;
  59581. this.rtEDLs = new Map;
  59582. this.gl = viewer.renderer.getContext();
  59583. //反正也没用到,注释了:
  59584. //this.shadowMap = new PointCloudSM(this.viewer.pRenderer);
  59585. viewer.addEventListener('resize',this.resize.bind(this));
  59586. this.initEDL(viewer);
  59587. }
  59588. initEDL(viewer){
  59589. if (this.edlMaterial != null || !Features.EXT_DEPTH.isSupported()){
  59590. return;
  59591. }
  59592. this.edlMaterial = new ExtendEyeDomeLightingMaterial();
  59593. this.edlMaterial.depthTest = true;
  59594. this.edlMaterial.depthWrite = true;
  59595. this.edlMaterial.transparent = true;
  59596. let copyUniforms = UniformsUtils.clone( copyShader.uniforms );
  59597. this.recoverToScreenMat = new ShaderMaterial({
  59598. uniforms: copyUniforms,
  59599. vertexShader:copyShader.vertexShader,
  59600. fragmentShader: copyShader.fragmentShader,
  59601. transparent: true,
  59602. defines:{
  59603. useDepth: true //开启后,其他物体才能被遮挡
  59604. }
  59605. });
  59606. /* let copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms );
  59607. this.copyMaterial = new THREE.ShaderMaterial( {
  59608. uniforms: copyUniforms,
  59609. vertexShader: copyShader.vertexShader,
  59610. fragmentShader: copyShader.fragmentShader,
  59611. //premultipliedAlpha: true,
  59612. transparent: true,
  59613. //blending: THREE.AdditiveBlending,
  59614. depthTest: false,
  59615. depthWrite: false
  59616. }); */
  59617. if(Potree.settings.useRTskybox != Potree.settings.useRTPoint){//如果两个只开了一个
  59618. viewer.images360.addEventListener('endChangeMode',()=>{
  59619. this.resize({viewport:viewer.mainViewport});
  59620. });
  59621. }
  59622. //this.depthTexSampler = new DepthTexSampler(this);
  59623. };
  59624. resize(e){
  59625. if(Features.EXT_DEPTH.isSupported()){
  59626. let viewport = e.viewport;
  59627. let size = ( Potree.settings.displayMode == 'showPanos' ? Potree.settings.useRTskybox : Potree.settings.useRTPoint) ? viewport.resolution2 : viewport.resolution; //若要渲染skybox,需要和设备一样精度的rt
  59628. this.getRtEDL(viewport).setSize( size.x, size.y ); //理论上可以是任意尺寸,但会影响精度,且aspect最好和渲染的一致
  59629. }
  59630. }
  59631. clearTargets(params={}){
  59632. const viewer = this.viewer;
  59633. const {renderer} = viewer;
  59634. const oldTarget = renderer.getRenderTarget();
  59635. if(params.target){//add
  59636. renderer.setRenderTarget( params.target);
  59637. renderer.clear();
  59638. }
  59639. if(Features.EXT_DEPTH.isSupported()){
  59640. if(params.rtEDL){
  59641. renderer.setRenderTarget( params.rtEDL);
  59642. renderer.clear();
  59643. }else {
  59644. var rtEDL = this.getRtEDL(params.viewport);
  59645. if(rtEDL){
  59646. renderer.setRenderTarget( rtEDL );
  59647. renderer.clear( true, true, true );
  59648. }
  59649. }
  59650. }
  59651. //renderer.setRenderTarget( this.rtRegular );
  59652. //renderer.clear( true, true, false );
  59653. renderer.setRenderTarget(oldTarget);
  59654. }
  59655. getRtEDL(viewport){//根据不同viewport返回rtEDL的texture
  59656. if(!viewport){
  59657. console.warn('getRtEDL没传viewport!!!! !!!!!!!!!!');
  59658. viewport = viewer.mainViewport;
  59659. }
  59660. var rtEDL = this.rtEDLs.get(viewport);
  59661. if(!rtEDL){
  59662. if(Features.EXT_DEPTH.isSupported()){
  59663. rtEDL = new WebGLRenderTarget(viewport.resolution.x, viewport.resolution.y, {
  59664. minFilter: NearestFilter,
  59665. magFilter: NearestFilter,
  59666. format: RGBAFormat,
  59667. type: FloatType,
  59668. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  59669. });
  59670. //注: 部分手机在resize时会崩溃,经检验去掉rtEDL的resize可以解决,所以更应该注释掉这个
  59671. this.rtEDLs.set(viewport, rtEDL);
  59672. }
  59673. }
  59674. //注:当pc窗口缩小,deviceRatio变小后,resolution2会小于resolution,然后遮挡会出现精度损失而有细微不准,是正常现象。
  59675. return rtEDL
  59676. }
  59677. renderShadowMap(visiblePointClouds, camera, lights){
  59678. const {viewer} = this;
  59679. const doShadows = lights.length > 0 && !(lights[0].disableShadowUpdates);
  59680. if(doShadows){
  59681. let light = lights[0];
  59682. this.shadowMap.setLight(light);
  59683. let originalAttributes = new Map();
  59684. for(let pointcloud of viewer.scene.pointclouds){
  59685. // TODO IMPORTANT !!! check
  59686. originalAttributes.set(pointcloud, pointcloud.material.activeAttributeName);
  59687. pointcloud.material.disableEvents();
  59688. pointcloud.material.activeAttributeName = "depth";
  59689. //pointcloud.material.pointColorType = PointColorType.DEPTH;
  59690. }
  59691. this.shadowMap.render(viewer.scene.scenePointCloud, camera);
  59692. for(let pointcloud of visiblePointClouds){
  59693. let originalAttribute = originalAttributes.get(pointcloud);
  59694. // TODO IMPORTANT !!! check
  59695. pointcloud.material.activeAttributeName = originalAttribute;
  59696. pointcloud.material.enableEvents();
  59697. }
  59698. viewer.shadowTestCam.updateMatrixWorld();
  59699. viewer.shadowTestCam.matrixWorldInverse.copy(viewer.shadowTestCam.matrixWorld).invert();
  59700. viewer.shadowTestCam.updateProjectionMatrix();
  59701. }
  59702. }
  59703. render(params={}){
  59704. const viewer = this.viewer;
  59705. let camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  59706. let rtEDL = (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL) &&
  59707. Features.EXT_DEPTH.isSupported() && camera.type != "OrthographicCamera" && !params.dontRenderRtEDL && (params.rtEDL || this.getRtEDL(params.viewport)); // 平面相机不用depthTex直接打开depthTest?且不使用edl
  59708. let useEDL = viewer.useEDL && rtEDL && Potree.settings.displayMode != 'showPanos';
  59709. let target = params.target || null;
  59710. const 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的大小
  59711. viewer.renderer.setRenderTarget(target);
  59712. //viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  59713. let lights = [];
  59714. /* viewer.scene.scene.traverse(node => {
  59715. if(node.type === "SpotLight"){
  59716. lights.push(node);
  59717. }
  59718. }); */
  59719. //skybox 全景图
  59720. if(!params.magnifier){
  59721. if(Potree.settings.displayMode == 'showPanos' || Potree.settings.testCube ){
  59722. Potree.Utils.setCameraLayers(camera, ['skybox']);
  59723. if((Potree.settings.displayMode == 'showPanos' )&& viewer.images360.currentPano.pointcloud.hasDepthTex && rtEDL){//渲染深度图
  59724. viewer.renderer.setRenderTarget(rtEDL); //将带有深度图的skybox画在rtEDL一下,这样就不需要绘制后边的点云了
  59725. viewer.renderer.render(viewer.scene.scene, camera);
  59726. viewer.renderer.setRenderTarget(target);
  59727. if(Potree.settings.useRTskybox){//直接使用rtEDL,但是会失去抗锯齿,不知在skybox上需要抗锯齿吗
  59728. this.recoverToScreenMat.uniforms.depthTex.value = rtEDL.depthTexture;
  59729. this.recoverToScreenMat.uniforms.tDiffuse.value = rtEDL.texture;
  59730. Utils.screenPass.render(viewer.renderer, this.recoverToScreenMat, target);
  59731. }else {
  59732. viewer.renderer.render(viewer.scene.scene, camera);
  59733. }
  59734. if(Potree.settings.displayMode == 'showPanos' )return
  59735. }else {
  59736. viewer.renderer.render(viewer.scene.scene, camera);
  59737. }
  59738. }
  59739. }
  59740. const visiblePointClouds2 = viewer.scene.pointclouds.filter(pc => Potree.Utils.getObjVisiByReason(pc,'datasetSelection') ); //需要绘制到rtEDL的
  59741. const showPointClouds = params.magnifier ? visiblePointClouds2.length>0 : viewer.scene.pointclouds.some(e=>e.visible); //是否有需要绘制到屏幕的
  59742. visiblePointClouds2.forEach(e=>{//为了绘制到depthTexture,先显示(展示全景图时隐藏了点云,所以需要显示下。且放大镜需要绘制点云)
  59743. e.oldVisi = e.visible;
  59744. e.visible = true;
  59745. });
  59746. Potree.Utils.setCameraLayers(camera, ['pointcloud']);
  59747. camera.layers.set(Potree.config.renderLayers.pointcloud);
  59748. //TODO adapt to multiple lights
  59749. //this.renderShadowMap(visiblePointClouds2, camera, lights); //???????
  59750. {
  59751. for (let pointcloud of visiblePointClouds2) {
  59752. let material = pointcloud.material;
  59753. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  59754. material.fov = MathUtils.degToRad(camera.fov);
  59755. material.resolution = resolution;
  59756. material.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  59757. material.near = camera.near;
  59758. material.far = camera.far;
  59759. material.uniforms.octreeSize.value = octreeSize;
  59760. if(useEDL ){
  59761. material.useEDL = true;
  59762. //material.fakeEDL = false; //add
  59763. }else {
  59764. material.useEDL = false;
  59765. //material.fakeEDL = true; //add 使也输出深度
  59766. }
  59767. }
  59768. if(rtEDL ){ //借用rtEDL存储深度信息
  59769. viewer.renderer.setRenderTarget( rtEDL );
  59770. if(visiblePointClouds2.length>0){ //渲染scenePointCloud到rtEDL
  59771. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, rtEDL, {
  59772. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  59773. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume$1)),
  59774. transparent: true, //如果点云透明需要透明
  59775. notAdditiveBlending: Potree.settings.notAdditiveBlending
  59776. });
  59777. }
  59778. if(Potree.settings.intersectOnObjs){// model也要渲染到rtEDL
  59779. Potree.Utils.setCameraLayers(camera, ['model','light']);
  59780. viewer.objs.traverse(e=>{if(e.material)e._OlddepthWrite = e.material.depthWrite, e.material.depthWrite = true;}); //否则半透明的mesh无法遮住测量线
  59781. viewer.renderer.render(viewer.scene.scene, camera);
  59782. viewer.objs.traverse(e=>{if(e.material)e.material.depthWrite = e._OlddepthWrite;});
  59783. //缺点:半透明的model 就算完全透明, 也会遮住测量线
  59784. }
  59785. }
  59786. }
  59787. //渲染到rtEDL完毕
  59788. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer });
  59789. viewer.renderer.setRenderTarget( target );
  59790. if(!params.magnifier)visiblePointClouds2.forEach(e=>{//放大镜显示点云
  59791. e.visible = e.oldVisi;
  59792. });
  59793. if(showPointClouds){ //绘制点云到画布
  59794. if(useEDL){ //设置edlMaterial //Features.EXT_DEPTH不支持的话不会到这一块
  59795. const uniforms = this.edlMaterial.uniforms;
  59796. uniforms.resolution.value.copy(resolution);
  59797. uniforms.edlStrength.value = viewer.edlStrength;
  59798. uniforms.radius.value = viewer.edlRadius;
  59799. uniforms.useEDL.value = 1;//add
  59800. let proj = camera.projectionMatrix;
  59801. let projArray = new Float32Array(16);
  59802. projArray.set(proj.elements);
  59803. uniforms.uProj.value = projArray;
  59804. uniforms.uEDLColor.value = rtEDL.texture;
  59805. uniforms.opacity.value = viewer.edlOpacity; // HACK
  59806. Utils.screenPass.render(viewer.renderer, this.edlMaterial, target); //相当于一个描边后期特效。 缺点: 因为target上的没有抗锯齿,所以点云在晃动镜头时会不稳定地闪烁1px位置。优点:比不打开edl少绘制一次点云,更流畅了?!
  59807. }else if(Potree.settings.useRTPoint && rtEDL){
  59808. this.recoverToScreenMat.uniforms.tDiffuse.value = rtEDL.texture;
  59809. if(this.recoverToScreenMat.defines.useDepth){
  59810. this.recoverToScreenMat.uniforms.depthTex.value = rtEDL.depthTexture;
  59811. }
  59812. Utils.screenPass.render(viewer.renderer, this.recoverToScreenMat, target/* , Potree.settings.useFxaa && viewer.composer2 */);
  59813. params.drawedModelOnRT = true;
  59814. }else {
  59815. //渲染点云 (直接用rtEDL上的会失去抗锯齿, 导致频闪、密集时出现条纹, 自己写抗锯齿也要渲染好几次。另外透明度也要处理下)
  59816. let prop = {
  59817. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  59818. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume$1)) ,
  59819. notAdditiveBlending: Potree.settings.notAdditiveBlending//add 否则透明的点云会挡住后面的模型。 加上这句后竟然透明不会叠加了!
  59820. };
  59821. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, null , prop);
  59822. }
  59823. }
  59824. visiblePointClouds2.forEach(e=>{
  59825. e.visible = e.oldVisi;
  59826. });
  59827. //viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  59828. }
  59829. /*
  59830. 渲染顺序:
  59831. 底层:背景 -> skybox(也可中间)
  59832. 中间层(含有深度信息):1 点云、marker等mesh,
  59833. 2 测量线(现在被做成借用depthTex
  59834. 顶层:maginifier
  59835. magnifier的贴图渲染不需要顶层、中间层只需要点云。
  59836. */
  59837. }
  59838. let texLoader$4 = new TextureLoader();
  59839. texLoader$4.crossOrigin = "anonymous";
  59840. let createErrorMaterial = function() {
  59841. var t = new MeshBasicMaterial({
  59842. transparent: !0,
  59843. depthWrite: !1,
  59844. depthTest: !0,
  59845. opacity: 1,
  59846. side: DoubleSide
  59847. });
  59848. return t.color = new Color(3355443),
  59849. t
  59850. };
  59851. let tempVector = new Vector3, //sharedata
  59852. face1 = new Face3(0,1,2),
  59853. face2 = new Face3(2,3,0),
  59854. errorMaterial = createErrorMaterial(),
  59855. uv00 = new Vector2(0,0),
  59856. uv01 = new Vector2(0,1),
  59857. uv10 = new Vector2(1,0),
  59858. uv11 = new Vector2(1,1),
  59859. face1UV = [uv00, uv10, uv11],
  59860. face2UV = [uv11, uv01, uv00];
  59861. const HALF_WORLD_SIZE = 21e6; //略大于半个周长(mapSizeM/2)
  59862. const MAX_VERTICAL_DIST = 2;
  59863. const MAX_VERTICAL_DIST_TO_BEST = 1;
  59864. function defineLocalProj(locationLonLat){
  59865. proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  59866. }
  59867. const getSid = (function(){
  59868. let sid = 0;
  59869. return function(){
  59870. return sid++
  59871. }
  59872. })();
  59873. //高德坐标拾取工具 : https://lbs.amap.com/tools/picker
  59874. class MapLayer extends EventDispatcher{ // 包括了 MapLayerBase SceneLayer
  59875. constructor(viewer_, viewport){
  59876. super();
  59877. this.sceneGroup = new Object3D;
  59878. this.sceneGroup.name = "MapLayer";
  59879. this.waitQueue = []; //等待加载的
  59880. this.loadingInProgress = 0;
  59881. this.maps = [];
  59882. this.frustum = new Frustum;
  59883. this.frustumMatrix = new Matrix4;
  59884. this.tileColor = new Color(16777215);
  59885. this.viewport = viewport;
  59886. this.changeViewer(viewer_);
  59887. //添加地图
  59888. var map = new TiledMapOpenStreetMap(this, this.tileColor );
  59889. this.addMap(map);
  59890. //map.setEnable(false)
  59891. }
  59892. addMapEntity(data, datasetId){
  59893. if(!data || !data[0]){
  59894. Potree.Log('平面图无数据',{font:'red'});
  59895. return
  59896. }
  59897. data[0].datasetId = datasetId;
  59898. var floorplan = new TiledMapFromEntity(this, this.tileColor, data[0] );//[0]?
  59899. if(floorplan){
  59900. floorplan.name += "_"+ datasetId;
  59901. this.addMap(floorplan);
  59902. floorplan.updateProjection();
  59903. floorplan.updateObjectGroup();
  59904. let visible = false;
  59905. if(datasetId in Potree.settings.floorplanEnables){
  59906. visible = Potree.settings.floorplanEnables[datasetId];
  59907. }else {
  59908. visible = Potree.settings.floorplanEnable;
  59909. }
  59910. if(visible){
  59911. this.needUpdate = true;
  59912. }else {
  59913. floorplan.setEnable(false);
  59914. }
  59915. this.dispatchEvent({type:'floorplanLoaded', floorplan});
  59916. }
  59917. return floorplan
  59918. }
  59919. getFloorplan(datasetId){
  59920. return this.maps.find(e=>e.name == 'floorplan'+"_"+ datasetId )
  59921. }
  59922. addMap(t){
  59923. this.maps.push(t);
  59924. //this.view.invalidateScene()
  59925. this.needUpdate = true;
  59926. this.viewer.mapChanged = true;
  59927. }
  59928. removeMap(t){
  59929. var e = this.maps.indexOf(t);
  59930. if(e >= 0){
  59931. t.removeFromSceneGroup(this.sceneGroup);
  59932. this.maps.splice(e, 1);
  59933. }
  59934. /* this.view.invalidateScene() */
  59935. this.needUpdate = true;
  59936. this.viewer.mapChanged = true;
  59937. }
  59938. changeViewer(viewer_){//add
  59939. this.viewer = viewer_;
  59940. }
  59941. initProjection(){
  59942. this.maps.forEach(map=>{
  59943. map.updateProjection();
  59944. map.updateObjectGroup();
  59945. });
  59946. }
  59947. visibilityChanged(){
  59948. if (!this.visible)
  59949. for (var t = 0, e = this.maps; t < e.length; t++){
  59950. e[t].removeFromSceneGroup(this.sceneGroup);
  59951. }
  59952. }
  59953. update(){
  59954. this.needUpdate = false;
  59955. if(this.disabled || !this.maps.find(e=>!e.disabled) || !this.maps.find(e=>e.objectGroup.visible) )return //add
  59956. this.viewer.mapChanged = true;
  59957. var e, n, i, r, o;
  59958. this.updateTimer = void 0,
  59959. e = this.viewport.camera,
  59960. n = e.projectionMatrix.clone();
  59961. let expandRatio = 1.3;
  59962. n.elements[0] /= expandRatio;
  59963. n.elements[5] /= expandRatio; // 为了缓存吗,使边界处也提前加载,扩大显示区域
  59964. this.frustumMatrix.multiplyMatrices(n, e.matrixWorldInverse),
  59965. this.frustum.setFromProjectionMatrix(this.frustumMatrix),
  59966. this.frustum.planes[4].setComponents(0, 0, 0, 0),
  59967. this.frustum.planes[5].setComponents(0, 0, 0, 0),
  59968. i = !0;
  59969. for (r = 0; r < this.maps.length; r++){
  59970. var map = this.maps[r];
  59971. i = map.update(this.frustum, this.sceneGroup) && i;
  59972. }
  59973. return [2, i]
  59974. }
  59975. updateProjection(){
  59976. for (var t = 0, e = this.maps; t < e.length; t++){
  59977. var n = e[t];
  59978. n.clearProjection(),
  59979. n.updateObjectGroup();
  59980. }
  59981. }
  59982. }
  59983. class TiledMapBase extends EventDispatcher{
  59984. constructor( name, mapLayer, tileColor, projection){
  59985. super();
  59986. this.name = name;
  59987. this.mapLayer = mapLayer,
  59988. this.tileColor = tileColor,
  59989. this.bias = 0;
  59990. this.zIndex = -1;
  59991. this.objectGroup = new Object3D;
  59992. this.objectGroup.name = name;
  59993. this.objectGroupAdded = !1,
  59994. this.baseTile = new MapTile(this, this.objectGroup, this.tileColor, null, '0'),
  59995. this.isTileVisibleBox = new Box3,
  59996. this.isTileVisibleVec = new Vector3;
  59997. this.projection = projection;
  59998. this._zoomLevel = 0;//1-20
  59999. this.objectGroup.addEventListener('isVisible',()=>{
  60000. this.mapLayer.viewer.mapChanged = true;
  60001. });
  60002. this.computeCount = 0;
  60003. this.maxLoading = 3;
  60004. this.loadFailCount = 0;
  60005. this.loadingInProgress = 0;
  60006. }
  60007. get zoomLevel(){
  60008. return this._zoomLevel
  60009. }
  60010. set zoomLevel(zoomLevel){
  60011. if(this._zoomLevel != zoomLevel){
  60012. this._zoomLevel = zoomLevel;
  60013. this.dispatchEvent({type:'zoomLevelChange',zoomLevel});
  60014. //if(this.name == 'map')console.log(zoomLevel,viewer.mapViewer.camera.zoom)
  60015. }
  60016. }
  60017. updateObjectGroup(){
  60018. this.position && this.objectGroup.position.copy(this.position),
  60019. this.quaternion && this.objectGroup.quaternion.copy(this.quaternion),
  60020. this.objectGroup.updateMatrixWorld(!0);
  60021. }
  60022. updateProjection(){
  60023. if(!this.transformMapToLocal){
  60024. if(proj4.defs("LOCAL_MAP")){
  60025. /* if(this.projection == "EPSG:4550"){
  60026. this.transformMapToLocal = {
  60027. forward:(e)=>{
  60028. var a = viewer.transform.lonlatTo4550.inverse(e)
  60029. return viewer.transform.lonlatToLocal.forward(a)
  60030. },
  60031. }
  60032. }else{ */
  60033. this.transformMapToLocal = proj4(this.projection, "LOCAL_MAP");
  60034. //}
  60035. }
  60036. }
  60037. }
  60038. clearProjection(){
  60039. this.transformMapToLocal = void 0;
  60040. this.projection !== 'LOCAL_MAP' && this.baseTile.remove();
  60041. }
  60042. setEnable(enable){//add
  60043. if(!this.disabled == enable)return
  60044. if(enable){
  60045. //console.log('setEnable',true)
  60046. }
  60047. this.disabled = !enable;
  60048. Potree.Utils.updateVisible(this.objectGroup, 'setEnable', enable);
  60049. if(!enable){
  60050. this.baseTile.remove();
  60051. }else {
  60052. this.mapLayer.needUpdate = true;
  60053. }
  60054. }
  60055. update(e, n){
  60056. this.computeCount = 0;
  60057. var unavailable = (this.disabled || !this.objectGroup.visible);//地图即使不显示也要获得zoomlevel
  60058. if(this.name != 'map' && unavailable)return
  60059. this.updateProjection();
  60060. if(!this.transformMapToLocal)return
  60061. if (!this.isTileVisible(new Vector3(0,0,0), this.mapSizeM, e))
  60062. return this.removeFromSceneGroup(n), !0;
  60063. let viewport = this.mapLayer.viewport;
  60064. var i = new Vector3(-.5 * this.mapSizeM,0,0);
  60065. i.applyMatrix4(this.objectGroup.matrixWorld),
  60066. i.project(viewport.camera);
  60067. var o = new Vector3(.5 * this.mapSizeM,0,0);
  60068. o.applyMatrix4(this.objectGroup.matrixWorld),
  60069. o.project(viewport.camera);
  60070. var a = viewport.resolution.x
  60071. , s = viewport.resolution.y;
  60072. if (a <= 0 || s <= 0 || isNaN(i.x) || isNaN(o.x)) return !1;
  60073. i.sub(o),
  60074. i.x *= a / 2,
  60075. i.y *= s / 2;
  60076. let scale;
  60077. if(this.name == 'map'){
  60078. //add 高纬度的因倾斜而造成tile较小,所以放大些,否则会造成显示的tile过多而卡
  60079. let lonlat = viewer.transform.lonlatToLocal.inverse(viewport.camera.position.clone());
  60080. let cos = Math.cos(MathUtils.degToRad(lonlat.y)); //越小就在纬度上越高,tile表现越小
  60081. //为什么lonlat.y会超出90?
  60082. /* if(lonlat.y>90){
  60083. console.log('lonlat.y>90',lonlat.y)
  60084. } */
  60085. cos = MathUtils.clamp(cos, 0,1);
  60086. let lonShift = Math.abs(viewer.mapViewer.camera.position.x / this.mapSizeM * 16 ); //越大就在经度离中心越远,tile表现越大 。
  60087. lonShift = MathUtils.clamp(lonShift, 0, Math.PI);
  60088. lonShift = (1 - Math.sin( 1/2 * lonShift + Math.PI/2 )) * Math.PI; // 0-Math.PI sin增速向上
  60089. scale = 0.5 * cos * (1+lonShift) + 0.5 * Math.pow(cos, lonShift);
  60090. }else {
  60091. scale = 1;
  60092. }
  60093. var c = this.tileSizePx / i.length() / scale //多除以一个scale缩放因子,scale越大level越小
  60094. , level = Math.ceil(-Math.log(c) / Math.log(2) - this.bias);
  60095. level = Math.max(level, 0);
  60096. level = Math.min(level, void 0 === this.maxDepth ? 1 / 0 : this.maxDepth);
  60097. this.zoomLevel = level;//add
  60098. /* if(isNaN(this.zoomLevel )){
  60099. console.log(level, cos , scale , lonlat )
  60100. } */
  60101. if(!unavailable){
  60102. this.addToSceneGroup(n);
  60103. return this.baseTile.update(this, e, level, this.mapSizeM, 0, 0, "")
  60104. }
  60105. }
  60106. isTileVisible(e, n, i){
  60107. if (n > HALF_WORLD_SIZE) return !0;
  60108. var r = .5 * n;
  60109. //简单版:
  60110. this.transformMapToLocal.forward(e); //e转化为local
  60111. this.isTileVisibleBox.makeEmpty();
  60112. this.isTileVisibleVec.set(e.x - r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  60113. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  60114. this.isTileVisibleVec.set(e.x - r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  60115. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  60116. this.isTileVisibleVec.set(e.x + r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  60117. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  60118. this.isTileVisibleVec.set(e.x + r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  60119. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  60120. //仿造createMesh写的准确版,但会因为大的tile非矩形,而视口是矩形,若视口刚好在tile的曲线边缘外却识别为可见,就会创建冗余tile。 但上面那个简单版在zoomlevel低的时候地球边缘容易有识别不到的tile,造成黑色三角形。
  60121. //容易出现奇怪的mesh
  60122. /* this.isTileVisibleBox.makeEmpty()
  60123. this.isTileVisibleVec.set(e.x - r, e.y - r, e.z)
  60124. this.transformMapToLocal.forward(this.isTileVisibleVec)
  60125. this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld)
  60126. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec)
  60127. this.isTileVisibleVec.set(e.x - r, e.y + r, e.z)
  60128. this.transformMapToLocal.forward(this.isTileVisibleVec)
  60129. this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld)
  60130. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec)
  60131. this.isTileVisibleVec.set(e.x + r, e.y - r, e.z)
  60132. this.transformMapToLocal.forward(this.isTileVisibleVec)
  60133. this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld)
  60134. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec)
  60135. this.isTileVisibleVec.set(e.x + r, e.y + r, e.z)
  60136. this.transformMapToLocal.forward(this.isTileVisibleVec)
  60137. this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld)
  60138. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec) */
  60139. return i.intersectsBox(this.isTileVisibleBox)
  60140. }
  60141. addToSceneGroup(t){
  60142. this.objectGroupAdded || (t.add(this.objectGroup),
  60143. this.objectGroupAdded = !0);
  60144. }
  60145. removeFromSceneGroup(t){
  60146. this.baseTile.remove(),
  60147. this.objectGroupAdded && (t.remove(this.objectGroup),
  60148. this.objectGroupAdded = !1);
  60149. }
  60150. }
  60151. const loadDone = (tile, success)=>{
  60152. tile.map.mapLayer.loadingInProgress--;
  60153. tile.map.loadingInProgress--;
  60154. //console.log('loaddone', tile.name, 'loadingInProgress',tile.map.mapLayer.loadingInProgress, Date.now())
  60155. tile.loading = false;
  60156. let next = tile.map.mapLayer.waitQueue[0];
  60157. if(next){
  60158. addLoadTile(next);
  60159. }else {
  60160. if(tile.map.mapLayer.loadingInProgress == 0){//注意这时候不一定就加载完了,300ms后可能还会有新的tile加载
  60161. //console.log('loadDone All ?', Date.now())
  60162. tile.map.mapLayer.dispatchEvent('loadDone');
  60163. }
  60164. }
  60165. tile.mesh && (tile.mesh.material.needsUpdate = true);
  60166. };
  60167. function addLoadTile(tile){
  60168. if(tile.map.loadingInProgress < tile.map.maxLoading){
  60169. if(!tile.mesh)return; //有时候会遇到这种情况, 为什么没有被cancelLoad呢?
  60170. tile.map.mapLayer.loadingInProgress++;
  60171. tile.map.loadingInProgress ++;
  60172. tile.map.mapLayer.dispatchEvent('startLoad');
  60173. //console.log('addLoad', 'loadingInProgress',tile.map.mapLayer.loadingInProgress, Date.now())
  60174. //tile.texURL && tile.texURL.includes('testdata') && console.log('addLoadTile', tile.texURL.split('map_tiles/')[1] )
  60175. tile.loading = true;
  60176. let index = tile.map.mapLayer.waitQueue.indexOf(tile);
  60177. index > -1 && tile.map.mapLayer.waitQueue.splice(index,1);
  60178. let tex = tile.mesh.material.map = texLoader$4.load(tile.texURL, (tex)=>{ //如果一直加载不了会影响其他的加载,如google地图没有vpn会使全景图一直加载不了
  60179. if(tile.mesh){//如果还要显示的话
  60180. tile.textureLoaded = true;
  60181. tile.mesh.material.opacity = 1;
  60182. tile.map.mapLayer.viewer.mapChanged = true;
  60183. tile.map.mapLayer.needUpdate = true; //表示还要继续update(以removeChildren)
  60184. if(tile.map instanceof TiledMapOpenStreetMap){
  60185. tile.map.maxLoading = browser.isMobile() ? 5 : 10;
  60186. }
  60187. }else {
  60188. //tile.texURL && tile.texURL.includes('testdata') && console.log('loadDone and dispose', tile.texURL.split('map_tiles/')[1] )
  60189. tex.dispose();
  60190. }
  60191. loadDone(tile, true);
  60192. } , void 0, (()=>{//error
  60193. tile.textureLoaded = !0;
  60194. if(tile.mesh){
  60195. tile.mesh.material.dispose();
  60196. tile.mesh.material = errorMaterial;
  60197. tile.map.mapLayer.viewer.mapChanged = true;
  60198. }
  60199. loadDone(tile, false);
  60200. tile.map.loadFailCount ++ ;
  60201. if(tile.map instanceof TiledMapOpenStreetMap && Potree.settings.mapCompany == 'google' && tile.map.loadFailCount > 3){//极有可能没有vpn为了防止影响到其他资源加载,减少加载的个数
  60202. tile.map.maxLoading = 2;
  60203. }
  60204. }));
  60205. tex.anisotropy = 0;
  60206. tex.generateMipmaps = !1;
  60207. tex.minFilter = LinearFilter;
  60208. tex.magFilter = LinearFilter;
  60209. }else {
  60210. tile.map.mapLayer.waitQueue.includes(tile) || tile.map.mapLayer.waitQueue.push(tile);
  60211. }
  60212. }
  60213. function cancelLoad(tile,log){//如果等待加载,但还没开始加载,取消加载
  60214. if(!tile.loading){
  60215. let index = tile.map.mapLayer.waitQueue.indexOf(tile);
  60216. index > -1 && tile.map.mapLayer.waitQueue.splice(index,1);
  60217. //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 */ )
  60218. }
  60219. }
  60220. class MapTile{
  60221. constructor(map, e, n, parent, name){
  60222. this.map = map;
  60223. this.name = name;
  60224. this.parent = parent;
  60225. this.objectGroup = e,
  60226. this.tileColor = n,
  60227. this.meshAdded = !1,
  60228. this.textureLoaded = !1,
  60229. this.children = [];
  60230. this.id = getSid();
  60231. }
  60232. update(e, n, i, r, o, a, s){
  60233. return !!this.doesNotContainTilesToBeDisplayed(e) || (0 === i ? this.updateTile(e, r, o, a) : this.updateSubTiles(e, n, i, r, o, a, s))
  60234. }
  60235. doesNotContainTilesToBeDisplayed(t){
  60236. return t.tilePresenceMap && t.tilePresenceMap.empty
  60237. }
  60238. updateTile(t, e, n, i){ //真正显示mesh的是这一层,最高level, i==0的
  60239. if(!this.mesh){
  60240. this.createTileObject(t, e, n, i);
  60241. }
  60242. if(!this.meshAdded){
  60243. this.objectGroup.add(this.mesh);
  60244. this.meshAdded = !0;
  60245. }
  60246. if(this.textureLoaded){//贴图加载完就不需要子集了
  60247. this.removeChildren();
  60248. }else {
  60249. this.cancelChildren(); //add 停止加载子集
  60250. }
  60251. return this.textureLoaded
  60252. }
  60253. updateSubTiles(entity, n, level, o, a, s, c){
  60254. for (var noContent = !0, u = [-.25 * o, .25 * o, -.25 * o, .25 * o], d = [.25 * o, .25 * o, -.25 * o, -.25 * o], p = 0; p < 4; ++p){
  60255. var h = c + p.toString(10);
  60256. //一级(512):0 1 2 3分别为左上、右上、左下、右下。二级(1024)就是把一级的每一块分裂,如00 01 02 03分别是0的左上、右上、左下、右下……
  60257. /* if(entity.name == 'floorplan'){
  60258. console.log(1)
  60259. } */
  60260. if (!entity.tilePresenceMap || entity.tilePresenceMap[h]){
  60261. //去掉判断,直接显示
  60262. var f = a + u[p]
  60263. , m = s + d[p];
  60264. tempVector.set(f, m, 0);
  60265. this.map.computeCount ++;
  60266. //console.log(this.map.computeCount, this.name, 'level:',level)
  60267. if (entity.isTileVisible(tempVector, .5 * o, n)){
  60268. this.children[p] || (this.children[p] = new MapTile(this.map, this.objectGroup,this.tileColor, this, this.name+p ));
  60269. noContent = noContent && this.children[p].update(entity, n, level - 1, .5 * o, f, m, h);
  60270. } else {
  60271. if (this.children[p]){
  60272. this.children[p].remove();
  60273. delete this.children[p];
  60274. }
  60275. }
  60276. }
  60277. }
  60278. return noContent && this.removeObject3D(),
  60279. noContent
  60280. }
  60281. createTileObject(t, e, n, a){
  60282. var s = this;
  60283. this.mesh = this.createMesh(t.transformMapToLocal, e, n, a),
  60284. this.textureLoaded = !1;
  60285. var c = t.mapSizeM / e
  60286. , l = Math.log(c) / Math.log(2)
  60287. , u = n / e + .5 * (c - 1)
  60288. , d = -a / e + .5 * (c - 1)
  60289. , p = t.getTileUrl(Math.round(l), Math.round(u), Math.round(d));
  60290. Potree.Utils.setObjectLayers(this.mesh, 'map' );
  60291. this.mesh.renderOrder = -(1e6 - l - 100 * (t.zIndex || 0));
  60292. this.mesh.name = this.name; //add
  60293. this.texURL = p;
  60294. /* let area = math.getArea(this.mesh.geometry.vertices.slice(0,3));
  60295. if(area >0){
  60296. this.mesh.visible = false
  60297. console.log('area>0',this.mesh.name)
  60298. } */
  60299. addLoadTile(this);
  60300. }
  60301. createMesh(t, e, n, o){
  60302. var a = new Geometry;
  60303. return tempVector.set(n - e / 2, o - e / 2, 0),
  60304. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  60305. tempVector.set(n + e / 2, o - e / 2, 0),
  60306. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  60307. tempVector.set(n + e / 2, o + e / 2, 0),
  60308. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  60309. tempVector.set(n - e / 2, o + e / 2, 0),
  60310. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  60311. a.faces.push(face1),
  60312. a.faces.push(face2),
  60313. a.faceVertexUvs[0].push(face1UV),
  60314. a.faceVertexUvs[0].push(face2UV),
  60315. new Mesh(a,this.createMaterial())
  60316. }
  60317. createMaterial(){
  60318. var t = new MeshBasicMaterial({
  60319. transparent: !0,
  60320. depthWrite: !1,
  60321. depthTest: !0,
  60322. opacity: 0,
  60323. side: DoubleSide,
  60324. });
  60325. if(Potree.settings.isTest) {
  60326. var colorHue = Math.random();
  60327. t.color = new Color().setHSL(colorHue, 0.6, 0.92);
  60328. }else {
  60329. t.color = this.tileColor ? this.tileColor : new Color(16777215);
  60330. }
  60331. return t
  60332. }
  60333. traverse(f){//add
  60334. return Mesh.prototype.traverse.call(this,f)
  60335. }
  60336. remove(){
  60337. this.removeObject3D(),
  60338. this.removeChildren();
  60339. }
  60340. removeObject3D(){
  60341. let hasMesh = !!this.mesh;
  60342. if (this.mesh){
  60343. this.objectGroup.remove(this.mesh);
  60344. if (this.textureLoaded){
  60345. var t = this.mesh.material.map;
  60346. t && t.dispose();
  60347. }else {
  60348. cancelLoad(this);
  60349. }
  60350. this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh),
  60351. this.mesh.geometry.dispose();
  60352. this.mesh = void 0;
  60353. }
  60354. this.meshAdded = !1,
  60355. this.textureLoaded = !1;
  60356. //this.texURL && this.texURL.includes('testdata') && console.log('removeObject3D', this.id, 'hasMesh',hasMesh, this.texURL.split('map_tiles/')[1] )
  60357. }
  60358. removeChildren(){
  60359. for (var t = 0, e = this.children; t < e.length; t++){
  60360. var n = e[t];
  60361. n && (n.removeObject3D(),
  60362. n.removeChildren());
  60363. }
  60364. this.children.length = 0;
  60365. }
  60366. cancelChildren(){//子集全部停止加载
  60367. for (var t = 0, e = this.children; t < e.length; t++){
  60368. var n = e[t];
  60369. n && (cancelLoad(n, '提前'), n.cancelChildren());
  60370. }
  60371. }
  60372. }
  60373. 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");
  60374. //这里地图世界的中心是不是lon:0,lat:0
  60375. class TiledMapOpenStreetMap extends TiledMapBase{
  60376. constructor(mapLayer, tileColor){
  60377. //Potree.settings.mapCompany = 'google'
  60378. super('map', mapLayer, tileColor/* , projection */ ); //EPSG projection
  60379. //this.baseUrl = "https://wprd03.is.autonavi.com/appmaptile?style=7&x=${x}&y=${y}&z=${z}",
  60380. //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
  60381. this.switchStyle();
  60382. this.tileSizePx = 256;
  60383. this.mapSizeM = 40075017; //总占据多少米(地球赤道周长) 和三维空间的不一样 - -, 空间上的是直径,地图上的是半个圆周
  60384. this.bias = 0.5;
  60385. if(Potree.settings.mapCompany == 'google'){
  60386. this.attribution = "© PopSmart, © 谷歌地图";
  60387. this.projection = "EPSG:900913"; //"EPSG:4326"//4550
  60388. }else {
  60389. this.attribution = "© PopSmart, © 高德地图";
  60390. this.projection = "EPSG:3857";
  60391. }
  60392. }
  60393. getTileUrl(t, e, n){
  60394. return this.baseUrl.replace(/\${z}/, t.toString(10)).replace(/\${x}/, e.toString(10)).replace(/\${y}/, n.toString(10))
  60395. }
  60396. switchStyle(style = 'standard'){
  60397. //if(Potree.settings.mapCompany == 'google')return
  60398. if(style == this.style)return
  60399. if(Potree.settings.mapCompany == 'google'){
  60400. if(style == 'satellite'){//卫星
  60401. 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
  60402. this.maxDepth = 22;
  60403. }else {
  60404. 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
  60405. this.maxDepth = 22;
  60406. }
  60407. /* 1)lyrs= 表示的是图层类型,即瓦片类型,具体含义如下:
  60408. m:路线图
  60409. t:地形图
  60410. p:带标签的地形图
  60411. s:卫星图
  60412. y:带标签的卫星图
  60413. h:标签层(路名、地名等)
  60414. 2)& gl=CN
  60415. 谷歌地图针对中国有两套坐标,一套做了偏移,一套没有。经测试在url加入gl=cn地图会有偏移。
  60416. Tips:如果谷歌地图和RTK测量的WGS84坐标有偏差,可以尝试在url里去掉& gl=cn。
  60417. 5)&hl=
  60418. 设置地图注记文字语言类型,缺省默认为中文。
  60419. hl=nl 中英双语
  60420. hl=zh-CN 中文
  60421. */
  60422. }else {
  60423. //baseUrl = "https://webst01.is.autonavi.com/appmaptile?lang=zh_cn&style=6&yrs=m&x=${x}&y=${y}&z=${z}" //卫星 maxDepth = 18
  60424. //搜索高德地图瓦片url
  60425. if(style == 'satellite'){//卫星
  60426. this.maxDepth = 18;
  60427. this.baseUrl = "https://webst01.is.autonavi.com/appmaptile?lang=zh_cn&style=6&yrs=m&x=${x}&y=${y}&z=${z}";
  60428. }else {
  60429. this.maxDepth = 19;
  60430. this.baseUrl = "https://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&style=7&yrs=m&x=${x}&y=${y}&z=${z}"; //
  60431. }
  60432. }
  60433. this.style = style;
  60434. this.setEnable(false);
  60435. this.setEnable(true);
  60436. viewer.dispatchEvent('content_changed');
  60437. }
  60438. }
  60439. class TiledMapFromEntity extends TiledMapBase{
  60440. constructor(mapLayer, tileColor, data){
  60441. super('floorplan', mapLayer, tileColor, "LOCAL" /* "EPSG:3857" *//* "WGS84" */); //直接就是本地坐标,没有projec
  60442. let entity = this.tiledMapEntity = this.fillFromData(data);
  60443. let time = entity.updateTime || entity.createTime;
  60444. this.tileSizePx = entity.tileSizePx,
  60445. this.mapSizeM = entity.mapSizeM,
  60446. this.maxDepth = entity.maxDepth;
  60447. this.postStamp = time ? time.replace(/[^0-9]/ig,'') : (new Date).getTime();
  60448. //this.projection = n.crsLocal,
  60449. this.zIndex = 0,
  60450. this.tilePresenceMap = this.decodeBitStream(this.tiledMapEntity.quadtree); //包含tile分裂信息,如果写错了会造成tile显示不全
  60451. this.maxLoading = 5;
  60452. this.bias = 0.5; //越大加载层级越低,越模糊
  60453. if(window.devicePixelRatio>=2 && window.innerHeight * window.innerWidth < 768*1024){ //手机还是加载高清点(反正也不需要截图等待),但平板太大了,要铺满屏幕可能慢,所以稍微模糊点?(反正可以继续放大去看)
  60454. this.bias = 0; //level更高些
  60455. }
  60456. }
  60457. fillFromData(e){
  60458. let data = {};
  60459. data.id = e.id;
  60460. data.globalLocation = Potree.Utils.VectorFactory.fromArray3(e.location);
  60461. data.orientation = Potree.Utils.QuaternionFactory.fromArray(e.orientation);
  60462. let pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id == e.datasetId);
  60463. if(pointcloud.datasetData.mapping){
  60464. data.filePath = `${Potree.settings.urls.prefix1}/${pointcloud.datasetData.mapping}${e.file_path}`;
  60465. }else {
  60466. data.filePath = `${Potree.settings.urls.prefix1}${e.file_path}`;
  60467. }
  60468. data.fileName = '$DEPTH/$X/$Y.png';
  60469. data.type = e.type,
  60470. data.mapSizeM = e.map_size_m,
  60471. data.tileSizePx = e.tile_size_px,
  60472. data.maxDepth = e.max_depth,
  60473. data.quadtree = e.quadtree,
  60474. data.floorId = e.floor_id,
  60475. data.bundleId = e.bundle_id;
  60476. //this.computeLocalCoordinates()
  60477. return data
  60478. }
  60479. computeLocalCoordinates(){
  60480. if(proj4.defs("LOCAL_MAP")){
  60481. let lonlat = this.tiledMapEntity.globalLocation;
  60482. /* if(window.AMapWith84){//需要转换
  60483. lonlat = AMapWith84.wgs84ToAMap(lonlat)
  60484. } */
  60485. lonlat = viewer.transform.lonlatToLocal.forward(lonlat);
  60486. this.tiledMapEntity.location = new Vector3().copy(lonlat);
  60487. }
  60488. }
  60489. updateProjection() {
  60490. super.updateProjection();
  60491. if(!this.position){
  60492. this.computeLocalCoordinates();
  60493. }
  60494. /* this.projection = this.TransformService.crsLocal,
  60495. t.prototype.updateProjection.call(this) */
  60496. }
  60497. get position(){
  60498. return this.tiledMapEntity.location
  60499. /* enumerable: !0,
  60500. configurable: !0 */
  60501. }
  60502. get quaternion(){
  60503. return this.tiledMapEntity.orientation
  60504. /* enumerable: !0,
  60505. configurable: !0 */
  60506. }
  60507. getTileUrl(t, e, n) {
  60508. 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));
  60509. return i += "?t=" + this.postStamp
  60510. //this.RestService.addAuthorizationQueryParameter(i) //????
  60511. }
  60512. decodeBitStream(t) {
  60513. if (!t)
  60514. return {
  60515. empty: !0
  60516. };
  60517. for (var e = {}, n = [e], i = 0; i < t.length; i++) {
  60518. var r = n.shift()
  60519. , o = parseInt(t.substr(i, 1), 16);
  60520. if (1 & o) {
  60521. var a = {};
  60522. r[0] = a,
  60523. n.push(a);
  60524. }
  60525. 2 & o && (a = {},
  60526. r[1] = a,
  60527. n.push(a)),
  60528. 4 & o && (a = {},
  60529. r[2] = a,
  60530. n.push(a)),
  60531. 8 & o && (a = {},
  60532. r[3] = a,
  60533. n.push(a));
  60534. }
  60535. var s = {
  60536. empty: !0
  60537. };
  60538. return this.computeHashes(s, e, ""),
  60539. s
  60540. }
  60541. computeHashes(t, e, n) {
  60542. for (var i = 0; i < 4; i++)
  60543. e[i] && (t[n + i.toString(10)] = !0,
  60544. t.empty = !1,
  60545. this.computeHashes(t, e[i], n + i.toString(10)));
  60546. }
  60547. }
  60548. /*
  60549. note:
  60550. 目前缩小了能看出形态是一个地球。相机在高空朝下观测,地球平放着。
  60551. 所以越靠近赤道和地球朝上的那面所在的中央经度(也就是local 0,0,0所对应的初始经度),tile越接近正方形。
  60552. 所以在两极地区要怎么显示?
  60553. 注册地理坐标时需要滚动地球吗?(修改初始经度、重定义NAVVIS:TMERC, 就需要更新所有三维世界中的物体位置)
  60554. 切换中心点:
  60555. var locationLonLat = viewer.transform.lonlatToLocal.inverse(viewer.mapViewer.camera.position.clone())
  60556. proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat.x.toPrecision(15) + " +lat_0=" + locationLonLat.y.toPrecision(15));
  60557. viewer.mapViewer.mapLayer.maps[0].transformMapToLocal = null
  60558. 地理注册部分地图上的1和2标记有两层意思。当地图全屏展示时,标记的是当前右侧经纬度的位置;当地图为小窗时,标记的是对应场景里三维位置。(所以感觉最好换一个ui?)且在2023.2.1之前才改好,之前都是后者。
  60559. 为什么边缘总是有奇怪的mesh,是因为有顶点到背面了吗
  60560. https://lbs.amap.com/tools/picker 高德坐标拾取器,但和这里展示的不一样, 要用AMapWith84.aMapToWgs84({x: ,y: })转成84。 (qq or 手机登录) 所以potree本地和有AMapWith84函数的laser地图展现不一样
  60561. https://www.google.com/maps/@77.7730021,-34.4952712,4z google取点
  60562. 打印所有mapTile的名字,字符串最长的代表有显示的mesh。
  60563. viewer.mapViewer.mapLayer.maps[0].baseTile.traverse(function(e){console.log(e.name)})
  60564. 能查看有几个显示的mesh
  60565. viewer.mapViewer.mapLayer.maps[0].objectGroup.children
  60566. 图片地址中 tiles/4/3/9.png 第一个数字越高代表level越高,放得越大 . (tile.name.length也能反映出
  60567. viewer.mapViewer.mapLayer.maps[1].objectGroup.children.map(e=>e.name.length)
  60568. 目前看的几个场景floorplan原图是1米=33.03个像素 图宽度= 512*2^(max_depth-1) , map_size_m 代表整个地图是多少米
  60569. */
  60570. /**
  60571. * @author mschuetz / http://mschuetz.at
  60572. *
  60573. * adapted from THREE.OrbitControls by
  60574. *
  60575. * @author qiao / https://github.com/qiao
  60576. * @author mrdoob / http://mrdoob.com
  60577. * @author alteredq / http://alteredqualia.com/
  60578. * @author WestLangley / http://github.com/WestLangley
  60579. * @author erich666 / http://erichaines.com
  60580. *
  60581. *
  60582. *
  60583. */
  60584. let Buttons = Potree.defines.Buttons;
  60585. class FirstPersonControls extends EventDispatcher {
  60586. constructor (viewer, viewport) {
  60587. super();
  60588. this.viewer = viewer;
  60589. this.renderer = viewer.renderer;
  60590. this.scene = viewer.scene;
  60591. this.rotationSpeed = 200;
  60592. this.moveSpeed = 10;
  60593. this.setCurrentViewport({hoverViewport:viewport, force:true}); //this.currentViewport = viewport
  60594. this.keys = {
  60595. FORWARD: ['W'.charCodeAt(0), 38],
  60596. BACKWARD: ['S'.charCodeAt(0), 40],
  60597. LEFT: ['A'.charCodeAt(0), 37],
  60598. RIGHT: ['D'.charCodeAt(0), 39],
  60599. UP: ['Q'.charCodeAt(0)],
  60600. DOWN: ['E'.charCodeAt(0)],
  60601. //SHIFT : [16],
  60602. ALT : [18],
  60603. SPACE:[32],
  60604. Rotate_LEFT : ['L'.charCodeAt(0)],
  60605. Rotate_RIGHT : ['J'.charCodeAt(0)],
  60606. Rotate_UP : ['K'.charCodeAt(0)],
  60607. Rotate_DOWN : ['I'.charCodeAt(0)],
  60608. };
  60609. this.fadeFactor = 20;
  60610. this.yawDelta = 0;
  60611. this.pitchDelta = 0;
  60612. this.translationDelta = new Vector3(0, 0, 0);
  60613. this.translationWorldDelta = new Vector3(0, 0, 0);
  60614. this.tweens = [];
  60615. this.dollyStart = new Vector2;
  60616. this.dollyEnd = new Vector2;
  60617. //this.enableChangePos = true
  60618. this.viewer.addEventListener('camera_changed',(e)=>{
  60619. if(this.viewer.name == 'mapViewer' || e.changeInfo && e.changeInfo.positionChanged && !viewer.mainViewport.view.isFlying() ){
  60620. this.setFPCMoveSpeed(e.viewport);
  60621. }
  60622. });
  60623. let drag = (e) => {
  60624. if(!this.enabled)return
  60625. let viewport = e.dragViewport;
  60626. if(!viewport)return
  60627. let camera = viewport.camera;
  60628. let mode;
  60629. if(e.isTouch){
  60630. if(e.touches.length == 1){
  60631. mode = (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan';
  60632. }else if(e.touches.length == 2){
  60633. mode = Potree.settings.displayMode == 'showPanos' ? 'scale' : 'pan-scale';
  60634. }else {
  60635. mode = (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'pan' : 'scale';
  60636. }
  60637. }else {
  60638. //mode = e.buttons === Buttons.LEFT && (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan'
  60639. mode = e.buttons === Buttons.LEFT && camera.type != 'OrthographicCamera' ? 'rotate' : 'pan';
  60640. }
  60641. //console.log('mode ', mode )
  60642. let moveSpeed = this.currentViewport.getMoveSpeed();
  60643. if (e.drag.startHandled === undefined) {///???????
  60644. e.drag.startHandled = true;
  60645. this.dispatchEvent({type: 'start'});
  60646. }
  60647. if (mode.includes('rotate')) {//旋转
  60648. //来自panoramaControl updateRotation
  60649. if(!this.pointerDragStart){
  60650. return this.pointerDragStart = e.pointer.clone()
  60651. }
  60652. let view = this.scene.view;
  60653. if(this.rotateStartInfo.rotAroundPoint){//定点旋转: 以当前intersect的点为target旋转,不改点在屏幕中的位置
  60654. let distance = camera.position.distanceTo(this.rotateStartInfo.rotCenter/* this.intersectStart.location */); //不按下ctrl的话
  60655. let posDir = new Vector3().subVectors(this.rotateStartInfo.rotCenter, view.position);
  60656. if(posDir.dot(view.direction) < 0 )distance *= -1; //在背面
  60657. //按照orbitControl的方式旋转:
  60658. let rotationSpeed = 2;
  60659. this.yawDelta -= e.drag.pointerDelta.x * rotationSpeed;
  60660. this.pitchDelta += e.drag.pointerDelta.y * rotationSpeed;
  60661. /* //旋转方向和偏移量尽量和在漫游点处旋转方式的一样
  60662. this.yawDelta += e.drag.pointerDelta.x / 500 * viewport.resolution.x
  60663. this.pitchDelta -= e.drag.pointerDelta.y / 500 * viewport.resolution.y */
  60664. //先更新一下相机:
  60665. this.update();
  60666. view.applyToCamera(camera);
  60667. //然后得到新的相机角度下,原先点在屏幕中的位置所对应的3d点现在的坐标。只需要平移一下新旧坐标差值即可。//感觉貌似也可以用project和unproject后的差值的方式,还不用判断z背面
  60668. let newPointerDir = viewer.inputHandler.getMouseDirection(this.rotateStartInfo.rotCenter2d).direction.clone().multiplyScalar(distance);
  60669. let pivot = new Vector3().addVectors(camera.position, newPointerDir); //新的3d点
  60670. let moveVec = new Vector3().subVectors(pivot, this.rotateStartInfo.rotCenter);
  60671. this.translationWorldDelta.copy(moveVec.negate());
  60672. //立即更新下,防止因update和此drag频率不同而打滑。
  60673. this.update();
  60674. view.applyToCamera(camera);
  60675. }else {
  60676. let _matrixWorld = camera.matrixWorld;
  60677. camera.matrixWorld = new Matrix4;//unproject 前先把相机置于原点
  60678. var e1 = new Vector3(this.pointerDragStart.x,this.pointerDragStart.y,-1).unproject(camera)
  60679. , t = new Vector3(e.pointer.x,e.pointer.y,-1).unproject(camera)
  60680. , i = Math.sqrt(e1.x * e1.x + e1.z * e1.z)
  60681. , n = Math.sqrt(t.x * t.x + t.z * t.z)
  60682. , o = Math.atan2(e1.y, i)
  60683. , a = Math.atan2(t.y, n);
  60684. this.pitchDelta += o - a; //上下旋转
  60685. e1.y = 0,
  60686. t.y = 0;
  60687. var s = Math.acos(e1.dot(t) / e1.length() / t.length());
  60688. if(!isNaN(s)){
  60689. var yawDelta = s; //左右旋转
  60690. this.pointerDragStart.x > e.pointer.x && (yawDelta *= -1);
  60691. this.yawDelta += yawDelta;
  60692. }
  60693. //console.log('rotate:', this.pitchDelta, e.pointer.toArray(), this.pointerDragStart.toArray())
  60694. this.pointerDragStart.copy(e.pointer);
  60695. camera.matrixWorld = _matrixWorld ;
  60696. }
  60697. }
  60698. if (mode.includes('pan')) {//平移
  60699. if(!this.canMovePos(viewport)){
  60700. return
  60701. }
  60702. if(camera.type == "OrthographicCamera"){
  60703. //console.log(e.drag.pointerDelta, e.pointer, e.drag.end)
  60704. let moveVec = Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, camera );//最近一次移动向量
  60705. let pointclouds;
  60706. let Alignment = window.viewer.modules.Alignment;
  60707. let MergeEditor = window.viewer.modules.MergeEditor;
  60708. let handleState = Alignment.handleState;
  60709. //右键平移视图、左键操作点云
  60710. let a = e.buttons === Buttons.LEFT && viewport.alignment && handleState && viewport.alignment[handleState];
  60711. if(Potree.settings.editType == 'pano'){
  60712. let PanoEditor = window.viewer.modules.PanoEditor;
  60713. if(a && PanoEditor.selectedPano){
  60714. if(/* !PanoEditor.selectedGroup || */!PanoEditor.checkIfAllLinked({group:PanoEditor.selectedGroup}) ){
  60715. if(handleState == 'translate' && ( e.drag.intersectStart.pointclouds && Common$1.getMixedSet(PanoEditor.selectedClouds, e.drag.intersectStart.pointclouds).length || PanoEditor.selectedPano.hovered)//平移时 拖拽到点云上 或 circle。(其中点云只需要intersect的点云中包含选择的点云中之一即可)
  60716. || handleState == 'rotate' ) //旋转模式不需要intersect
  60717. {
  60718. pointclouds = PanoEditor.selectedClouds;
  60719. }
  60720. }else {
  60721. PanoEditor.dispatchEvent('needToDisConnect');
  60722. console.warn('选中的漫游点连通了整个数据集,不允许移动');
  60723. }
  60724. }
  60725. if(!pointclouds && e.buttons === Buttons.LEFT && viewport.rotateSide){//侧视图 (有时候会卡顿,是mousemove执行延迟了,一般发生在突然加载很多点云时)
  60726. //console.log('rotateSide', -e.drag.pointerDelta.x )
  60727. return PanoEditor.rotateSideCamera(-e.drag.pointerDelta.x)
  60728. }
  60729. }else if(Potree.settings.editType == 'merge'){
  60730. if(e.buttons === Buttons.LEFT && viewport.rotateSide){
  60731. return MergeEditor.rotateSideCamera(-e.drag.pointerDelta.x)
  60732. }
  60733. }else {
  60734. /* if(Alignment.selectedClouds && Alignment.selectedClouds.length){//多个点云
  60735. pointclouds = a && e.drag.intersectStart.pointclouds && Common.getMixedSet(Alignment.selectedClouds, e.drag.intersectStart.pointclouds).length && Alignment.selectedClouds
  60736. }else{ */
  60737. //pointclouds = a && e.drag.intersectStart.pointcloud && [e.drag.intersectStart.pointcloud]
  60738. //}
  60739. if(a && e.drag.intersectStart.pointcloud){
  60740. pointclouds = [e.drag.intersectStart.pointcloud];
  60741. if(e.drag.intersectStart.pointcloud.dataset_id == Potree.settings.originDatasetId){
  60742. let p = e.drag.intersectStart.pointclouds.find(p=>p.dataset_id != Potree.settings.originDatasetId);
  60743. if(p) pointclouds = [p];
  60744. }
  60745. }
  60746. }
  60747. if(pointclouds){
  60748. if(handleState == 'translate' && viewport.alignment.translateVec){//只能沿某个方向移动
  60749. moveVec.projectOnVector(viewport.alignment.translateVec);
  60750. }
  60751. this.dispatchEvent({
  60752. type : "transformPointcloud",
  60753. intersect: e.intersect.orthoIntersect,
  60754. intersectStart: e.drag.intersectStart.orthoIntersect,
  60755. moveVec,
  60756. pointclouds,
  60757. camera
  60758. });
  60759. }else {
  60760. this.translationWorldDelta.add(moveVec.negate());
  60761. }
  60762. }else { //perspectiveCamera:
  60763. if(e.drag.intersectStart){//如果拖拽着点云
  60764. let ifInit = e.drag.z == void 0;
  60765. let pointerStartPos2d = e.drag.intersectStart.location.clone().project(camera);//识别到的点云点的位置
  60766. e.drag.z = pointerStartPos2d.z; //记录z,保持拖拽物体到屏幕距离不变,所以z深度不变(如果拖拽过程中没有缩放,这个z其实不变)
  60767. if(ifInit){//拖拽开始
  60768. e.drag.projectionMatrixInverse = camera.projectionMatrixInverse.clone();
  60769. //防止吸附到最近点上(因为鼠标所在位置并非识别到的点云点的位置,需要得到鼠标所在位置的3d坐标。)
  60770. let pointerStartPos2dReal = new Vector3(this.pointerDragStart.x,this.pointerDragStart.y, e.drag.z);
  60771. e.drag.translateStartPos = pointerStartPos2dReal.clone().unproject(camera);
  60772. //console.log('开始拖拽', e.pointer.clone())
  60773. }
  60774. //拖拽的过程中将projectionMatrixInverse替换成开始拖拽时的,因为near、far一直在变,会导致unproject计算出的3d坐标改变很大而闪烁。
  60775. var _projectionMatrixInverse = camera.projectionMatrixInverse;
  60776. camera.projectionMatrixInverse = e.drag.projectionMatrixInverse;
  60777. let newPos2d = new Vector3(e.pointer.x,e.pointer.y, e.drag.z );
  60778. let newPos3d = newPos2d.clone().unproject(camera);
  60779. let moveVec = newPos3d.clone().sub( e.drag.translateStartPos /* e.drag.intersectStart.location */ );//移动相机,保持鼠标下的位置永远不变,所以用鼠标下的新位置减去鼠标下的原始位置
  60780. camera.projectionMatrixInverse = _projectionMatrixInverse;
  60781. this.translationWorldDelta.copy(moveVec.negate()); //这里没法用add,原因未知,打开console时会跳动
  60782. //console.log('pan 1', this.translationWorldDelta.clone())
  60783. //四指松开剩三指时会偏移一下,暂不知道哪里的问题,或许跟开头防止点云吸附有关?
  60784. }else { //如果鼠标没有找到和点云的交点,就假设移动整个模型(也可以去扩大范围寻找最近点云)
  60785. /* let center = viewer.scene.pointclouds[0].position;
  60786. let radius = camera.position.distanceTo(center);
  60787. let ratio = radius * Math.tan(THREE.Math.degToRad(camera.fov)/2) / 1000 */
  60788. /* let speed = this.currentViewport.getMoveSpeed()
  60789. if(FirstPersonControls.boundPlane){
  60790. speed = FirstPersonControls.boundPlane.distanceToPoint(this.currentViewport.position)
  60791. speed = Math.max(1 , speed)
  60792. } */
  60793. let lastIntersect = this.target || viewport.lastIntersect && (viewport.lastIntersect.location || viewport.lastIntersect);//该viewport的最近一次鼠标和点云的交点
  60794. if(!lastIntersect || !(lastIntersect instanceof Vector3))lastIntersect = viewer.bound.center;
  60795. let speed = camera.position.distanceTo(lastIntersect);
  60796. let fov = cameraLight.getHFOVForCamera(camera, true);
  60797. let ratio = speed * Math.tan(fov/2);
  60798. this.translationDelta.x -= e.drag.pointerDelta.x * ratio;
  60799. this.translationDelta.z -= e.drag.pointerDelta.y * ratio;
  60800. //console.log('pan2', e.drag.pointerDelta)
  60801. }
  60802. }
  60803. this.useAttenuation = false;
  60804. }
  60805. if(mode.includes('scale')){//触屏缩放
  60806. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  60807. //if(!this.dollyStart)return
  60808. var scale = this.dollyEnd.length() / this.dollyStart.length();
  60809. let pointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  60810. dolly({
  60811. pointer,
  60812. scale, camera, drag:e.drag
  60813. });
  60814. this.dollyStart.copy(this.dollyEnd);
  60815. }
  60816. //最好按ctrl可以变为dollhouse的那种旋转
  60817. };
  60818. let drop = e => {
  60819. if(!this.enabled)return
  60820. this.dispatchEvent({type: 'end'});
  60821. };
  60822. let dolly = (e={})=>{
  60823. if(Potree.settings.displayMode == 'showPanos' && this.currentViewport == viewer.mainViewport/* this.currentViewport.unableChangePos */){//全景时
  60824. this.dispatchEvent({type:'dollyStopCauseUnable',delta:e.delta, scale:e.scale});
  60825. return
  60826. }
  60827. let camera = e.camera;
  60828. if(camera.type == "OrthographicCamera"){
  60829. let ratio;
  60830. if(e.delta != void 0){//滚轮缩放
  60831. if(e.delta == 0){//mac
  60832. return
  60833. }else if (e.delta < 0) {
  60834. ratio = 0.9;
  60835. } else if (e.delta > 0) {
  60836. ratio = 1.12; //增加的需要比减少的多一些,否则缩放相同次数下,r0 * ([1+s)(1-s)]^n = r0 * (1-s^2)^n < r0
  60837. }
  60838. }else {
  60839. ratio = e.scale; //触屏缩放
  60840. }
  60841. let zoom = camera.zoom * ratio;
  60842. let limit = camera.zoomLimit;
  60843. if(limit) zoom = MathUtils.clamp(zoom, limit.min,limit.max );
  60844. let pointerPos = new Vector3(e.pointer.x, e.pointer.y,0.5);
  60845. let oldPos = pointerPos.clone().unproject(camera);
  60846. if(camera.zoom != zoom){
  60847. camera.zoom = zoom;
  60848. camera.updateProjectionMatrix();
  60849. }
  60850. let newPos = pointerPos.clone().unproject(camera);
  60851. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  60852. let moveVec = new Vector3().subVectors(newPos,oldPos);
  60853. this.translationWorldDelta.add(moveVec.negate());
  60854. this.useAttenuation = false;
  60855. }else {
  60856. let speed = this.currentViewport.getMoveSpeed() * 7, direction;
  60857. if(e.delta != void 0){//滚轮缩放
  60858. if(e.delta == 0)return //mac
  60859. /*if(this.target && !e.intersect){//如果没有intersect点云且有target的话,就朝target的方向. 但无限靠近时有问题,且到背面时前进却是后退
  60860. direction = new THREE.Vector3().subVectors(this.target, camera.position).normalize()
  60861. }else{ */
  60862. direction = this.viewer.inputHandler.getMouseDirection().direction; //定点缩放
  60863. if(e.intersect && e.intersect.location){//和intersect的墙越接近,速度越慢,便于focus细节
  60864. let dis = camera.position.distanceTo(e.intersect.location);
  60865. speed = MathUtils.clamp(dis * 0.1, 0.3, speed);
  60866. }
  60867. if (e.delta < 0) {
  60868. speed *= -1;
  60869. }
  60870. this.useAttenuation = true;
  60871. }else {//触屏缩放
  60872. direction = this.viewer.inputHandler.getMouseDirection(e.pointer).direction; //定点缩放
  60873. if(e.drag.intersectStart){//和intersect的墙越接近,速度越慢,便于focus细节
  60874. let dis = camera.position.distanceTo(e.drag.intersectStart.location);
  60875. let r = 1-1/e.scale;
  60876. let closeMin = 0.1, standardMin = 0.001, disBound1 = 2, disBound2 = 5;
  60877. if(math.closeTo(e.scale,1,0.03)){//如果偏差小于0.01,就不限制最小值,因为平移容易正负抖动,近距离有最小值的话抖动明显
  60878. closeMin = 0; //所以若缩放不明显(双指滑动慢),就不设置最低值。(这时候穿越障碍物会比较困难。)
  60879. }
  60880. //console.log('closeMin',closeMin)
  60881. let min = math.linearClamp(dis, disBound1, disBound2, closeMin, standardMin); //触屏和滚轮不一样,触发较为连续,所以最小值设低一点。若要保持双指相对点云位置不变,理想最小值是0,但那样就无法穿越点云(最小值太小的话穿越密集点云如树丛很困难;太大会打滑)所以当离点云近时增大最小值
  60882. speed = Math.sign(r) * MathUtils.clamp(dis * Math.abs(r), min, speed);
  60883. //console.log(speed, dis, e.scale)
  60884. }else {
  60885. this.useAttenuation = true;
  60886. let accelerate = 40;
  60887. if(math.closeTo(e.scale,1,0.02)){//缩放小的时候很可能是双指平移时,容易抖动,所以降低移动速度
  60888. accelerate *= Math.min(40*Math.abs(e.scale-1), 0.8);
  60889. }
  60890. // console.log('accelerate',accelerate)
  60891. const constantDis = this.currentViewport.getMoveSpeed() * accelerate; //constantDis = 10;//常量系数,当放大一倍时前进的距离。可以调整
  60892. speed = (e.scale-1)*constantDis;
  60893. }
  60894. }
  60895. var vec = direction.multiplyScalar(speed );
  60896. //this.translationWorldDelta.copy(vec)
  60897. this.translationWorldDelta.add(vec);
  60898. //console.log(direction.toArray(), speed, e.scale)
  60899. }
  60900. return true
  60901. };
  60902. let scroll = (e) => {
  60903. if(!this.enabled || !e.hoverViewport)return
  60904. this.setCurrentViewport(e);
  60905. e.camera = e.hoverViewport.camera;
  60906. dolly(e);
  60907. };
  60908. let dblclick = (e) => {
  60909. if(!this.enabled)return
  60910. if(!Potree.settings.dblToFocusPoint)return;//调试时才可双击
  60911. if(Potree.settings.displayMode == 'showPointCloud'/* !viewer.images360.isAtPano() */) this.zoomToLocation(e.mouse);
  60912. };
  60913. this.viewer.addEventListener('global_drag', drag);
  60914. /* this.viewer.addEventListener('global_touchmove', (e)=>{
  60915. if(!this.enabled)return
  60916. if(e.touches.length>1){//单指的就触发上一句
  60917. //console.log('global_touchmove' )
  60918. drag(e)
  60919. }
  60920. }); */
  60921. this.viewer.addEventListener('global_drop', drop);
  60922. this.viewer.addEventListener('global_mousewheel', scroll);
  60923. this.viewer.addEventListener('global_dblclick', dblclick);
  60924. let prepareScale = (e)=>{//触屏的scale
  60925. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  60926. e.drag.camDisToPointStart = null;
  60927. };
  60928. let prepareRotate = (e)=>{
  60929. this.pointerDragStart = e.pointer.clone();
  60930. if(e.viewer.name != 'mainViewer' )return
  60931. let intersect = e.intersect || e.dragViewport.lastIntersect;
  60932. //在数据集外部时绕中心点旋转,在数据集内部时绕intersect点旋转(其他数据集的点也可以) 或者 原地旋转镜头
  60933. let 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];
  60934. let rotCenter2d, rotCenter;
  60935. if(rotAroundPoint){
  60936. let pivotType = this.target ? 'target' : viewer.atDatasets.length > 0 ? 'intersect' : viewer.inputHandler.selection.length ? 'selection' : this.target2 ? 'target2' : 'boundCenter';
  60937. rotCenter = pivotType == 'target'? this.target :pivotType == 'intersect' ? intersect.location : pivotType == 'selection' ? viewer.inputHandler.selection[0].position : pivotType == 'target2' ? this.target2 :viewer.bound.center;
  60938. if(rotCenter){
  60939. rotCenter2d = rotCenter.clone().project(e.dragViewport.camera); //点在屏幕中的位置。 若z>1 则在背面 或 超出far范围
  60940. }else {
  60941. rotAroundPoint = false;
  60942. }
  60943. }
  60944. this.rotateStartInfo = {
  60945. rotAroundPoint, //定点旋转
  60946. rotCenter,
  60947. rotCenter2d
  60948. };
  60949. //缺点:多数据集绕中心点转很难操作,感觉可以也改为绕lastIntersect
  60950. //console.log('prepareRotate' )
  60951. };
  60952. let preparePan = (e)=>{//触屏的pan点云 还是会偏移
  60953. this.pointerDragStart = e.pointer.clone();
  60954. e.drag.z = void 0; //清空
  60955. drag(e); //触屏点击时更新的pointer直接用一次drag
  60956. //console.log('preparePan ' )
  60957. };
  60958. this.viewer.addEventListener('global_mousedown'/* 'startDragging' */, (e)=>{
  60959. if(!this.enabled)return
  60960. this.setCurrentViewport(e);
  60961. prepareRotate(e);
  60962. });
  60963. //注意,每次增减指头都会修改pointer,需要更新下状态
  60964. this.viewer.addEventListener('global_touchstart', (e)=>{
  60965. if(!this.enabled)return
  60966. if(e.touches.length==2){//只监听开头两个指头
  60967. prepareScale(e);
  60968. preparePan(e);
  60969. }else if(e.touches.length>=3){
  60970. preparePan(e);
  60971. }
  60972. });
  60973. this.viewer.addEventListener('global_touchend', (e)=>{//e.touches是剩余的指头
  60974. if(!this.enabled)return
  60975. if(e.touches.length==2){//停止平移,开始scale
  60976. prepareScale(e);
  60977. preparePan(e);
  60978. }else if(e.touches.length==1){//停止scale,开始rotate
  60979. prepareRotate(e);
  60980. }else if(e.touches.length>=3){//重新准备下平移(因为抬起的指头可能包含平移使用的数据),否则抬起时漂移
  60981. preparePan(e);
  60982. }
  60983. });
  60984. /* this.viewer.addEventListener('enableChangePos', (e)=>{
  60985. if(!this.enabled)return
  60986. this.enableChangePos = e.canLeavePano
  60987. }) */
  60988. }
  60989. canMovePos(viewport){
  60990. if(viewport == viewer.mainViewport && (Potree.settings.displayMode == 'showPanos'
  60991. || viewer.images360.bumping || viewer.images360.latestToPano))return false
  60992. else return true
  60993. }
  60994. setEnable(enabled){
  60995. this.enabled = enabled;
  60996. }
  60997. setTarget(target, index){//绕该点旋转,类似orbitControl
  60998. if(index == 2)this.target2 = target;
  60999. else this.target = target;
  61000. }
  61001. setFPCMoveSpeed(viewport){
  61002. if(viewport.camera.type == 'OrthographicCamera'){
  61003. let s = 1 / viewport.camera.zoom;
  61004. viewport.setMoveSpeed(s);
  61005. }else {
  61006. //根据和漫游点的最短距离算moveSpeed。缺点:对于导入的无漫游点的数据集没有意义。
  61007. if(viewport == viewer.mainViewport && viewer.images360){
  61008. let position = viewer.mainViewport.view.position;
  61009. let speed;
  61010. let pano = viewer.images360.findNearestPano();
  61011. if(!pano){
  61012. if(!viewer.bound || viewer.bound.boundSize.x == 0)return
  61013. let boundFloor = viewer.bound.boundingBox.clone();
  61014. boundFloor.max.z = boundFloor.min.z;
  61015. speed = boundFloor.distanceToPoint(viewer.mainViewport.view.position);
  61016. speed = Math.sqrt(speed) / 50;
  61017. }else {
  61018. let dis = pano.position.distanceTo(position);
  61019. let minSpeed = 0.05, minDis = 3, multiplier = 0.005;
  61020. speed = dis <= minDis ? minSpeed : minSpeed + (dis-minDis) * multiplier;
  61021. //console.log('dis', dis, 'speed', speed, pano.id )
  61022. }
  61023. viewer.setMoveSpeed(speed*2);
  61024. }
  61025. //调试场景t-FhDWmV5xur 两个数据集,大的数据集没有漫游点。
  61026. }
  61027. }
  61028. setCurrentViewport(o={}){//add
  61029. if(!this.enabled && !o.force )return
  61030. if(o.hoverViewport && this.currentViewport != o.hoverViewport ){
  61031. this.currentViewport = o.hoverViewport;
  61032. //this.viewer.setMoveSpeed(this.currentViewport.radius/100);
  61033. this.setFPCMoveSpeed(this.currentViewport);
  61034. }
  61035. if(this.currentViewport.camera.type == 'OrthographicCamera'){
  61036. this.lockElevationOri = true;
  61037. this.lockRotation = true;
  61038. }else {
  61039. this.lockElevationOri = false;
  61040. this.lockRotation = false;
  61041. }
  61042. }
  61043. setScene (scene) {
  61044. this.scene = scene;
  61045. }
  61046. stop(){
  61047. this.yawDelta = 0;
  61048. this.pitchDelta = 0;
  61049. this.translationDelta.set(0, 0, 0);
  61050. }
  61051. zoomToLocation(mouse){
  61052. if(!this.enabled)return
  61053. let camera = this.scene.getActiveCamera();
  61054. /* let I = Utils.getMousePointCloudIntersection(
  61055. mouse,
  61056. camera,
  61057. this.viewer,
  61058. this.scene.pointclouds); */
  61059. var I = this.viewer.inputHandler.intersect;
  61060. if (!I) {
  61061. return;
  61062. }
  61063. let targetRadius = 0;
  61064. {
  61065. let minimumJumpDistance = 0.2;
  61066. let domElement = this.renderer.domElement;
  61067. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer, camera);
  61068. let {origin, direction} = this.viewer.inputHandler.getMouseDirection();
  61069. let raycaster = new Raycaster();
  61070. raycaster.ray.set(origin, direction);
  61071. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  61072. let nodes2 = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, raycaster.ray);
  61073. let lastNode = nodes[nodes.length - 1];
  61074. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  61075. targetRadius = Math.min(this.scene.view.radius, radius);
  61076. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  61077. }
  61078. let d = this.scene.view.direction.multiplyScalar(-1);
  61079. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  61080. // TODO Unused: let controlsTargetPosition = I.location;
  61081. let animationDuration = 600;
  61082. let easing = TWEEN.Easing.Quartic.Out;
  61083. { // animate
  61084. let value = {x: 0};
  61085. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  61086. tween.easing(easing);
  61087. this.tweens.push(tween);
  61088. let startPos = this.scene.view.position.clone();
  61089. let targetPos = cameraTargetPosition.clone();
  61090. let startRadius = this.scene.view.radius;
  61091. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  61092. tween.onUpdate(() => {
  61093. let t = value.x;
  61094. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  61095. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  61096. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  61097. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  61098. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  61099. });
  61100. tween.onComplete(() => {
  61101. this.tweens = this.tweens.filter(e => e !== tween);
  61102. });
  61103. tween.start();
  61104. }
  61105. }
  61106. update (delta=1) {
  61107. if(!this.enabled)return
  61108. //console.log('update')
  61109. let view = this.currentViewport.view;
  61110. { // cancel move animations on user input
  61111. let changes = [ this.yawDelta,
  61112. this.pitchDelta,
  61113. this.translationDelta.length(),
  61114. this.translationWorldDelta.length() ];
  61115. let changeHappens = changes.some(e => Math.abs(e) > 0.001);
  61116. if (changeHappens && this.tweens.length > 0) {
  61117. this.tweens.forEach(e => e.stop());
  61118. this.tweens = [];
  61119. }
  61120. }
  61121. { // accelerate while input is given
  61122. let ih = this.viewer.inputHandler;
  61123. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  61124. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  61125. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  61126. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  61127. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  61128. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  61129. let rotateLeft = this.keys.Rotate_LEFT.some(e => ih.pressedKeys[e]);
  61130. let rotateRight = this.keys.Rotate_RIGHT.some(e => ih.pressedKeys[e]);
  61131. let rotateUp = this.keys.Rotate_UP.some(e => ih.pressedKeys[e]);
  61132. let rotateDown = this.keys.Rotate_DOWN.some(e => ih.pressedKeys[e]);
  61133. this.lockElevation = this.lockElevationOri || this.keys.SPACE.some(e => ih.pressedKeys[e]);
  61134. if(!this.lockRotation){
  61135. if(rotateLeft){
  61136. this.yawDelta -= 0.01;
  61137. }else if(rotateRight){
  61138. this.yawDelta += 0.01;
  61139. }
  61140. if(rotateUp){
  61141. this.pitchDelta -= 0.01;
  61142. }else if(rotateDown){
  61143. this.pitchDelta += 0.01;
  61144. }
  61145. }
  61146. if(this.canMovePos(this.currentViewport) && !this.lockKey){
  61147. if(this.lockElevation){
  61148. let dir = view.direction;
  61149. dir.z = 0;
  61150. dir.normalize();
  61151. if (moveForward && moveBackward) {
  61152. this.translationWorldDelta.set(0, 0, 0);
  61153. } else if (moveForward) {
  61154. this.translationWorldDelta.copy(dir.multiplyScalar(this.currentViewport.getMoveSpeed()));
  61155. } else if (moveBackward) {
  61156. this.translationWorldDelta.copy(dir.multiplyScalar(-this.currentViewport.getMoveSpeed()));
  61157. }
  61158. }else {
  61159. if (moveForward && moveBackward) {
  61160. this.translationDelta.y = 0;
  61161. } else if (moveForward) {
  61162. this.translationDelta.y = this.currentViewport.getMoveSpeed();
  61163. } else if (moveBackward) {
  61164. this.translationDelta.y = -this.currentViewport.getMoveSpeed();
  61165. }
  61166. }
  61167. if (moveLeft && moveRight) {
  61168. this.translationDelta.x = 0;
  61169. } else if (moveLeft) {
  61170. this.translationDelta.x = -this.currentViewport.getMoveSpeed();
  61171. } else if (moveRight) {
  61172. this.translationDelta.x = this.currentViewport.getMoveSpeed();
  61173. }
  61174. if (moveUp && moveDown) {
  61175. this.translationWorldDelta.z = 0;
  61176. } else if (moveUp) {
  61177. this.translationWorldDelta.z = this.currentViewport.getMoveSpeed();
  61178. } else if (moveDown) {
  61179. this.translationWorldDelta.z = -this.currentViewport.getMoveSpeed();
  61180. }
  61181. if(moveUp || moveDown || moveForward || moveBackward){
  61182. this.useAttenuation = false;
  61183. }
  61184. }
  61185. }
  61186. { // apply rotation
  61187. let yaw = view.yaw;
  61188. let pitch = view.pitch;
  61189. yaw += this.yawDelta; /* * delta; */
  61190. pitch += this.pitchDelta;/* * delta; */
  61191. view.yaw = yaw;
  61192. view.pitch = pitch;
  61193. if(this.yawDelta || this.pitchDelta){
  61194. view.cancelFlying('rotate');
  61195. }
  61196. this.yawDelta = 0;
  61197. this.pitchDelta = 0;
  61198. }
  61199. /* if(this.translationWorldDelta.length()>0) {
  61200. // console.log('translationDelta')
  61201. } */
  61202. { // apply translation
  61203. view.translate(
  61204. this.translationDelta.x, /* * delta, */
  61205. this.translationDelta.y, /* * delta, */
  61206. this.translationDelta.z, /* * delta */
  61207. );
  61208. this.translationDelta.set(0,0,0);
  61209. //if(this.translationWorldDelta.length())console.log(translationWorldDelta)
  61210. view.translateWorld(
  61211. this.translationWorldDelta.x /* * delta */,
  61212. this.translationWorldDelta.y /* * delta */,
  61213. this.translationWorldDelta.z /* * delta */
  61214. );
  61215. //this.translationWorldDelta.set(0,0,0)
  61216. }
  61217. { // set view target according to speed
  61218. //view.radius = 1 * this.currentViewport.getMoveSpeed();
  61219. /* if(viewer.bound) view.radius = view.position.distanceTo(viewer.bound.center)
  61220. let speed = view.radius/100;
  61221. this.viewer.setMoveSpeed(speed); */
  61222. //this.setMoveSpeed()
  61223. }
  61224. if(this.useAttenuation){ //只有滚轮缩放时开启
  61225. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  61226. /*this.yawDelta *= attenuation;
  61227. this.pitchDelta *= attenuation;
  61228. this.translationDelta.multiplyScalar(attenuation);*/
  61229. this.translationWorldDelta.multiplyScalar(attenuation);
  61230. }else {
  61231. this.translationWorldDelta.set(0,0,0);
  61232. }
  61233. }
  61234. };
  61235. /**
  61236. * @author mschuetz / http://mschuetz.at
  61237. *
  61238. *
  61239. */
  61240. let {Buttons: Buttons$1} = Potree.defines;
  61241. class InputHandler extends EventDispatcher {
  61242. constructor (viewer,scene) {
  61243. super();
  61244. this.viewer = viewer;
  61245. this.renderer = viewer.renderer;
  61246. this.domElement = this.renderer.domElement;
  61247. this.enabled = true;
  61248. this.scene = scene;
  61249. this.interactiveScenes = [];
  61250. this.interactiveObjects = new Set();
  61251. this.inputListeners = [];
  61252. this.blacklist = new Set();
  61253. this.drag = null;
  61254. this.mouse = new Vector2(0, 0);
  61255. //add:
  61256. this.pointer = new Vector2(0, 0); //交互点的屏幕坐标,有别于DOM坐标,在此存放NDC坐标。(NDC,三维常用坐标系,二维坐标,整个屏幕映射范围(-1,1),屏幕中心为原点,+Y朝上,+X朝右)
  61257. this.mouseDownMouse = new Vector2(0, 0);
  61258. this.selection = [];
  61259. this.hoveredElements = [];
  61260. this.pressedKeys = {};
  61261. this.wheelDelta = 0;
  61262. this.speed = 1;
  61263. this.logMessages = false;
  61264. if (this.domElement.tabIndex === -1) {
  61265. this.domElement.tabIndex = 2222;
  61266. }
  61267. this.lastPointerUpTime = 0;
  61268. this.touches = [];
  61269. this.interactHistory = {move:0}; //add
  61270. this.hoverViewport = viewer.viewports[0];
  61271. this.domElement.addEventListener('contextmenu', (event) => { event.preventDefault(); }, false);
  61272. this.domElement.addEventListener('click', this.onMouseClick.bind(this), false);
  61273. this.domElement.addEventListener('mousedown', this.onMouseDown.bind(this), false);
  61274. window.addEventListener('mouseup', this.onMouseUp.bind(this), false);
  61275. if(Potree.isIframeChild){//子页面的话在父页面也要加侦听(应该不会有多层吧?否则要一直加到最外层)
  61276. //window.parent.addEventListener('mouseup', this.onMouseUp.bind(this), false); //可能跨域
  61277. //window.parent.postMessage('listenMouseup', '*');
  61278. window.addEventListener('mouseout', this.onMouseUp.bind(this), false); //cancel drag
  61279. }
  61280. this.domElement.addEventListener('mouseout', ()=>{
  61281. this.containsMouse = false;
  61282. }, false);
  61283. this.domElement.addEventListener('mousemove', this.onMouseMove.bind(this), false);
  61284. //add
  61285. /* this.domElement.addEventListener("pointerout", this.onMouseUp.bind(this)),
  61286. this.domElement.addEventListener("pointercancel", this.onMouseUp.bind(this)),
  61287. */
  61288. this.domElement.addEventListener('mousewheel', this.onMouseWheel.bind(this), false);
  61289. this.domElement.addEventListener('DOMMouseScroll', this.onMouseWheel.bind(this), false); // Firefox
  61290. //this.domElement.addEventListener('dblclick', this.onDoubleClick.bind(this)); //因为双击时间间隔是跟随系统的所以不好判断
  61291. window.addEventListener('keydown', this.onKeyDown.bind(this));//原先是this.domElement,这样的话一开始要点击屏幕后才能监听到
  61292. window.addEventListener('keyup', this.onKeyUp.bind(this));
  61293. window.addEventListener('blur',this.onKeyUp.bind(this)); //add
  61294. this.domElement.addEventListener('touchstart', this.onTouchStart.bind(this));
  61295. this.domElement.addEventListener('touchend', this.onTouchEnd.bind(this));
  61296. this.domElement.addEventListener('touchmove', this.onTouchMove.bind(this));
  61297. {
  61298. this.measuring = []; //正在编辑的measure
  61299. //let mesureInfo = new THREE.EventDispatcher()
  61300. this.addEventListener('measuring',(e)=>{
  61301. //true优先级高于false, 正在添加时dropMarker也不会停止
  61302. //Potree.Utils.updateVisible(mesureInfo, e.situation, e.v, 0, e.v?'add':'cancel' )//借用该函数,使true优先级高于false,防止正在添加时dropMarker而停止
  61303. if(e.v){
  61304. this.measuring.includes(e.object) || this.measuring.push(e.object);
  61305. }else {
  61306. let index = this.measuring.indexOf(e.object);
  61307. index > -1 && this.measuring.splice(index, 1);
  61308. }
  61309. if(this.measuring.length == 0 && this.measuring.length>0 ){
  61310. this.viewer.viewports.forEach((viewport)=>{
  61311. this.collectClosePoints(viewport, true );//forceUpdate
  61312. });
  61313. }
  61314. //console.log('measuring',e.v, e.cause, e.situation, this.measuring.length )
  61315. });
  61316. }
  61317. window.viewer.addEventListener('loopStart',()=>{
  61318. this.interactHistory = {}; //清空
  61319. });
  61320. }
  61321. /* addInputListener (listener) {
  61322. this.inputListeners.push(listener);
  61323. }
  61324. removeInputListener (listener) {
  61325. this.inputListeners = this.inputListeners.filter(e => e !== listener);
  61326. }
  61327. getSortedListeners(){
  61328. return this.inputListeners.sort( (a, b) => {
  61329. let ia = (a.importance !== undefined) ? a.importance : 0;
  61330. let ib = (b.importance !== undefined) ? b.importance : 0;
  61331. return ib - ia;
  61332. });
  61333. } */
  61334. //统一跟第一个触碰的viewport相同
  61335. updateTouchesInfo(e){
  61336. var viewport, pointer, camera;
  61337. let oldTouches = this.touches;
  61338. let changedTouches = Array.from(e.changedTouches);
  61339. let touches = Array.from(e.touches);
  61340. this.touches = touches.map(touch=>{
  61341. let touch_ = oldTouches.find(a=>a.touch.identifier == touch.identifier);
  61342. let pointer = touch_ && touch_.pointer; //复制原先的值
  61343. return {
  61344. touch, pointer,
  61345. }
  61346. });
  61347. if(e.touches.length > 0){
  61348. let newTouches = touches.filter(e=>!
  61349. oldTouches.some(a=>a.touch.identifier == e.identifier) && !changedTouches.some(a=>a.identifier == e.identifier)
  61350. ); //从按钮处划过时e.touches中会出现this.touches和changedTouches中都没有的identifier
  61351. if(newTouches.length>0){
  61352. console.warn('has new',newTouches.map(e=>e.identifier));
  61353. }
  61354. newTouches.concat(changedTouches).forEach(touch=>{ //修改changedTouches的
  61355. let touch_ = this.touches.find(a=>a.touch.identifier == touch.identifier);
  61356. if(touch_){
  61357. let a = this.getPointerInViewport(touch.pageX, touch.pageY, this.dragViewport||viewport, new Vector2);
  61358. touch_.pointer = a.pointer.clone();
  61359. viewport = a.viewport; camera = a.camera;
  61360. }
  61361. });
  61362. //使用当前touches的平均
  61363. if(e.touches.length > 1){
  61364. let pageX = Common$1.average(e.touches, "pageX");
  61365. let pageY = Common$1.average(e.touches, "pageY");
  61366. let a = this.getPointerInViewport(pageX, pageY, viewport, new Vector2);
  61367. this.pointer.copy(a.pointer);
  61368. //console.log('updateTouchesInfo', this.pointer.clone())
  61369. }else {
  61370. this.pointer = this.touches[0].pointer.clone(); //更新,使用当前touches中的第一个
  61371. }
  61372. /* if(this.touches.find(e=>!e.pointer)){
  61373. console.error(' touches has no pointer', oldTouches.map(e=>e.touch.identifier),
  61374. Array.from(e.touches).map(e=>e.identifier), Array.from(e.changedTouches).map(e=>e.identifier) )
  61375. } */
  61376. //console.log(this.touches)
  61377. //console.log('更新pointer1',this.pointer.toArray())
  61378. return {viewport, camera/* , pointer:this.pointer */}
  61379. }
  61380. }
  61381. onTouchStart (e) {
  61382. if (this.logMessages) console.log(this.constructor.name + ': onTouchStart');
  61383. e.preventDefault();
  61384. /* if (e.touches.length === 1 || !this.drag) { //!this.drag代表一次性下了两个指头
  61385. let rect = this.domElement.getBoundingClientRect();
  61386. let x = e.touches[0].pageX
  61387. let y = e.touches[0].pageY
  61388. this.dealPointerDown(x,y,e,true)
  61389. }else{
  61390. this.updateTouchesInfo(e)
  61391. this.drag.end.copy(this.pointer)
  61392. } */
  61393. this.dealPointerDown(e,true);
  61394. this.viewer.dispatchEvent($.extend(
  61395. this.getEventDesc(e,true),
  61396. {
  61397. type: 'global_' + e.type,
  61398. changedTouches: e.changedTouches
  61399. }
  61400. ));
  61401. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  61402. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  61403. ) */
  61404. //console.log('')
  61405. }
  61406. onTouchMove (e) {
  61407. if (this.logMessages) console.log(this.constructor.name + ': onTouchMove');
  61408. e.preventDefault();
  61409. /* if (e.touches.length === 1) {
  61410. let rect = this.domElement.getBoundingClientRect();
  61411. let x = e.touches[0].pageX;
  61412. let y = e.touches[0].pageY;
  61413. }else{
  61414. this.updateTouchesInfo(e)
  61415. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end)
  61416. this.drag.end.copy(this.pointer)
  61417. }
  61418. */
  61419. this.dealPointerMove(e, true);
  61420. this.viewer.dispatchEvent($.extend(
  61421. this.getEventDesc(e,true),
  61422. {
  61423. type: 'global_' + e.type,
  61424. changedTouches: e.changedTouches
  61425. }
  61426. ));
  61427. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  61428. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  61429. ) */
  61430. }
  61431. onTouchEnd (e) {
  61432. if (this.logMessages) console.log(this.constructor.name + ': onTouchEnd');
  61433. e.preventDefault();
  61434. //console.log('onTouchEnd')
  61435. this.updateTouchesInfo(e);
  61436. /* if (e.touches.length === 0) {
  61437. let rect = this.domElement.getBoundingClientRect();
  61438. let x = e.changedTouches[0].pageX //万一一次松开两个指头的怎么办
  61439. let y = e.changedTouches[0].pageY
  61440. this.dealPointerUp(x,y,e,true)
  61441. }else {
  61442. this.drag.end.copy(this.pointer)
  61443. } */
  61444. this.dealPointerUp(e,true);
  61445. this.viewer.dispatchEvent($.extend(
  61446. this.getEventDesc(e,true),
  61447. {
  61448. type: 'global_' + e.type,
  61449. }
  61450. ));
  61451. //console.log('touchend length '+e.touches.length, this.touches.length)
  61452. }
  61453. onKeyDown (e) {
  61454. if (this.logMessages) console.log(this.constructor.name + ': onKeyDown');
  61455. if(!this.containsMouse)return //在别的ui上无效
  61456. // DELETE
  61457. /* if (e.keyCode === KeyCodes.DELETE && this.selection.length > 0) {
  61458. this.dispatchEvent({
  61459. type: 'delete',
  61460. selection: this.selection
  61461. });
  61462. this.deselectAll();
  61463. } */
  61464. this.dispatchEvent({
  61465. type: 'keydown',
  61466. keyCode: e.keyCode,
  61467. event: e
  61468. });
  61469. // for(let l of this.getSortedListeners()){
  61470. // l.dispatchEvent({
  61471. // type: "keydown",
  61472. // keyCode: e.keyCode,
  61473. // event: e
  61474. // });
  61475. // }
  61476. this.pressedKeys[e.keyCode] = true;
  61477. // e.preventDefault();
  61478. }
  61479. onKeyUp (e) {
  61480. if (this.logMessages) console.log(this.constructor.name + ': onKeyUp');
  61481. if(e.keyCode != void 0){
  61482. delete this.pressedKeys[e.keyCode];
  61483. }else {
  61484. this.pressedKeys = {};
  61485. }
  61486. e.preventDefault();
  61487. }
  61488. onDoubleClick (e) {
  61489. if (this.logMessages) console.log(this.constructor.name + ': onDoubleClick');
  61490. let consumed = false;
  61491. for (let hovered of this.hoveredElements) {
  61492. if (hovered._listeners && hovered._listeners['dblclick']) {
  61493. hovered.object.dispatchEvent({
  61494. type: 'dblclick',
  61495. mouse: this.mouse,
  61496. object: hovered.object
  61497. });
  61498. consumed = true;
  61499. break;
  61500. }
  61501. }
  61502. if (!consumed) {
  61503. /* for (let inputListener of this.getSortedListeners()) {
  61504. inputListener. */this.viewer.dispatchEvent({
  61505. type: 'global_dblclick',
  61506. mouse: this.mouse,
  61507. object: null
  61508. });
  61509. //}
  61510. }
  61511. this.needSingleClick = false;//add
  61512. e.preventDefault();
  61513. }
  61514. onMouseClick (e) {
  61515. if (this.logMessages) console.log(this.constructor.name + ': onMouseClick');
  61516. e.preventDefault();
  61517. }
  61518. dealPointerDown(e,isTouch){
  61519. e.preventDefault();
  61520. //重新获取一下pointer, 因点击了浏览器的按钮展开列表时 move回来不会触发onmousemove,所以pointer是旧的
  61521. if(isTouch){
  61522. var { camera, viewport } = this.updateTouchesInfo(e);
  61523. if(this.drag){
  61524. //因为触屏在按下前缺少pointermove所以要更新下
  61525. this.drag.end = this.pointer.clone();
  61526. }
  61527. }else {
  61528. var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY );
  61529. }
  61530. this.dragViewport = this.hoverViewport = viewport;
  61531. //if(isTouch || !Potree.settings.intersectWhenHover ){
  61532. if(isTouch || !this.dragViewport.view.isFlying() && Potree.settings.intersectWhenHover && Potree.settings.editType != 'pano' ){//漫游点编辑如果拖拽前getIntersect旋转会延迟
  61533. //isTouch必须更新 否则是旧的
  61534. this.hoveredElements = this.getHoveredElements();
  61535. let dontIntersect = false;
  61536. this.intersect = this.getIntersect({viewport, dontIntersect, clientX:e.clientX, clientY:e.clientY}); //更新intersect,避免在没有mousemove但flyToPano后intersect未更新。
  61537. //this.intersect = this.getWholeIntersect()
  61538. }
  61539. if(!viewport)return //why add this?
  61540. if (!this.drag) {
  61541. let target = (isTouch||e.button == MOUSE.LEFT) && this.hoveredElements.find(el => (//只有左键能拖拽
  61542. el.object._listeners &&
  61543. el.object._listeners['drag'] &&
  61544. el.object._listeners['drag'].length > 0));
  61545. if (target) {
  61546. this.startDragging(target.object, {location: target.point});
  61547. } else {
  61548. this.startDragging(null);
  61549. }
  61550. }
  61551. this.drag.intersectStart = this.intersect;
  61552. if(!isTouch || e.touches.length == 1){
  61553. let consumed = false;
  61554. let consume = () => { return consumed = true; };
  61555. //if (this.hoveredElements.length === 0) {
  61556. this.viewer.dispatchEvent($.extend(
  61557. this.getEventDesc(e,isTouch),
  61558. {
  61559. type: 'global_mousedown'
  61560. }
  61561. ));
  61562. for(let hovered of this.hoveredElements){
  61563. let object = hovered.object;
  61564. object.dispatchEvent({
  61565. type: 'mousedown',
  61566. viewer: this.viewer,
  61567. consume: consume
  61568. });
  61569. if(consumed){
  61570. break;
  61571. }
  61572. }
  61573. }
  61574. this.mouseDownMouse = this.mouse.clone();
  61575. this.pointerDownTime = Date.now();
  61576. }
  61577. onMouseDown (e) {
  61578. if (this.logMessages) console.log(this.constructor.name + ': onMouseDown');
  61579. this.dealPointerDown(e);
  61580. }
  61581. /* getWholeIntersect(hoveredElements, intersectPoint){//add
  61582. hoveredElements = hoveredElements || this.hoveredElements
  61583. intersectPoint = intersectPoint || this.intersectPoint
  61584. if(Potree.settings.intersectOnObjs && hoveredElements[0] && hoveredElements[0].object.isModel){
  61585. return {//模拟点云的intersectPoint的结构写法
  61586. hoveredElement : hoveredElements[0] ,
  61587. location: hoveredElements[0].point,
  61588. point: {normal: hoveredElements[0].face.normal },
  61589. distance: hoveredElements[0].distance,
  61590. object: hoveredElements[0].object
  61591. }
  61592. }else return intersectPoint
  61593. } */
  61594. getEventDesc(e,isTouch){//搜集dispatchEvent要给的一般数据
  61595. let o = {
  61596. viewer: this.viewer,
  61597. mouse: this.mouse,
  61598. pointer:this.pointer,
  61599. drag :this.drag,
  61600. isTouch,
  61601. dragViewport : this.dragViewport,
  61602. hoverViewport: this.hoverViewport,
  61603. // button: isTouch ? 0 : e.button,
  61604. //intersectPoint:this.intersectPoint,
  61605. hoveredElement: this.hoveredElements[0],
  61606. intersect: this.intersect//this.getWholeIntersect() , //可能包含mesh上的,针对融合页面
  61607. };
  61608. if(e){
  61609. o.isAtDomElement = e.target == this.domElement;
  61610. }
  61611. if(isTouch){
  61612. o.touches = this.touches;
  61613. }else if(e){
  61614. o.button = e.button;
  61615. o.buttons = e.buttons;
  61616. }
  61617. return o;
  61618. }
  61619. dealPointerUp(e,isTouch){
  61620. if(!this.drag){// 在canvas外mousedown
  61621. return
  61622. }
  61623. this.drag.end.copy(this.pointer);
  61624. if(isTouch && e.touches.length >= 1){
  61625. return
  61626. }
  61627. let now = Date.now();
  61628. if (this.logMessages) console.log(this.constructor.name + ': onMouseUp');
  61629. e.preventDefault();
  61630. let pressDistance = this.mouseDownMouse.distanceTo(this.mouse);
  61631. let pressTime = now - this.pointerDownTime;
  61632. let noMovement = this.drag.pointerDelta.length() == 0;//this.getNormalizedDrag().length() === 0;
  61633. let consumed = false;
  61634. let consume = () => { return consumed = true; };
  61635. //if (this.hoveredElements.length === 0) {
  61636. /* for (let inputListener of this.getSortedListeners()) {
  61637. inputListener */this.viewer.dispatchEvent($.extend(
  61638. this.getEventDesc(e,isTouch),
  61639. {
  61640. type: 'global_mouseup',
  61641. pressDistance,
  61642. consume,
  61643. }
  61644. ));
  61645. /* if(consumed){//??
  61646. break;
  61647. } */
  61648. //}
  61649. //}
  61650. if (this.hoveredElements.length > 0) {
  61651. let hovered = this.hoveredElements
  61652. .map(e => e.object)
  61653. .find(e => (e._listeners && e._listeners['mouseup']));
  61654. if(hovered){
  61655. hovered.dispatchEvent({
  61656. type: 'mouseup',
  61657. viewer: this.viewer,
  61658. consume: consume
  61659. });
  61660. }
  61661. }
  61662. if (this.drag) {
  61663. //拖拽结束
  61664. if (this.drag.object/* && e.button == THREE.MOUSE.LEFT */) {//add LEFT
  61665. if (this.logMessages) console.log(`${this.constructor.name}: drop ${this.drag.object.name}`);
  61666. this.drag.object.dispatchEvent($.extend(
  61667. this.getEventDesc(e,isTouch),
  61668. {
  61669. type: 'drop',
  61670. pressDistance,
  61671. }
  61672. ));
  61673. } else {
  61674. this.viewer.dispatchEvent($.extend(
  61675. this.getEventDesc(e,isTouch),
  61676. {
  61677. type: 'global_drop',
  61678. pressDistance
  61679. }
  61680. ));
  61681. }
  61682. // check for a click
  61683. if(pressDistance < Potree.config.clickMaxDragDis && pressTime<Potree.config.clickMaxPressTime && !e.unableClick){
  61684. let clickElement, consumed = false;
  61685. if(this.hoveredElements){
  61686. clickElement = this.hoveredElements.find(e=>e.object._listeners['click']);
  61687. if(clickElement){
  61688. let canceled;
  61689. let cancel = () => { return canceled = true; };
  61690. //console.log('clickElement',clickElement)
  61691. if (this.logMessages) console.log(`${this.constructor.name}: click ${clickElement.name}`);
  61692. clickElement.object.dispatchEvent($.extend(
  61693. this.getEventDesc(e,isTouch),
  61694. {
  61695. type: 'click',
  61696. pressDistance ,
  61697. cancel
  61698. }
  61699. ));
  61700. if(canceled){//比如只需要右键的话,可以忽视左键的点击
  61701. clickElement = null;
  61702. }
  61703. }
  61704. }
  61705. let selectable;
  61706. if(/* !consumed && */ !this.fixSelection){
  61707. if (e.button === MOUSE.LEFT) {
  61708. if (noMovement) {
  61709. selectable = this.hoveredElements.find(el => el.object._listeners && el.object._listeners['select']);
  61710. if (selectable) {
  61711. selectable = selectable.object;
  61712. if (this.isSelected(selectable)) {
  61713. this.deselectAll();
  61714. } else {
  61715. this.deselectAll();
  61716. this.toggleSelection(selectable);
  61717. }
  61718. consumed = true; //add
  61719. } else {
  61720. if(this.selection.length>0)consumed = true; //add 取消选择后,阻断后续
  61721. this.deselectAll();
  61722. }
  61723. }
  61724. } else if ((e.button === MOUSE.RIGHT) && noMovement) {
  61725. this.deselectAll();
  61726. }
  61727. }
  61728. let consume = () => { return consumed = true; };
  61729. let desc = this.getEventDesc(e,isTouch);
  61730. if(!consumed){
  61731. this.viewer.dispatchEvent($.extend(
  61732. desc,
  61733. {
  61734. type: 'global_click',
  61735. pressDistance,
  61736. clickElement:clickElement/* || selectable */,
  61737. consume
  61738. }
  61739. ));
  61740. }
  61741. //增加 单击:
  61742. this.needSingleClick = true;
  61743. consumed || setTimeout(()=>{
  61744. if(this.needSingleClick){
  61745. this.viewer.dispatchEvent($.extend(
  61746. desc,
  61747. {
  61748. type: 'global_single_click',
  61749. pressDistance,
  61750. clickElement
  61751. }
  61752. ));
  61753. }
  61754. }, Potree.config.doubleClickTime+1);
  61755. //自行执行双击:
  61756. if(now - this.lastClickTime < Potree.config.doubleClickTime){
  61757. this.onDoubleClick(e);
  61758. }
  61759. this.lastClickTime = now;
  61760. }
  61761. this.drag = null;
  61762. }
  61763. this.dragViewport = null;
  61764. }
  61765. onMouseUp (e) {
  61766. this.dealPointerUp( e );
  61767. }
  61768. getPointerInViewport(clientX, clientY, viewForceAt, pointer ){
  61769. let rect = this.domElement.getBoundingClientRect();
  61770. let x = clientX - rect.left;
  61771. let y = clientY - rect.top;
  61772. let camera;
  61773. let viewport;
  61774. pointer = pointer ||this.pointer;
  61775. //if(this.viewer.viewports || viewForceAt){
  61776. var getDimension = (view)=>{
  61777. var left = Math.ceil(this.domElement.clientWidth * view.left)
  61778. , bottom = Math.ceil(this.domElement.clientHeight * view.bottom)
  61779. , width = Math.ceil(this.domElement.clientWidth * view.width)
  61780. , height = Math.ceil(this.domElement.clientHeight * view.height)
  61781. , top = this.domElement.clientHeight - bottom - height;
  61782. return {left, bottom, width, height, top}
  61783. };
  61784. var getView = (view, left, bottom, width, height, top)=>{
  61785. this.mouse.set(x-left, y - top );
  61786. Utils.convertScreenPositionToNDC(pointer, this.mouse, width, height);
  61787. //console.log('更新pointer2',this.pointer.toArray())
  61788. camera = view.camera;
  61789. viewport = view;
  61790. };
  61791. if(viewForceAt){
  61792. let {left, bottom, width, height, top} = getDimension(viewForceAt);
  61793. getView(viewForceAt, left, bottom, width, height, top);
  61794. }else {
  61795. var length = this.viewer.viewports.length;
  61796. //var getif = false
  61797. for(var i=0;i<length;i++){
  61798. var view = this.viewer.viewports[i];
  61799. if(!view.active)continue
  61800. var {left, bottom, width, height, top} = getDimension(view);
  61801. if(x >= left && x <= left + width && y >= top && y <= top + height){
  61802. getView(view, left, bottom, width, height, top);
  61803. //getif = true
  61804. break;
  61805. }
  61806. }
  61807. }
  61808. return {
  61809. camera, viewport, pointer
  61810. }
  61811. }
  61812. ifBlockedByIntersect({point, margin=0, cameraPos, pickWindowSize, pano, useDepthTex, viewport}={}){//某点是否被遮挡(不允许camera修改位置, 因为depthTex不好置换)
  61813. viewport = viewport || this.hoverViewport || viewer.mainViewport;
  61814. let intersect = this.getIntersect({viewport, onlyGetIntersect:true, pickWindowSize, useDepthTex, point, cameraPos, pano });
  61815. let cameraPos_ = (!cameraPos && pano) ? pano.position : (cameraPos||viewport.view.position);
  61816. if(intersect && intersect.distance+margin <= point.distanceTo(cameraPos_)){
  61817. return intersect //被遮挡
  61818. }
  61819. //点云模式,对没加载出的点云不准确。 尤其是需要修改相机位置时,因临时修改并不能使点云加载。
  61820. }
  61821. collectClosePoints(viewport, forceUpdate){//获取吸附点
  61822. if(!Potree.settings.adsorption)return
  61823. let point2ds = [];
  61824. //吸附测量线端点
  61825. viewer.scene.measurements.forEach(e=>{
  61826. if(this.measuring.includes(e)) return//不吸附到正在拖拽的自身
  61827. point2ds.push(...e.getPointsPos2d(viewport, forceUpdate));
  61828. });
  61829. return point2ds
  61830. }
  61831. getIntersect({viewport, onlyGetIntersect, pickWindowSize, dontIntersect, usePointcloud, useDepthTex, cameraPos, point, pano, clientX, clientY}={}){// usePointcloud:必须使用点云
  61832. let intersect, intersectPoint, intersectOnModel, allElements;
  61833. let camera = viewport.camera;
  61834. let raycaster;
  61835. viewer.addTimeMark('getIntersect','start');
  61836. let getByDepthTex = ()=>{
  61837. let intersect;
  61838. if(point){
  61839. let cameraPos = pano ? pano.position : camera.position;
  61840. let dir = new Vector3().subVectors(point, cameraPos).normalize();
  61841. intersect = {dir};
  61842. }else {
  61843. intersect = Utils.getIntersect(camera, [viewer.images360.cube], this.pointer, raycaster);
  61844. }
  61845. intersectPoint = viewer.images360.depthSampler.sample(intersect, pano, !!point); //可能不准确, 因pano可能未加载depthTex
  61846. if(intersectPoint && Potree.settings.depTexLocBindDataset){
  61847. intersectPoint.pointcloud = ( pano || viewer.images360.currentPano).pointcloud;
  61848. //在全景模式下,虽然深度图上的点可能对应别的pointcloud,但因为是在当前全景图处得到的,所以即使将原本对应的点云移走,该点也不移动是有道理的。它可以永远跟着该全景图。
  61849. }
  61850. };
  61851. let getByCloud = ()=>{
  61852. let pointer, mouse;
  61853. if(point){//指定了目标点,而非只是用pointer所在位置
  61854. cameraPos && camera.position.copy( cameraPos);
  61855. camera.lookAt(point);
  61856. camera.updateMatrixWorld();
  61857. pointer = this.pointer.clone();
  61858. mouse = this.mouse.clone();
  61859. this.pointer.set(0,0); //画布中心
  61860. this.mouse.set(Math.round(viewport.resolution.x/2), Math.round(viewport.resolution.y/2));
  61861. }
  61862. intersectPoint = (viewport.noPointcloud || dontIntersect)? null : Utils.getMousePointCloudIntersection(
  61863. viewport,
  61864. this.mouse,
  61865. this.pointer,
  61866. camera,
  61867. this.viewer,
  61868. this.viewer.scene.pointclouds,
  61869. {pickClipped: true, measuring: this.measuring.length>0, pickWindowSize, cameraChanged: !!point }
  61870. );
  61871. //恢复
  61872. if(point){
  61873. viewport.view.applyToCamera(camera);
  61874. this.pointer.copy(pointer);
  61875. this.mouse.copy(mouse);
  61876. }
  61877. };
  61878. if(this.measuring.length && Potree.settings.adsorption ){//吸附
  61879. let points = this.collectClosePoints(viewport);
  61880. let points2 = points.filter(e=>e.trueSide && e.inSight
  61881. && math.closeTo(this.mouse, e.posInViewport, Potree.config.measure.adsorptMinDis)
  61882. );
  61883. let disArr = points2.map(e=> e.pos.distanceToSquared(this.mouse) );
  61884. let min = points2.slice().sort((a,b)=>disArr[points.indexOf(a)] - disArr[points.indexOf(b)]);
  61885. if(min[0]){
  61886. intersect = {
  61887. //hoveredElement
  61888. location: min[0].pos3d,
  61889. //point: {normal: allElements[0].face.normal },
  61890. //normal
  61891. //distance
  61892. object: min[0].object,
  61893. adsorption:true
  61894. };
  61895. console.log('找到吸附点', min[0].pos3d, min[0].object.uuid);
  61896. }
  61897. }
  61898. if(!intersect){
  61899. let canUseDepthTex = (Potree.settings.displayMode == 'showPanos' || useDepthTex)
  61900. && viewer.images360.currentPano.pointcloud.hasDepthTex && viewport == viewer.mainViewport && !usePointcloud;
  61901. if(canUseDepthTex)getByDepthTex();
  61902. else getByCloud();
  61903. /* if(canUseDepthTex && this.measuring.length){
  61904. getByDepthTex()
  61905. }else{
  61906. getByCloud()
  61907. if(!intersectPoint && canUseDepthTex ){ //若在测量,先尝试点云,再用全景 //后来发现有深度图的点云全景visibleNode为空,pick不到的
  61908. getByDepthTex()
  61909. }
  61910. } */
  61911. //console.log(viewport.name , intersectPoint && intersectPoint.location )
  61912. if(Potree.settings.intersectOnObjs && !dontIntersect){
  61913. if(point){
  61914. raycaster = new Raycaster();
  61915. var dir = new Vector3().subVectors(point, camera.position).normalize();
  61916. raycaster.set(camera.position, dir); //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera),
  61917. }
  61918. allElements = this.getHoveredElements(viewer.objs.children, true, raycaster);
  61919. if(allElements[0]){
  61920. intersectOnModel = {//模拟点云的intersectPoint的结构写法
  61921. hoveredElement : allElements[0] ,
  61922. location: allElements[0].point,
  61923. //point: {normal: allElements[0].face.normal },
  61924. normal: allElements[0].face && allElements[0].face.normal,
  61925. distance: allElements[0].distance,
  61926. object: allElements[0].object
  61927. };
  61928. }
  61929. }
  61930. if(intersectPoint && intersectOnModel){
  61931. if(intersectPoint.distance < intersectOnModel.distance){
  61932. intersect = intersectPoint;
  61933. }else {
  61934. intersect = intersectOnModel;
  61935. }
  61936. }else {
  61937. intersect = intersectOnModel || intersectPoint;
  61938. }
  61939. }
  61940. if(viewport.camera.type == 'OrthographicCamera'/* == 'mapViewport' */){
  61941. let pos3d = new Vector3(this.pointer.x,this.pointer.y,-1).unproject(viewport.camera); //z:-1朝外
  61942. if(!intersect){
  61943. intersect = {};
  61944. }
  61945. intersect.orthoIntersect = pos3d.clone();
  61946. }
  61947. //记录全部hover到的:
  61948. if(intersect){
  61949. intersect.allElements = allElements;
  61950. intersect.pointclouds = intersectPoint ? intersectPoint.pointclouds : [];
  61951. }
  61952. viewer.addTimeMark('getIntersect','end');
  61953. //点云费时:2-15ms
  61954. //深度图费时: 0.1-0.2ms
  61955. /*
  61956. intersect && intersect.location && intersect.location.applyMatrix4(viewer.scene.scene.matrix)//add
  61957. */
  61958. if(onlyGetIntersect){
  61959. return intersect
  61960. }
  61961. if (intersect) {
  61962. if(viewer.showCoordType){ //显示坐标位置时
  61963. let pos = intersect.point.position.toArray();
  61964. if(viewer.showCoordType == "local"){
  61965. }else if(viewer.showCoordType == "lonlat"){
  61966. pos = viewer.transform.lonlatToLocal.inverse(pos);
  61967. }else {
  61968. pos = viewer.transform.lonlatToLocal.inverse(pos);
  61969. pos = viewer.transform.lonlatTo4550.forward(pos);
  61970. }
  61971. viewer.dispatchEvent({
  61972. type : "coordinateChange", pos
  61973. });
  61974. }
  61975. }
  61976. //console.log('getIntersect', !!intersectPoint)
  61977. this.intersect = intersect;
  61978. intersect && (this.hoverViewport.lastIntersect = intersect);
  61979. return intersect
  61980. }
  61981. onMouseMove (e) {
  61982. return this.dealPointerMove( e )
  61983. }
  61984. dealPointerMove(e, isTouch){
  61985. if(this.interactHistory.move) return //一帧只触发一次
  61986. this.interactHistory.move = 1;
  61987. if(isTouch){
  61988. var { camera, viewport } = this.updateTouchesInfo(e);
  61989. }else {
  61990. var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY, this.dragViewport);
  61991. }
  61992. this.hoverViewport = viewport;
  61993. if(!viewport)return//刚变化viewport时会找不到
  61994. let isFlying = this.viewer.viewports.some(e=>e.view.isFlying()) || viewer.scene.cameraAnimations.some(c=>c.onUpdate);
  61995. let intersect;
  61996. if(e.onlyGetIntersect || (!this.drag || this.drag.object || viewport.alignment ) ){ //没有拖拽物体,但按下鼠标了的话,不intersect。触屏的就能直接避免intersect
  61997. let dontIntersect = this.drag && viewport.alignment || isFlying || !Potree.settings.intersectWhenHover; // flying 时可能卡顿
  61998. //console.log('dontIntersectPointcloud',dontIntersectPointcloud)
  61999. intersect = this.getIntersect(Object.assign({}, e, {viewport, dontIntersect, clientX:e.clientX, clientY:e.clientY })); //数据集多的时候卡顿
  62000. }
  62001. if(e.onlyGetIntersect){
  62002. return intersect
  62003. }
  62004. e.preventDefault();
  62005. if (this.drag) {//有拖拽(不一定拖拽了物体, 也不一定按下了鼠标)
  62006. this.drag.mouse = isTouch ? 1 : e.buttons;
  62007. //add:
  62008. //this.drag.pointer = this.pointer.clone();
  62009. //this.drag.hoverViewport = this.hoverViewport
  62010. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end);
  62011. this.drag.end.copy(this.pointer);
  62012. let dragConsumed = false;
  62013. if (this.drag.object && (e.buttons == Buttons$1.NONE || !this.drag.notPressMouse )){//如果是本不需要按鼠标的拖拽,但按下了鼠标,就不执行这段(改为拖拽场景,如添加测量时突然拖拽画面)
  62014. if (this.logMessages) console.log(this.constructor.name + ': drag: ' + this.drag.object.name);
  62015. let refused;
  62016. this.drag.object.dispatchEvent($.extend(
  62017. this.getEventDesc(e,isTouch),
  62018. {
  62019. type: 'drag', //拖拽物体
  62020. refuse: () => {refused = true;}
  62021. }
  62022. ));
  62023. if(!refused)dragConsumed = true;
  62024. viewer.dispatchEvent('content_changed');
  62025. }
  62026. if(!dragConsumed){
  62027. if (this.logMessages) console.log(this.constructor.name + ': drag: ');
  62028. this.viewer.dispatchEvent($.extend(
  62029. this.getEventDesc(e,isTouch),
  62030. {
  62031. type: 'global_drag', //拖拽画面
  62032. //consume: () => {dragConsumed = true;}
  62033. }
  62034. ));
  62035. }
  62036. }
  62037. if(!isTouch || e.touches.length == 1){
  62038. if((!this.drag || this.drag.notPressMouse || Potree.settings.intersectOnObjs && this.drag.object) && !isFlying){
  62039. /* let blacklist = this.drag && this.drag */
  62040. let hoveredElements = this.getHoveredElements( );
  62041. if(hoveredElements.length > 0){
  62042. let names = hoveredElements.map(h => h.object.name).join(", ");
  62043. if (this.logMessages) console.log(`${this.constructor.name}: onMouseMove; hovered: '${names}'`);
  62044. }
  62045. let curr = hoveredElements.map(a => a.object).find(a => true);//只取第一个
  62046. let prev = this.lastMouseoverElement; //this.hoveredElements.map(a => a.object).find(a => true);
  62047. if(curr !== prev){
  62048. if(curr){
  62049. if (this.logMessages) console.log(`${this.constructor.name}: mouseover: ${curr.name}`);
  62050. curr.dispatchEvent({
  62051. type: 'mouseover',
  62052. object: curr,
  62053. });
  62054. }
  62055. if(prev){
  62056. if (this.logMessages) console.log(`${this.constructor.name}: mouseleave: ${prev.name}`);
  62057. prev.dispatchEvent({
  62058. type: 'mouseleave',
  62059. object: prev,
  62060. });
  62061. }
  62062. this.lastMouseoverElement = curr;
  62063. viewer.dispatchEvent('content_changed');
  62064. }
  62065. if(hoveredElements.length > 0){
  62066. let object = hoveredElements
  62067. .map(e => e.object)
  62068. .find(e => (e._listeners && e._listeners['mousemove']));
  62069. if(object){
  62070. object.dispatchEvent({
  62071. type: 'mousemove',
  62072. object: object
  62073. });
  62074. }
  62075. }
  62076. this.hoveredElements = hoveredElements;
  62077. }
  62078. //this.intersect = this.getWholeIntersect()
  62079. this.viewer.dispatchEvent($.extend(
  62080. this.getEventDesc(e,isTouch),
  62081. {
  62082. type: 'global_mousemove',
  62083. }
  62084. ));
  62085. this.containsMouse = true;
  62086. }
  62087. }
  62088. onMouseWheel(e){
  62089. if(!this.enabled) return;
  62090. if(this.logMessages) console.log(this.constructor.name + ": onMouseWheel");
  62091. e.preventDefault();
  62092. let delta = 0;
  62093. if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9
  62094. delta = e.wheelDelta;
  62095. } else if (e.detail !== undefined) { // Firefox
  62096. delta = -e.detail;
  62097. }
  62098. let ndelta = Math.sign(delta);
  62099. // this.wheelDelta += Math.sign(delta);
  62100. if(!this.hoverViewport){//调试手机版时会无
  62101. var { viewport } = this.getPointerInViewport(e.clientX, e.clientY );
  62102. this.hoverViewport = viewport;
  62103. }
  62104. if (this.hoveredElement) {
  62105. this.hoveredElement.object.dispatchEvent($.extend(
  62106. this.getEventDesc(e,isTouch),
  62107. {
  62108. type: 'mousewheel',
  62109. delta: ndelta,
  62110. object: this.hoveredElement.object
  62111. }
  62112. ));
  62113. } else {
  62114. this.viewer.dispatchEvent($.extend(
  62115. this.getEventDesc(e),
  62116. {
  62117. type: 'global_mousewheel',
  62118. delta: ndelta,
  62119. }
  62120. ));
  62121. }
  62122. setTimeout(()=>{
  62123. this.dealPointerMove(e );//add 在更新完view后重新获取intersect 和 drag
  62124. },1);//只延迟1会崩溃吗
  62125. }
  62126. startDragging (object, args = null) {
  62127. let name = object ? object.name : "no name";
  62128. if (this.logMessages) console.log(`${this.constructor.name}: startDragging: '${name}'`);
  62129. this.drag = {
  62130. start: this.pointer.clone(),
  62131. end: this.pointer.clone(),
  62132. pointerDelta: new Vector2(0, 0),
  62133. object: object,
  62134. hoverViewport: this.hoverViewport, //会变化
  62135. dragViewport: this.hoverViewport, //不变
  62136. };
  62137. if (args) {
  62138. for (let key of Object.keys(args)) {
  62139. this.drag[key] = args[key];
  62140. }
  62141. }
  62142. if(object){
  62143. object.dispatchEvent($.extend(
  62144. this.getEventDesc(),
  62145. {
  62146. type: 'startDragging'
  62147. }
  62148. ));
  62149. }
  62150. }
  62151. /* getMousePointCloudIntersection (mouse) {
  62152. return Utils.getMousePointCloudIntersection(
  62153. this.mouse,
  62154. this.scene.getActiveCamera(),
  62155. this.viewer,
  62156. this.scene.pointclouds);
  62157. } */
  62158. toggleSelection (object) {
  62159. let oldSelection = this.selection;
  62160. let index = this.selection.indexOf(object);
  62161. if (index === -1) {
  62162. this.selection.push(object);
  62163. object.dispatchEvent({
  62164. type: 'select'
  62165. });
  62166. } else {
  62167. this.selection.splice(index, 1);
  62168. object.dispatchEvent({
  62169. type: 'deselect'
  62170. });
  62171. }
  62172. this.dispatchEvent({
  62173. type: 'selection_changed',
  62174. oldSelection: oldSelection,
  62175. selection: this.selection
  62176. });
  62177. viewer.dispatchEvent('content_changed');
  62178. }
  62179. deselect(object){
  62180. let oldSelection = this.selection;
  62181. let index = this.selection.indexOf(object);
  62182. if(index >= 0){
  62183. this.selection.splice(index, 1);
  62184. object.dispatchEvent({
  62185. type: 'deselect'
  62186. });
  62187. this.dispatchEvent({
  62188. type: 'selection_changed',
  62189. oldSelection: oldSelection,
  62190. selection: this.selection
  62191. });
  62192. }
  62193. viewer.dispatchEvent('content_changed');
  62194. }
  62195. deselectAll () {
  62196. for (let object of this.selection) {
  62197. object.dispatchEvent({
  62198. type: 'deselect'
  62199. });
  62200. }
  62201. let oldSelection = this.selection;
  62202. if (this.selection.length > 0) {
  62203. this.selection = [];
  62204. this.dispatchEvent({
  62205. type: 'selection_changed',
  62206. oldSelection: oldSelection,
  62207. selection: this.selection
  62208. });
  62209. }
  62210. viewer.dispatchEvent('content_changed');
  62211. }
  62212. isSelected (object) {
  62213. let index = this.selection.indexOf(object);
  62214. return index !== -1;
  62215. }
  62216. registerInteractiveObject(object){
  62217. this.interactiveObjects.add(object);
  62218. }
  62219. removeInteractiveObject(object){
  62220. this.interactiveObjects.delete(object);
  62221. }
  62222. registerInteractiveScene (scene) {
  62223. let index = this.interactiveScenes.indexOf(scene);
  62224. if (index === -1) {
  62225. this.interactiveScenes.push(scene);
  62226. }
  62227. }
  62228. unregisterInteractiveScene (scene) {
  62229. let index = this.interactiveScenes.indexOf(scene);
  62230. if (index > -1) {
  62231. this.interactiveScenes.splice(index, 1);
  62232. }
  62233. }
  62234. getHoveredElement () {
  62235. let hoveredElements = this.getHoveredElements();
  62236. if (hoveredElements.length > 0) {
  62237. return hoveredElements[0];
  62238. } else {
  62239. return null;
  62240. }
  62241. }
  62242. getHoveredElements (interactables, dontCheckDis, raycaster) {
  62243. if(!interactables){
  62244. let scenes = this.hoverViewport.interactiveScenes || this.interactiveScenes.concat(this.scene);
  62245. let interactableListeners = ['mouseup', 'mousemove', 'mouseover', 'mouseleave', 'drag', 'drop', 'click', 'select', 'deselect'];
  62246. interactables = [];
  62247. for (let scene of scenes) {
  62248. scene.traverseVisible(node => {//检测加了侦听的object
  62249. if (node._listeners && node.visible && !this.blacklist.has(node) ) {
  62250. let hasInteractableListener = interactableListeners.filter((e) => {
  62251. return node._listeners[e] !== undefined;
  62252. }).length > 0;
  62253. if (hasInteractableListener) {
  62254. interactables.push(node);
  62255. }
  62256. }
  62257. });
  62258. }
  62259. }else interactables = interactables.filter(e=>e.visible);
  62260. let camera = this.hoverViewport.camera;
  62261. if(!raycaster){
  62262. let ray = Utils.mouseToRay(this.pointer, camera );
  62263. raycaster = new Raycaster();
  62264. raycaster.ray.set(ray.origin, ray.direction);
  62265. raycaster.camera = camera; //add
  62266. }
  62267. if(camera.type == "OrthographicCamera"){//使无论多远,threshold区域都是一样宽的
  62268. raycaster.params.Line.threshold = 20/camera.zoom;
  62269. }else {
  62270. raycaster.params.Line.threshold = 0.04; //相对长度
  62271. }
  62272. raycaster.params.Line2 = {threshold : browser.isMobile()?100:20 }; //拓宽的lineWidth
  62273. //raycaster.layers.enableAll()//add
  62274. Potree.Utils.setCameraLayers(raycaster, //设置能识别到的layers(如空间模型里只有mapViewer能识别到marker)
  62275. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  62276. this.hoverViewport && this.hoverViewport.extraEnableLayers
  62277. );
  62278. //this.hoverViewport.beforeRender && this.hoverViewport.beforeRender()
  62279. viewer.dispatchEvent( {type:'raycaster', viewport: this.hoverViewport, raycaster, viewer:this.viewer, interactables });//add
  62280. let intersections = raycaster.intersectObjects(interactables , true, null, true); //原本是false 检测不到children
  62281. let intersectionsCopy = intersections.slice();
  62282. if(this.intersect && this.intersect.distance != void 0 && !dontCheckDis){//add
  62283. intersections = intersections.filter(e=>{
  62284. let material = e.object.material;
  62285. return e.object.pickDontCheckDis || ( material.depthTest == false || material.depthWrite == false) && !material.realUseDepth //!material.depthTestWhenPick
  62286. || ( material.useDepth ? e.distance < this.intersect.distance + material.uniforms.clipDistance.value : e.distance < this.intersect.distance )
  62287. //maxClipFactor是否需要考虑?
  62288. });
  62289. }
  62290. intersections = intersections.map(e=>{//add 转化为interactables
  62291. var object = e.object;
  62292. do{
  62293. if(interactables.includes(object)) {
  62294. e.oriObject = e.object;
  62295. e.object = object;
  62296. break
  62297. }
  62298. object = object.parent;
  62299. }while(object)
  62300. return e
  62301. });
  62302. //add for测量线,在检测到sphere时优先选中sphere而非线
  62303. //intersections = intersections.sort(function(a,b){return b.object.renderOrder-a.object.renderOrder}) // 降序
  62304. intersections = intersections.sort(function(a,b){
  62305. let order2 = b.object.pickOrder || 0;
  62306. let order1 = a.object.pickOrder || 0;
  62307. return order2-order1
  62308. }); // 降序
  62309. //console.log('getHoveredElement ', intersections)
  62310. return intersections;
  62311. }
  62312. /* setScene (scene) {
  62313. this.deselectAll();
  62314. this.scene = scene;
  62315. } */
  62316. update (delta) {
  62317. }
  62318. /*getNormalizedDrag () {
  62319. if (!this.drag) {
  62320. return new THREE.Vector2(0, 0);
  62321. }
  62322. let diff = new THREE.Vector2().subVectors(this.drag.end, this.drag.start);
  62323. diff.x = diff.x / this.domElement.clientWidth;
  62324. diff.y = diff.y / this.domElement.clientHeight;
  62325. return diff;
  62326. }
  62327. getNormalizedLastDrag () {
  62328. if (!this.drag) {
  62329. return new THREE.Vector2(0, 0);
  62330. }
  62331. let mouseDelta = this.drag.mouseDelta.clone();
  62332. mouseDelta.x = mouseDelta.x / this.domElement.clientWidth;
  62333. mouseDelta.y = mouseDelta.y / this.domElement.clientHeight;
  62334. return mouseDelta;
  62335. } */
  62336. getMouseDirection(pointer) {//add
  62337. pointer = pointer || this.pointer;
  62338. let camera = this.hoverViewport.camera;
  62339. var t = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  62340. i = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  62341. return {origin: t, direction:i.clone().sub(t).normalize() }
  62342. }
  62343. }
  62344. class ViewerBase extends EventDispatcher{
  62345. constructor(domElement, args = {}){
  62346. super();
  62347. this.name = args.name;
  62348. this.renderArea = domElement;
  62349. this.oldResolution = new Vector2();
  62350. this.oldResolution2 = new Vector2();
  62351. this.screenSizeInfo = {
  62352. W:0, H:0, pixelRatio:1 , windowWidth:0, windowHeight:0
  62353. };
  62354. this.initContext(args);
  62355. this.addEventListener('content_changed', ()=>{//画面改变,需要渲染
  62356. this.needRender = true;
  62357. //console.log('needRender')
  62358. });
  62359. }
  62360. initContext(args){
  62361. //console.log(`initializing three.js ${THREE.REVISION}`);
  62362. let width = this.renderArea.clientWidth;
  62363. let height = this.renderArea.clientHeight;
  62364. let contextAttributes = {
  62365. alpha: true,//支持透明
  62366. depth: true,
  62367. stencil: false,
  62368. antialias: !!args.antialias,
  62369. preserveDrawingBuffer: args.preserveDrawingBuffer || false ,
  62370. powerPreference: "high-performance",
  62371. };
  62372. let canvas = document.createElement("canvas");
  62373. let context = canvas.getContext('webgl', contextAttributes ); //不用webgl2是因为有的写法在webgl2不支持 如gl_FragDepthEXT
  62374. this.renderer = new WebGLRenderer({
  62375. premultipliedAlpha: false,
  62376. canvas: canvas,
  62377. context: context,
  62378. });
  62379. this.renderer.sortObjects = true; //原先false 打开了renderOrder才奏效
  62380. //this.renderer.setSize(width, height);
  62381. this.renderer.autoClear = args.autoClear || false;
  62382. //args.clearColor = args.clearColor || '#aa0033'
  62383. args.clearColor && this.renderer.setClearColor(args.clearColor);
  62384. this.renderArea.appendChild(this.renderer.domElement);
  62385. this.renderer.domElement.tabIndex = '2222';
  62386. this.renderer.domElement.style.position = 'absolute';
  62387. this.renderer.domElement.addEventListener('mousedown', () => {
  62388. this.renderer.domElement.focus();
  62389. });
  62390. //this.renderer.domElement.focus();
  62391. // NOTE: If extension errors occur, pass the string into this.renderer.extensions.get(x) before enabling
  62392. // enable frag_depth extension for the interpolation shader, if available
  62393. let gl = this.renderer.getContext();
  62394. gl.getExtension('EXT_frag_depth');
  62395. gl.getExtension('WEBGL_depth_texture');
  62396. gl.getExtension('WEBGL_color_buffer_float'); // Enable explicitly for more portability, EXT_color_buffer_float is the proper name in WebGL 2
  62397. if(gl.createVertexArray == null){
  62398. let extVAO = gl.getExtension('OES_vertex_array_object');
  62399. if(!extVAO){
  62400. throw new Error("OES_vertex_array_object extension not supported");
  62401. }
  62402. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  62403. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  62404. }
  62405. /* let oldClear = gl.clear;
  62406. gl.clear = (bits)=>{
  62407. console.error('clear')
  62408. }
  62409. */
  62410. }
  62411. updateScreenSize(o={}) { //有可能需要让viewport来判断,当窗口大小不变但viewport大小变时
  62412. var render = false, ratio, w, h;
  62413. //记录应当render的大小
  62414. if (o.width != void 0 && o.height != void 0) {
  62415. w = o.width;
  62416. h = o.height;
  62417. render = true;
  62418. ratio = 1;
  62419. }else {
  62420. w = this.renderArea.clientWidth;
  62421. h = this.renderArea.clientHeight;
  62422. if(w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || o.forceUpdateSize || this.screenSizeInfo.pixelRatio != window.devicePixelRatio){
  62423. this.screenSizeInfo.W = w;
  62424. this.screenSizeInfo.H = h;
  62425. render = true;
  62426. this.screenSizeInfo.pixelRatio = window.devicePixelRatio; //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变
  62427. //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio)
  62428. ratio = window.devicePixelRatio;
  62429. }
  62430. }
  62431. if (render) {
  62432. this.setSize(w, h, ratio, o.forTarget );
  62433. }
  62434. }
  62435. setSize(width, height, devicePixelRatio, onlyForTarget){
  62436. //console.log('setSize', width)
  62437. if(!onlyForTarget){//onlyForTarget表示不更改当前renderer,只是为了rendertarget才要改变viewport
  62438. this.renderer.setPixelRatio(devicePixelRatio);
  62439. this.renderer.setSize(width, height ); // resize之后会自动clear(似乎因为setScissor ),所以一定要立刻绘制,所以setSize要在cameraChanged、update之前
  62440. }
  62441. //this.composer && this.composer.setSize(width, height);
  62442. if(this.viewports){
  62443. this.viewports.forEach((view,i)=>{
  62444. if(!view.active)return
  62445. var width_ = width * view.width;
  62446. var height_ = height * view.height;
  62447. view.setResolution(Math.ceil(width_), Math.ceil(height_), width, height ); //本来应该是floor,但是这样奇数时会少一个像素,导致向左移一个像素且宽度少1。现在则多绘制1个像素,超出的1个像素应该不会绘制出来(但不知道其他地方是否有偏差,比如pick时)
  62448. if(height_ == 0)return //avoid NAN
  62449. let aspect = width_ / height_; //camera的参数精确些,不用视口的归整的resolution像素值,否则hasChange无法为true, 导致canvasResize了但map没update从而闪烁
  62450. view.camera.aspect = aspect;
  62451. if(view.camera.type == "OrthographicCamera"){
  62452. /* //不改宽度 同4dkk
  62453. var heightHalf = view.camera.right / aspect
  62454. view.camera.top = heightHalf
  62455. view.camera.bottom = -heightHalf */
  62456. //高宽都改 使大小不随视口大小改变 navvis (直接和视口大小一致即可,通过zoom来定大小)
  62457. view.camera.left = -width_/2;
  62458. view.camera.right = width_/2;
  62459. view.camera.bottom = -height_/2;
  62460. view.camera.top = height_/2;
  62461. }else {
  62462. }
  62463. view.camera.updateProjectionMatrix();
  62464. });
  62465. }
  62466. if(!onlyForTarget){//因为onlyForTarget不传递devicePixelRatio所以不发送了
  62467. this.ifEmitResize({viewport:this.viewports[0], deviceRatio:devicePixelRatio});
  62468. }
  62469. }
  62470. ifEmitResize(e){//切换viewport渲染时, 若这些viewport大小不同就发送一次, 通知一些材质更新resolution。
  62471. //console.log('ifEmitResize',e.viewport.name,e.viewport.resolution2 )
  62472. if(!e.viewport.resolution.equals(this.oldResolution)||!e.viewport.resolution2.equals(this.oldResolution2)){
  62473. this.dispatchEvent($.extend(e, {type:'resize'}));
  62474. this.oldResolution.copy(e.viewport.resolution);
  62475. this.oldResolution2.copy(e.viewport.resolution2);
  62476. }
  62477. }
  62478. cameraChanged() {//判断相机是否改变
  62479. var changed = false;
  62480. /* if(this.needRender){
  62481. this.needRender = false
  62482. return true
  62483. } */
  62484. for(let i=0,j=this.viewports.length;i<j;i++){
  62485. let viewport = this.viewports[i];
  62486. let changeInfo = viewport.cameraChanged();
  62487. if(changeInfo.changed){
  62488. changed = true;
  62489. //if(!this.changeTime ||this.changeTime<100){
  62490. this.dispatchEvent({
  62491. type: "camera_changed",
  62492. camera: viewport.camera,
  62493. viewport ,
  62494. changeInfo
  62495. });
  62496. //this.changeTime = (this.changeTime || 0) +1
  62497. //}
  62498. viewport.needRender = true; //直接写这咯
  62499. if(changeInfo.resolutionChanged){
  62500. this.ifEmitResize({viewport}); //for map
  62501. }
  62502. }
  62503. }
  62504. return changed
  62505. }
  62506. makeScreenshot( size, viewports, compressRatio){//暂时不要指定viewports渲染,但也可以
  62507. let {width, height} = size;
  62508. /* let oldBudget = Potree.pointBudget;
  62509. Potree.pointBudget = Math.max(10 * 1000 * 1000, 2 * oldBudget);
  62510. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, size );
  62511. Potree.pointBudget = oldBudget;
  62512. this.dispatchEvent({ //resize everything such as lines targets
  62513. type: 'resize',
  62514. resolution: new THREE.Vector2(width,height),
  62515. });*/
  62516. let target = new WebGLRenderTarget(width, height, {
  62517. format: RGBAFormat,
  62518. });
  62519. this.setSize(width, height,1,true);
  62520. this.render({
  62521. target ,
  62522. //camera ,
  62523. viewports: viewports || this.viewports,
  62524. screenshot : true,
  62525. width ,
  62526. height,
  62527. resize :true //需要resize
  62528. });
  62529. let dataUrl = Potree.Utils.renderTargetToDataUrl(target, width, height, this.renderer, compressRatio);
  62530. /* let pixelCount = width * height;
  62531. let buffer = new Uint8Array(4 * pixelCount);
  62532. this.renderer.readRenderTargetPixels(target, 0, 0, width, height, buffer);
  62533. let dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio) */
  62534. target.dispose();
  62535. //resize back
  62536. //this.updateScreenSize({forceUpdateSize:true})
  62537. return {
  62538. width,
  62539. height,
  62540. dataUrl
  62541. };
  62542. }
  62543. }
  62544. class Viewport extends EventDispatcher{
  62545. constructor( view, camera, prop={}){//目前不支持换camera
  62546. super();
  62547. this.left = prop.left;
  62548. this.bottom = prop.bottom;
  62549. this.width = prop.width;
  62550. this.height = prop.height;
  62551. this.name = prop.name;
  62552. this.view = view;
  62553. this.camera = camera;
  62554. this.active = true;
  62555. this.unableChangePos = false;
  62556. this.noPointcloud;
  62557. //this.keys = [...] firstPersonCtl....
  62558. this.resolution = new Vector2;
  62559. this.resolution2 = new Vector2;
  62560. this.offset = new Vector2; //viewportOffset 范围从0-整个画布的像素
  62561. this.extraEnableLayers = prop.extraEnableLayers || [];//额外可展示的层
  62562. this.cameraLayers = prop.cameraLayers;
  62563. this.pixelRatio = prop.pixelRatio; //如果规定pixelRatio的话要传,这样就覆盖devicePicelRatio, 如magnifier
  62564. }
  62565. clone(){
  62566. return Common$1.CloneClassObject(this)
  62567. }
  62568. getMoveSpeed(){
  62569. return this.moveSpeed
  62570. }
  62571. setMoveSpeed(e){
  62572. this.moveSpeed = e;
  62573. }
  62574. layersAdd(name){
  62575. this.extraEnableLayers.includes(name) || this.extraEnableLayers.push(name);
  62576. }
  62577. layersRemove(name){
  62578. let index = this.extraEnableLayers.indexOf(name);
  62579. if(index > -1){
  62580. this.extraEnableLayers.splice(index, 1);
  62581. }
  62582. }
  62583. cameraChanged() {
  62584. var copy = ()=>{
  62585. this.previousState = {
  62586. projectionMatrix: this.camera.projectionMatrix.clone(),//worldMatrix在this.control时归零了所以不用了吧,用position和qua也一样
  62587. position: this.camera.position.clone(),
  62588. quaternion: this.camera.quaternion.clone(),
  62589. active:this.active,
  62590. resolution:this.resolution.clone(),
  62591. resolution2:this.resolution2.clone(), //有时clientWidth没变但是ratio缩放了
  62592. };
  62593. };
  62594. let projectionChanged = true, positionChanged = true, quaternionChanged = true, activeChanged = true, resolutionChanged = true;
  62595. let getChanged = ()=>{
  62596. return {
  62597. projectionChanged,positionChanged,quaternionChanged, activeChanged, resolutionChanged,
  62598. changed:projectionChanged || positionChanged || quaternionChanged || activeChanged || resolutionChanged
  62599. }
  62600. };
  62601. if (this.previousState){
  62602. projectionChanged = !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix);
  62603. positionChanged = !this.camera.position.equals(this.previousState.position);
  62604. quaternionChanged = !this.camera.quaternion.equals(this.previousState.quaternion);
  62605. activeChanged = this.active != this.previousState.active;
  62606. resolutionChanged = !this.resolution.equals(this.previousState.resolution) || !this.resolution2.equals(this.previousState.resolution2);
  62607. }
  62608. copy();
  62609. return getChanged()
  62610. }
  62611. setResolution(w,h, wholeW=0, wholeH=0){
  62612. this.resolution.set(w,h);//是client的width height
  62613. this.resolution2.copy(this.resolution).multiplyScalar(this.pixelRatio || window.devicePixelRatio);
  62614. this.offset.set(wholeW,wholeH).multiply(new Vector2(this.left,this.bottom));//.multiplyScalar(window.devicePixelRatio)
  62615. this.dispatchEvent({type:'resize'});
  62616. }
  62617. }
  62618. const 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;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\n";
  62619. const prefixFragment ="precision highp float;\nprecision highp int;\n\nuniform mat4 viewMatrix;\nuniform vec3 cameraPosition;\n";
  62620. let shader = {
  62621. uniforms: {
  62622. opacity: {
  62623. type: "f",
  62624. // value: 1
  62625. },
  62626. progress: {
  62627. type: "f",
  62628. value: 0
  62629. },
  62630. pano0Map: {
  62631. type: "t",
  62632. value: null
  62633. },
  62634. pano1Map: {
  62635. type: "t",
  62636. value: null
  62637. },
  62638. depthMap0: {
  62639. type: "t",
  62640. value: null
  62641. },
  62642. depthMap1: {
  62643. type: "t",
  62644. value: null
  62645. },
  62646. pano0Position: {
  62647. type: "v3",
  62648. value: new Vector3
  62649. },
  62650. pano0Matrix: {
  62651. type: "m4",
  62652. value: new Matrix4
  62653. },
  62654. pano1Position: {
  62655. type: "v3",
  62656. value: new Vector3
  62657. },
  62658. pano1Matrix: {
  62659. type: "m4",
  62660. value: new Matrix4
  62661. },
  62662. /* pano1Matrix2: {
  62663. type: "m4",
  62664. value: new THREE.Matrix4
  62665. },
  62666. */
  62667. inverseProjectionMatrix: {
  62668. value: new Matrix4
  62669. },
  62670. /* projectionMatrix:{//需要再写一遍吗
  62671. value: new THREE.Matrix4
  62672. }, */
  62673. viewport: {
  62674. value: new Vector4
  62675. },
  62676. //如 {x: 0, y: 0, z: 428, w: 969} xy应该是offset, zw是宽高
  62677. cameraHeight0: {
  62678. type: "f",
  62679. value: 1
  62680. },
  62681. cameraHeight1: {
  62682. type: "f",
  62683. value: 1
  62684. },
  62685. ceilHeight0:{
  62686. type: "f",
  62687. value: 2
  62688. },
  62689. ceilHeight1:{
  62690. type: "f",
  62691. value: 2
  62692. },
  62693. },
  62694. vertexShader: prefixVertex + `
  62695. uniform vec3 pano0Position;
  62696. uniform mat4 pano0Matrix;
  62697. uniform vec3 pano1Position;
  62698. uniform mat4 pano1Matrix;
  62699. //uniform mat4 pano1Matrix2;
  62700. varying vec2 vUv;
  62701. varying vec3 vWorldPosition0;
  62702. varying vec3 vWorldPosition1;
  62703. varying vec3 vWorldPosition12;
  62704. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  62705. {
  62706. float y = direction.y;
  62707. direction.y = direction.z;
  62708. direction.z = -y;
  62709. return direction;
  62710. }
  62711. void main() {
  62712. vUv = uv;
  62713. vec4 worldPosition = modelMatrix * vec4(position, 1.0);
  62714. vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;
  62715. vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;
  62716. vWorldPosition0.x *= -1.0;
  62717. vWorldPosition0 = transformAxis(vWorldPosition0);
  62718. vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;
  62719. vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;
  62720. vWorldPosition1.x *= -1.0;
  62721. vWorldPosition1 = transformAxis(vWorldPosition1);
  62722. /*
  62723. vec3 positionLocalToPanoCenter12 = worldPosition.xyz - pano1Position;
  62724. vWorldPosition12 = (vec4(positionLocalToPanoCenter12, 1.0) * pano1Matrix2).xyz;
  62725. vWorldPosition12.x *= -1.0;
  62726. vWorldPosition12 = transformAxis(vWorldPosition12);
  62727. */
  62728. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  62729. }
  62730. `,
  62731. fragmentShader: prefixFragment + `
  62732. #extension GL_EXT_frag_depth : enable
  62733. #define PI 3.141592653
  62734. uniform float modelAlpha;
  62735. uniform float opacity;
  62736. uniform float progress;
  62737. uniform int blackout;
  62738. uniform vec3 pano0Position;
  62739. uniform vec3 pano1Position;
  62740. uniform float maxDistance;
  62741. uniform float minDistance;
  62742. uniform float minOpa;
  62743. /* uniform sampler2D pano0Map;
  62744. uniform sampler2D pano1Map; */
  62745. uniform samplerCube pano0Map;
  62746. uniform samplerCube pano1Map;
  62747. varying vec2 vUv;
  62748. varying vec3 vWorldPosition0;
  62749. varying vec3 vWorldPosition1;
  62750. //varying vec3 vWorldPosition12;
  62751. /* vec2 getSamplerCoord( vec3 direction )
  62752. {
  62753. direction = normalize(direction);
  62754. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  62755. float ty=acos(direction.z)/PI;
  62756. return vec2(tx,ty);
  62757. } */
  62758. vec2 getSamplerCoord2( vec3 direction )
  62759. {
  62760. direction = normalize(direction);
  62761. float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;
  62762. float ty=acos(direction.y)/PI;
  62763. return vec2(tx,ty);
  62764. }
  62765. #if defined(GL_EXT_frag_depth) && defined(hasDepthTex)
  62766. uniform sampler2D depthMap0;
  62767. uniform sampler2D depthMap1;
  62768. uniform mat4 inverseProjectionMatrix;
  62769. uniform mat4 projectionMatrix;
  62770. uniform vec4 viewport;
  62771. uniform float cameraHeight0;
  62772. uniform float cameraHeight1;
  62773. uniform float ceilHeight0;
  62774. uniform float ceilHeight1;
  62775. vec2 getDepth(vec3 dir, sampler2D depthMap, float heightDown, float heightUp, vec4 eyePos){
  62776. vec2 depthValue = vec2(0.0, 0.0);
  62777. vec2 uv2 = getSamplerCoord2( dir.xyz); //暂时只用基于目标漫游点的方向
  62778. uv2.x -= 0.25; //全景图和Cube的水平采样起始坐标相差90度,这里矫正 0.25 个采样偏移
  62779. vec4 depth = texture2D(depthMap, uv2);
  62780. //float distance = depth.r + 256. * (depth.g + 256. * depth.b);
  62781. //distance *= 255. * .001; // distance is now in meters
  62782. //更改
  62783. float distance = (depth.g + depth.r / 256.) * 255.; //为什么要乘以255
  62784. if(distance == 0.0){//漫游点底部识别不到的区域,给一个地板高度
  62785. if(uv2.y < depthTexUVyLimit) distance = heightUp / dir.y;
  62786. else if(uv2.y > 1.0 - depthTexUVyLimit) distance = heightDown / -dir.y;
  62787. else distance = 100000.0;//给个超级远的值
  62788. }
  62789. if(distance == 0.0)distance = 100000.0;//给个超级远的值
  62790. depthValue.x = distance;
  62791. // return r[1] + r[0] / 256
  62792. distance += .1; // add a safety margin
  62793. vec4 eyePos2 = vec4(normalize(eyePos.xyz) * distance, 1.);
  62794. vec4 clipPos2 = projectionMatrix * eyePos2;
  62795. vec4 ndcPos2 = clipPos2 * 1. / clipPos2.w;
  62796. depthValue.y = 0.5 * ((gl_DepthRange.far - gl_DepthRange.near) * ndcPos2.z
  62797. + gl_DepthRange.near + gl_DepthRange.far);
  62798. return depthValue;
  62799. }
  62800. //注:未加载好的话,depth为0,导致第一次漫游过去的时候许多mesh会立刻被遮挡,所以要确保加载完
  62801. #endif
  62802. void main()
  62803. {
  62804. vec3 vWorldPosition0N = normalize(vWorldPosition0);
  62805. vec3 vWorldPosition1N = normalize(vWorldPosition1);
  62806. vec4 colorFromPano0 = vec4(0.0,0.0,0.0,0.0);
  62807. #if defined(usePanoMap0)
  62808. //即progress < 1.0 通常是1
  62809. colorFromPano0=textureCube(pano0Map,vWorldPosition0N.xyz);
  62810. #endif
  62811. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1N.xyz);
  62812. gl_FragColor=mix(colorFromPano0,colorFromPano1,progress);
  62813. //深度图修改深度
  62814. #if defined(GL_EXT_frag_depth) && defined(hasDepthTex)
  62815. vec4 ndcPos;
  62816. ndcPos.xy = ((2.0 * gl_FragCoord.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1.;
  62817. ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /
  62818. (gl_DepthRange.far - gl_DepthRange.near);
  62819. ndcPos.w = 1.0;
  62820. vec4 clipPos = ndcPos / gl_FragCoord.w;
  62821. vec4 eyePos = inverseProjectionMatrix * clipPos;
  62822. vec2 depth0 = vec2(0.0,0.0);
  62823. #if defined(usePanoMap0)
  62824. depth0 = getDepth(vWorldPosition0N, depthMap0, cameraHeight0, ceilHeight0, eyePos);
  62825. #endif
  62826. vec2 depth1 = getDepth(vWorldPosition1N, depthMap1, cameraHeight1, ceilHeight1, eyePos);
  62827. gl_FragDepthEXT = mix(depth0.y,depth1.y,progress);
  62828. gl_FragDepthEXT = clamp(gl_FragDepthEXT, 0.0, 1.0); //防止部分手机出现黑块。ios 16 。 因为我给的超远值超出范围
  62829. #endif
  62830. }
  62831. `
  62832. };
  62833. //注:gl_FragDepthEXT 修改了确实能像真实mesh那样遮挡住在后面的物体。但是为过渡时不能直接像有模型那样,和角度有关。
  62834. class ModelTextureMaterial extends RawShaderMaterial {
  62835. constructor( ){
  62836. let defines = {depthTexUVyLimit: Potree.config.depthTexUVyLimit};
  62837. super({
  62838. fragmentShader: shader.fragmentShader,
  62839. vertexShader: shader.vertexShader,
  62840. uniforms: UniformsUtils.clone(shader.uniforms),
  62841. side:DoubleSide,
  62842. name: "ModelTextureMaterial",
  62843. defines
  62844. });
  62845. let setSize = (e)=>{
  62846. let viewport = e.viewport;
  62847. //let viewportOffset = viewport.offset || new Vector2()
  62848. let resolution = viewport.resolution2;
  62849. //this.uniforms.viewport.value.set(viewportOffset.x, viewportOffset.y, resolution.x, resolution.y)
  62850. this.uniforms.viewport.value.set(0,0, resolution.x, resolution.y);// xy是在viewport中的left和bottom,和整个窗口没有关系,所以不是viewportOffset。几乎都是0,0
  62851. };
  62852. let viewport = viewer.mainViewport;
  62853. setSize({viewport});
  62854. viewer.addEventListener('resize',(e)=>{
  62855. if(e.viewport.name != "MainView")return
  62856. setSize(e);
  62857. });
  62858. //var supportExtDepth = !!Features.EXT_DEPTH.isSupported()
  62859. {
  62860. //add
  62861. viewer.addEventListener('camera_changed', (e)=>{
  62862. if(e.viewport.name != "MainView")return
  62863. //this.uniforms.projectionMatrix.value.copy(e.camera.projectionMatrix)
  62864. e.camera && this.uniforms.inverseProjectionMatrix.value.copy(e.camera.projectionMatrixInverse);
  62865. });
  62866. }
  62867. let progress = 0;
  62868. Object.defineProperty(this.uniforms.progress, 'value', {
  62869. get: function () {
  62870. return progress
  62871. },
  62872. set: e => {
  62873. if (e < 1) {
  62874. if (!('usePanoMap0' in this.defines)) {
  62875. this.defines.usePanoMap0 = '';
  62876. this.needsUpdate = true;
  62877. }
  62878. } else {
  62879. if ('usePanoMap0' in this.defines) {
  62880. delete this.defines.usePanoMap0;
  62881. this.needsUpdate = true;
  62882. }
  62883. }
  62884. progress = e;
  62885. },
  62886. });
  62887. //-------------------------------------
  62888. }
  62889. /**
  62890. *
  62891. * @param {Panorama} pano0
  62892. * @param {Panorama} pano1
  62893. * @param {boolean} flag
  62894. 更新全景图的材质uniforms
  62895. */
  62896. setProjectedPanos(pano0, pano1, progressValue ){
  62897. progressValue!=void 0 && (this.uniforms.progress.value = progressValue);
  62898. //pano0.ensureSkyboxReadyForRender();
  62899. if(pano0){
  62900. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();//pano0.texture
  62901. this.uniforms.pano0Position.value.copy(pano0.position);
  62902. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix/* pano0.mesh.matrixWorld */ );
  62903. //pano1.ensureSkyboxReadyForRender();
  62904. }
  62905. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();//pano1.texture;
  62906. this.uniforms.pano1Position.value.copy(pano1.position);
  62907. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix /* pano1.mesh.matrixWorld */ );
  62908. this.pano0 = pano0;
  62909. this.pano1 = pano1;
  62910. this.updateDepthTex(pano0);
  62911. this.updateDepthTex(pano1);
  62912. //console.log('setProjectedPanos', pano0&&pano0.id, pano1&&pano1.id)
  62913. this.needsUpdate = true;
  62914. }
  62915. updateDepthTex(pano, extra){
  62916. if( !Potree.settings.useDepthTex || !pano || !pano.depthTex || pano!=this.pano0 && pano!=this.pano1)return
  62917. //console.log('updateDepthTex', pano.id, this.pano0 && this.pano0.id, this.pano1 && this.pano1.id)
  62918. if(this.pano0){
  62919. this.uniforms.depthMap0.value = this.pano0.entered ? this.pano0.depthTex : null; //dispose了就不要赋值否则dispose会失败
  62920. this.uniforms.cameraHeight0.value = this.pano0.floorPosition.distanceTo(this.pano0.position);
  62921. this.uniforms.ceilHeight0.value = this.pano0.getCeilHeight() - this.pano0.position.z;
  62922. }
  62923. if(this.pano1){
  62924. this.uniforms.depthMap1.value = this.pano1.depthTex; //pano1还没entered时也需要,可能在飞入
  62925. this.uniforms.cameraHeight1.value = this.pano1.floorPosition.distanceTo(this.pano1.position);
  62926. this.uniforms.ceilHeight1.value = this.pano1.getCeilHeight() - this.pano1.position.z;
  62927. }
  62928. this.updateDepthTexEnable();
  62929. }
  62930. updateDepthTexEnable(){
  62931. let hasDepthTex = this.pano0 && this.pano1 && this.pano0.pointcloud.hasDepthTex && this.pano1.pointcloud.hasDepthTex; //暂时不知道一个有图一个没图怎么写所以
  62932. Potree.Utils.addOrRemoveDefine(this, 'hasDepthTex', hasDepthTex?'add':'remove' );
  62933. }
  62934. /* EnableDepthTex(){//开启DepthTex
  62935. if(this.defines['hasDepthTex']){
  62936. return
  62937. }
  62938. this.defines['hasDepthTex'] = ''
  62939. this.needsUpdate = true;
  62940. } */
  62941. }
  62942. let GLCubeFaces$1 = Potree.defines.GLCubeFaces;
  62943. var TileUtils = {};
  62944. TileUtils.TILE_SIZE = 512,
  62945. TileUtils.FACES_PER_PANO = 6,
  62946. TileUtils.LocationOnTile = {
  62947. Center: 0,
  62948. UpperLeft: 1,
  62949. UpperRight: 2,
  62950. LowerRight: 3,
  62951. LowerLeft: 4
  62952. },
  62953. /*
  62954. * 获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的指定位置)。spherical通过先求uv,再直接得到dir
  62955. * @param {*} size 面分辨率
  62956. * @param {*} cubeFace 所在面
  62957. * @param {*} Center 在tile上的目标位置,默认为中心,其他位置就是四个顶点
  62958. * @param {*} c 似乎是在tile的缩进百分比,根据所在面的不同,分别向不同方向缩进,但都是向tile的中心
  62959. * @param {*} dir 所求方向
  62960. */
  62961. TileUtils.getTileVector = function() {//获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的中心)
  62962. return function(size, tileSize, cubeFace, tileX, tileY, Center, c, dir) {//c似乎是缩进百分比
  62963. Center = Center || TileUtils.LocationOnTile.Center;
  62964. //假设该cube边长为2:
  62965. var u = size / tileSize
  62966. , d = tileX / u;
  62967. tileY = -tileY + (u - 1);
  62968. var p = tileY / u
  62969. , f = tileSize / size
  62970. , g = 2 * f //一个tile的宽度 (乘以2是因为cube边长是2)
  62971. , m = g / 2
  62972. , v = 2 * d - 1 + m
  62973. , A = 2 * p - 1 + m;
  62974. switch (Center) {//计算在tile中指定位置带来的偏移
  62975. case TileUtils.LocationOnTile.UpperLeft: //1
  62976. v -= m,
  62977. A += m,
  62978. v += c * g; //似乎是向内缩进
  62979. break;
  62980. case TileUtils.LocationOnTile.UpperRight:
  62981. v += m,
  62982. A += m,
  62983. A -= c * g;
  62984. break;
  62985. case TileUtils.LocationOnTile.LowerRight:
  62986. v += m,
  62987. A -= m,
  62988. v -= c * g;
  62989. break;
  62990. case TileUtils.LocationOnTile.LowerLeft:
  62991. v -= m,
  62992. A -= m,
  62993. A += c * g;
  62994. break;
  62995. case TileUtils.LocationOnTile.Center: //0
  62996. }
  62997. switch (cubeFace) {
  62998. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  62999. MathLight.setVector(dir, -1, A, -v);
  63000. break;
  63001. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  63002. MathLight.setVector(dir, 1, A, v);
  63003. break;
  63004. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y: //顶面
  63005. MathLight.setVector(dir, -v, 1, -A);
  63006. break;
  63007. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  63008. MathLight.setVector(dir, -v, -1, A);
  63009. break;
  63010. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  63011. MathLight.setVector(dir, -v, A, 1);
  63012. break;
  63013. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  63014. MathLight.setVector(dir, v, A, -1);
  63015. }
  63016. MathLight.normalize(dir);
  63017. }
  63018. }(),
  63019. /*
  63020. * 获取该tile在第几个面(简易装载法)
  63021. */
  63022. TileUtils.getFaceForTile = function(size, index) {//获取该tile在第几个面
  63023. var tileSize = TileUtils.TILE_SIZE;
  63024. size < TileUtils.TILE_SIZE && (tileSize = size);
  63025. var n = Math.floor(size / tileSize)
  63026. , sum = n * n; //得每个面tile总数
  63027. return Math.floor(index / sum)
  63028. }
  63029. ,
  63030. TileUtils.getTileLocation = function(size, t, result) {
  63031. var tileSize = TileUtils.TILE_SIZE;
  63032. size < TileUtils.TILE_SIZE && (tileSize = size);
  63033. var r = TileUtils.getFaceForTile(size, t)
  63034. , a = Math.floor(size / tileSize)
  63035. , s = a * a
  63036. , l = t - r * s;
  63037. result.tileX = l % a;
  63038. result.tileY = Math.floor(l / a);
  63039. result.face = r;
  63040. result.faceTileIndex = l;
  63041. return result
  63042. }
  63043. ,
  63044. /*
  63045. * 求size分辨率需要多少张tile
  63046. */
  63047. TileUtils.getTileCountForSize = function(e) {
  63048. if (e <= TileUtils.TILE_SIZE)
  63049. return TileUtils.FACES_PER_PANO;
  63050. var t = Math.floor(e / TileUtils.TILE_SIZE)
  63051. , i = t * t
  63052. , n = i * TileUtils.FACES_PER_PANO;
  63053. return n
  63054. }
  63055. ,
  63056. TileUtils.getRelativeDirection = function() {
  63057. var e = new MathLight.Matrix4
  63058. , t = new MathLight.Quaternion;
  63059. return function(i, n) {//i是pano.quaternion, n是camera的direction
  63060. t.copy(i),
  63061. t.inverse(),
  63062. e.makeRotationFromQuaternion(t),
  63063. e.applyToVector3(n),
  63064. MathLight.normalize(n);
  63065. }
  63066. }(),
  63067. /*
  63068. * 根据方向寻找合适的tile加载
  63069. */
  63070. TileUtils.matchingTilesInDirection = function() {
  63071. var e = new MathLight.Vector3
  63072. , t = new MathLight.Vector3(0,0,-1)
  63073. , i = new MathLight.Quaternion
  63074. , n = function(e, t) {
  63075. e.push({
  63076. face: t.face,
  63077. faceTileIndex: t.faceTileIndex,
  63078. tileX: t.tileX,
  63079. tileY: t.tileY
  63080. });
  63081. }
  63082. , a = function() {
  63083. var e = {
  63084. face: -1,
  63085. faceTileIndex: -1,
  63086. tileX: -1,
  63087. tileY: -1
  63088. };
  63089. return function(size, i, r) {
  63090. for (var a = TileUtils.getTileCountForSize(size), s = 0, l = 0; l < a; l++)
  63091. TileUtils.getTileLocation(size, l, e),
  63092. i && !i(e) || (s++,
  63093. r && n(r, e));
  63094. return s
  63095. }
  63096. }();
  63097. return function(pano, size, dir, hFov, vFov, result) {
  63098. var d = size < TileUtils.TILE_SIZE ? size : TileUtils.TILE_SIZE;
  63099. //TileUtils.getTileCountForSize(size);
  63100. if (!hFov && !vFov)
  63101. return a(size, null, result);
  63102. var p = !!vFov;
  63103. vFov = vFov || hFov,
  63104. vFov = Math.max(0, Math.min(vFov, 360)),
  63105. hFov = Math.max(0, Math.min(hFov, 360)),
  63106. MathLight.copyVector(dir, e),
  63107. TileUtils.getRelativeDirection(pano.quaternion4dkk, e);
  63108. if(p){//如果有vFov hFov
  63109. i.setFromUnitVectors(e, t);
  63110. var f = function(e) {
  63111. return TileUtils.isTileWithinFrustum(size, d, e.face, e.tileX, e.tileY, i, hFov, vFov)//在视野中的
  63112. };
  63113. return a(size, f, result)
  63114. }
  63115. var g = function(t) {//如果仅有hFov
  63116. return TileUtils.isTileWithinFOV(size, d, t.face, t.tileX, t.tileY, e, hFov)
  63117. };
  63118. return a(size, g, result)
  63119. }
  63120. }(),
  63121. /*
  63122. * 是否在屏幕范围内
  63123. */
  63124. TileUtils.isTileWithinFrustum = function() {
  63125. var e = new MathLight.Vector3
  63126. , t = 1e-5;
  63127. return function(i, n, a, s, l, c, h, u) {
  63128. 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++){
  63129. TileUtils.getTileVector(i, n, m, s, l, b, 0, e),//get e // size, tileSize, cubeFace, tileX, tileY, Center, c, dir
  63130. MathLight.applyQuaternionToVector(c, e);
  63131. if (e.z >= -t)//似乎是在相机背面
  63132. I++;
  63133. else {
  63134. var w = -1 / e.z
  63135. , _ = e.x * w
  63136. , T = e.y * w;
  63137. T > d ? v++ : T < p && A++, //这四种似乎代表在这个画框之外,如在左、在上、在下、在右
  63138. _ > f ? y++ : _ < g && C++,
  63139. E++;
  63140. }
  63141. }
  63142. return A !== E && v !== E && y !== E && C !== E //如果有一项和E相等代表要么是在相机背面要么是tile的四个顶点都画在画布的同一边,所以肯定不在画布上
  63143. }
  63144. }(),
  63145. /*
  63146. * 是否在FOV范围内
  63147. */
  63148. TileUtils.isTileWithinFOV = function() {
  63149. var e = new MathLight.Vector3
  63150. , t = new MathLight.Vector3(0,1,0)
  63151. , i = new MathLight.Vector3(1,0,0);
  63152. return function(panoSize, tileSize, face, tileX, tileY, direction, fov) {//direction是作用了pano.quaternion的camera.direction
  63153. var d = TileUtils.mapFaceToCubemapFace(face);
  63154. MathLight.cross(direction, t, i); //get i 好像没用到
  63155. TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, TileUtils.LocationOnTile.Center, 0, e);
  63156. if (TileUtils.isWithinFOV(e, direction, fov, null))//先判断tile中心在不在FOV内
  63157. return !0;
  63158. for (var p = fov / 360, f = Math.floor(1 / p), g = 0, m = 0; m < f; m++) {
  63159. for (var v = TileUtils.LocationOnTile.UpperLeft; v <= TileUtils.LocationOnTile.LowerLeft; v++)
  63160. if (TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, v, g, e),
  63161. TileUtils.isWithinFOV(e, direction, fov, null))
  63162. return !0;
  63163. g += p; //可能是考虑到有可能tile比fov覆盖了fov(虽然一般不可能,除非fov特别小),所以将tile分成若干段,取tile中的点再检测下
  63164. }
  63165. return !1
  63166. }
  63167. }(),
  63168. TileUtils.isWithinFOV = function() {
  63169. var e = new MathLight.Vector3
  63170. , t = new MathLight.Vector3;
  63171. return function(dir, cameraDir, fov, a) {
  63172. if (MathLight.copyVector(dir, t),
  63173. a) {
  63174. MathLight.copyVector(a, e),
  63175. MathLight.normalize(e);
  63176. var s = MathLight.dot(e, dir);
  63177. e.x *= s,
  63178. e.y *= s,
  63179. e.z *= s,
  63180. MathLight.subVector(t, e);
  63181. }
  63182. var l = fov / 2 * MathLight.RADIANS_PER_DEGREE
  63183. , c = Math.cos(l)
  63184. , h = MathLight.dot(t, cameraDir);
  63185. return h >= c
  63186. }
  63187. }(),
  63188. TileUtils.mapFaceToCubemapFace = function() {
  63189. var e = {
  63190. 0: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  63191. 1: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  63192. 2: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  63193. 3: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
  63194. 4: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  63195. 5: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
  63196. };
  63197. return function(t) {
  63198. return e[t]
  63199. }
  63200. }();
  63201. let { PanoRendererEvents, PanoramaEvents, PanoSizeClass} = Potree.defines;
  63202. var texLoader$5 = new TextureLoader();
  63203. const markerOpacitys ={
  63204. default : 0.4,
  63205. hovered : 1,
  63206. };
  63207. const labelProp = {
  63208. sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  63209. backgroundColor:{r: 255, g: 255, b: 255, a: 0.4 },
  63210. textColor:{r: 0, g: 0, b: 0, a: 1 },
  63211. borderRadius: 15,
  63212. renderOrder:10,
  63213. useDepth:true,
  63214. clipDistance: 30, maxClipFactor:0.3, occlusionDistance:3,
  63215. };
  63216. const labelProp2 = {
  63217. //sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  63218. backgroundColor:{r: 255, g: 255, b: 255, a: 0 },
  63219. textColor:{r:255 , g: 255, b: 255, a: 1 },
  63220. textBorderColor:{r:30 , g:30, b: 30, a: 1 },
  63221. textBorderThick:3,
  63222. dontFixOrient:true,
  63223. renderOrder:10,
  63224. fontsize:30,
  63225. };
  63226. let markerTex;
  63227. //显示全景图时marker没有被遮挡,如果需要,要换成depthBasicMaterial 或者直接把skybox的深度修改(拿到深度贴图后更如此)
  63228. let planeGeo$1 = new PlaneBufferGeometry(0.2,0.2);
  63229. let sg = new SphereGeometry(0.1, 8, 8);
  63230. let smHovered = new MeshBasicMaterial({/* side: THREE.BackSide, */color: 0xff0000});
  63231. let sm = new MeshBasicMaterial({/* side: THREE.BackSide */});
  63232. var rot90 = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
  63233. //var rot90 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0), -Math.PI/2 ); //4dkk->navvis
  63234. //var rot901 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0), -Math.PI/2 ); //整张球幕图要旋转下
  63235. //rot90 = new THREE.Quaternion().multiplyQuaternions( rot901, rot90)
  63236. var old = null;
  63237. /*
  63238. 转成四维看看的axis:
  63239. var a = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), THREE.Math.degToRad(-90)) 因为四维的要绕y转90
  63240. 这里的quaternion.multiply(a);
  63241. 先乘再换顺序 w : q.w, x:q.x , y:-q.z, z:q.y
  63242. */
  63243. //暂时直接用4dkkconsole输出的数据
  63244. class Panorama extends EventDispatcher{
  63245. constructor(o, images360){//file, time, longitude, latitude, altitude, course, pitch, roll
  63246. super();
  63247. this.id = o.id; //唯一标识
  63248. this.images360 = images360;
  63249. this.visible = true; //for updateVisible
  63250. this.enabled = true;//是否可以走
  63251. this.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  63252. //console.log('pano isVisible', this.id, e.visible)
  63253. Potree.Utils.updateVisible(this.marker, 'panoVisi', e.visible);
  63254. Potree.settings.showPanoMesh && (this.mesh.visible = e.visible);
  63255. if(e.reason == 'screenshot' || e.visible){
  63256. this.label && (this.label.visible = e.visible);//截图时隐藏下
  63257. }
  63258. this.label2 && Potree.Utils.updateVisible(this.label2, 'panoVisi', e.visible);
  63259. });
  63260. /*
  63261. 漫游点可见性:旧
  63262. level reason 类型
  63263. 2(最高)buildingChange(不在此楼层) unvisible
  63264. 1 modeIsShowPanos(漫游模式) visible //不记得为什么加这个了,所以重写
  63265. 0 pointcloudVisi(隐藏了数据集) unvisible
  63266. */
  63267. /*
  63268. 漫游点可见性:新
  63269. level reason 类型
  63270. 2(最高)buildingChange(不在此楼层) unvisible
  63271. 1 ifShowMarker(marker显示开关) unvisible
  63272. 0 pointcloudVisi(隐藏了数据集) unvisible
  63273. */
  63274. if(Potree.settings.editType == 'pano'){//漫游点拼合编辑
  63275. this.uuid = o.uuid; //因为有多个数据集 所以会重复
  63276. this.index = this.originID = o.index; //下标, 用于visibles
  63277. this.pointcloud = viewer.scene.pointclouds.find(e=>e.panoUuid == o.uuid);
  63278. this.pointcloud.panos.push(this);
  63279. this.sid = this.pointcloud.dataset_id + '|' + this.uuid; //不会更改的标记 用于entity.panos里的标记
  63280. this.panosData = o;
  63281. //数据中原本的位置朝向
  63282. this.dataPosition = new Vector3().copy(o.pose.translation);
  63283. this.dataQuaternion = new Quaternion().copy(o.pose.rotation);
  63284. this.dataRotation = new Euler().setFromQuaternion(this.dataQuaternion);
  63285. //因为位置朝向随着点云位置改变,所以直接运用到点云上,这里清零
  63286. this.originPosition = new Vector3(); //{x: 0, y: 0, z: 0}
  63287. this.quaternion = new Quaternion(); //{w: 0, x: 0, y: 0, z: 1}
  63288. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  63289. this.visibles = o.visibles;
  63290. this.rtkState = o.has_rtk ? o.use_rtk : null;
  63291. const height = 1.4; //相机高度
  63292. this.originFloorPosition = this.originPosition.clone();
  63293. this.originFloorPosition.z -= height;
  63294. /* this.originPosition = new THREE.Vector3().copy(o.pose.translation) //{x: 0, y: 0, z: 0}
  63295. this.quaternion = new THREE.Quaternion().copy(o.pose.rotation) //{w: 0, x: 0, y: 0, z: 1}
  63296. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  63297. this.visibles = o.visibles
  63298. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.uuid)
  63299. this.pointcloud.panos.push(this)
  63300. const height = 1.5; //相机高度
  63301. this.originFloorPosition = this.originPosition.clone()
  63302. this.originFloorPosition.z -= height
  63303. */
  63304. }else {
  63305. this.originPosition = new Vector3().fromArray(o.dataset_location); //完全对应vision.txt的translation
  63306. this.originFloorPosition = new Vector3().fromArray(o.dataset_floor_location);
  63307. this.originID = parseInt(o.file_id);//"file_id":"00022"对应是原本的4dkk的id --来自vision.txt
  63308. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.dataset_id) || viewer.scene.pointclouds[0];
  63309. this.pointcloud.panos.push(this);
  63310. //this.sid = this.pointcloud.sceneCode + '|' + this.originID //不会更改的标记
  63311. this.sid = this.pointcloud.dataset_id + '|' + this.originID; //不会更改的标记
  63312. //全景图和Cube的水平采样起始坐标相差90度
  63313. /* if(from4dkk){
  63314. var qua = o.dataset_orientation
  63315. var quaternion = new THREE.Quaternion().fromArray(qua)
  63316. quaternion = new THREE.Quaternion().multiplyQuaternions(quaternion, rot901);//整张球幕图要旋转下 因为在4dkk里转过,还原。如果是tiles的不用
  63317. this.quaternion = new THREE.Quaternion(quaternion.x, -quaternion.z, quaternion.y, quaternion.w) //转化坐标
  63318. }else{ */
  63319. var qua = o.dataset_orientation; //完全对应vision.txt的rotation
  63320. qua = [qua[1], qua[2], qua[3], qua[0]];
  63321. this.quaternion = new Quaternion().fromArray(qua);
  63322. this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion);//4dkk内使用的quaternion
  63323. this.quaternion2 = this.quaternion.clone();
  63324. this.quaternion = new Quaternion().multiplyQuaternions(this.quaternion, rot90);//全景图和Cube的水平采样起始坐标相差90度,cubeTex转90度
  63325. this.rotation4dkk = new Euler().setFromQuaternion(this.quaternion4dkk);
  63326. //}
  63327. //this.quaternion1 = Potree.Utils.QuaternionFactory.fromArray(o.dataset_orientation)
  63328. //同quaternion
  63329. //let xy = this.transform.forward([this.longitude, this.latitude]);
  63330. //this.file = `https://4dkk.4dage.com/images/images${Potree.settings.number}/pan/high/${this.id}.jpg`
  63331. this.neighbours = [];
  63332. }
  63333. this.rotation = new Euler().setFromQuaternion(this.quaternion);
  63334. this.build();
  63335. this.transformByPointcloud(); //初始化位移
  63336. {//tile
  63337. this.minimumTiledPanoLoaded = !1;
  63338. this.highestPartialTileRenderOpCompleted = 0;
  63339. this.highestFullTileRenderOpCompleted = 0;
  63340. this.shouldRedrawOnBaseLoaded = !1;
  63341. this.resolutionPromise = {};
  63342. this.tiledPanoRenderTarget = null;
  63343. this.zoomed = !1;
  63344. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderSuccess, this.onTileRendered.bind(this));
  63345. images360.panoRenderer.addEventListener(PanoRendererEvents.PanoRenderComplete, this.onPanoRendered.bind(this));
  63346. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderFailure, this.onTileRenderFail.bind(this));
  63347. images360.panoRenderer.addEventListener(PanoRendererEvents.UploadAttemptedForAllTiles, this.onUploadAttemptedForAllTiles.bind(this));
  63348. }
  63349. this.addEventListener('hoverOn', (e)=>{//from Map
  63350. if(!e.byMainView){
  63351. this.hoverOn(e);
  63352. }
  63353. });
  63354. this.addEventListener('hoverOff', (e)=>{
  63355. if(!e.byMainView){
  63356. this.hoverOff(e);
  63357. }
  63358. });
  63359. }
  63360. get noNeighbour(){//是否绝对到不到的孤立点
  63361. for(let i=0,j=this.images360.panos.length; i<j; i++){
  63362. if(this.images360.neighbourMap[this.id][i] !== false ){
  63363. return false
  63364. }
  63365. }
  63366. return true
  63367. //return this.neighbours.length == 0
  63368. }
  63369. setEnable(enable){//是否可以走
  63370. Potree.Utils.updateVisible(this, 'isEnabled', enable); //令所有marker不可见
  63371. this.enabled = enable;
  63372. //如果当前在全景模式且在这个点,需要切换显示吗? 目前用不到
  63373. }
  63374. loadDepthImg(){
  63375. if(!this.pointcloud.hasDepthTex || this.depthTex || this.depthTexLoading)return
  63376. this.depthTexLoading = true;
  63377. let mapping = Potree.settings.isLocal2 ? '' : this.pointcloud.datasetData.mapping; //非离线包的话加mapping
  63378. let src = `${Potree.settings.urls.prefix1}/${mapping?(mapping+'/'):''}${Potree.settings.webSite}/${this.pointcloud.sceneCode}/data/${this.pointcloud.sceneCode}/depthmap/${this.originID}.png`;
  63379. // `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${this.pointcloud.sceneCode}/data/${this.pointcloud.sceneCode}/depthmap/${this.originID}.png`
  63380. //console.log('开始下载depthImg', this.id)
  63381. let texture = texLoader$5.load( src, ()=>{
  63382. this.depthTex = texture;
  63383. this.dispatchEvent({type:'loadedDepthImg', loaded:true});
  63384. this.depthTexLoading = false;
  63385. this.images360.updateDepthTex(this);
  63386. //viewer.dispatchEvent('content_changed')
  63387. },null,(e)=>{//error
  63388. console.error('loadDepthImg失败, 数据集sceneCode'+ this.pointcloud.sceneCode, this.id );
  63389. this.pointcloud.hasDepthTex = false;
  63390. this.dispatchEvent({type:'loadedDepthImg' });
  63391. });
  63392. texture.wrapS = RepeatWrapping;
  63393. texture.flipY = false;
  63394. texture.magFilter = LinearFilter;
  63395. texture.minFilter = LinearFilter;
  63396. texture.generateMipmaps = false;
  63397. }
  63398. build(){
  63399. { // orientation
  63400. //add
  63401. //var quaternion = new THREE.Quaternion().multiplyQuaternions(this.quaternion, rot901);//改 为球目全
  63402. //quaternion.premultiply(rot90)
  63403. this.panoMatrix = new Matrix4().makeRotationFromQuaternion(this.quaternion);
  63404. this.oriPanoMatrix = this.panoMatrix.clone();
  63405. if(this.quaternion2)this.oriPanoMatrix2 = new Matrix4().makeRotationFromQuaternion(this.quaternion2);
  63406. //console.log(this.quaternion)
  63407. //this.quaternion = quaternion
  63408. }
  63409. /* let marker = new THREE.Mesh(planeGeo, this.getMarkerMat() )
  63410. //marker.lookAt(marker.up)
  63411. marker.scale.set(2,2,2) */
  63412. let marker = new Mesh(planeGeo$1, this.getMarkerMat() ); //new Sprite({mat:this.getMarkerMat(), dontFixOrient:true })
  63413. marker.scale.set(2,2,2);//marker.scale.set(0.4,0.4,0.4)
  63414. marker.name = 'marker_'+this.id;
  63415. marker.up.set(0,0,1);
  63416. this.addEventListener('changeMarkerTex',(e)=>{
  63417. marker.material.map = markerTex[e.name];
  63418. });
  63419. this.marker = marker;
  63420. marker.pano = this;
  63421. this.images360.node.add(marker);
  63422. Potree.settings.isTest && this.addLabel();
  63423. //this.addLabel2()
  63424. marker.addEventListener('mouseover', this.hoverOn.bind(this));
  63425. marker.addEventListener('mouseleave', this.hoverOff.bind(this));
  63426. }
  63427. transformByPointcloud(){
  63428. let position = this.originPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);//也可以用datasetPosTransform算
  63429. let floorPosition = this.originFloorPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);
  63430. this.setPosition(position, floorPosition);
  63431. this.panoMatrix = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix );
  63432. //this.panoMatrix2 = Potree.Utils.datasetRotTransform({fromDataset:true, pointcloud:this.pointcloud, matrix:this.oriPanoMatrix, getMatrix:true}) //和上一行结果一样
  63433. //quaternion也变下
  63434. if(this.oriPanoMatrix2){
  63435. this.panoMatrix2 = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix2 );//供DepthImageSampler使用
  63436. this.panoMatrix2Inverse = this.panoMatrix2.clone().invert();
  63437. }
  63438. this.dispatchEvent('rePos');
  63439. }
  63440. setPosition(position, floorPosition){
  63441. this.position = position;
  63442. this.floorPosition = floorPosition;
  63443. //this.mesh.position.copy(this.position)
  63444. this.marker.position.copy(this.floorPosition);
  63445. this.marker.position.z+=0.04;//会被点云遮住
  63446. if(this.label){
  63447. if(Potree.settings.editType == 'pano'){
  63448. this.label.position.copy(this.position);
  63449. }else {
  63450. this.label.position.copy(this.floorPosition);
  63451. }
  63452. this.label.position.z+=0.14;
  63453. this.label.update();
  63454. }
  63455. /* if(this.label2){
  63456. if(Potree.settings.editType == 'pano'){
  63457. this.label2.position.copy(this.position)
  63458. }else{
  63459. this.label2.position.copy(this.floorPosition)
  63460. }
  63461. this.label2.position.copy(this.marker.position)
  63462. this.label2.update()
  63463. } */
  63464. }
  63465. /* getRealPos(){//当整体移动以后
  63466. return this.position.clone().applyMatrix4(viewer.scene.scene.matrix)
  63467. } */
  63468. getMarkerMat(){
  63469. if(!markerTex) {
  63470. markerTex = {
  63471. default:texLoader$5.load( Potree.resourcePath+'/textures/marker.png' ),
  63472. ring:texLoader$5.load( Potree.resourcePath+'/textures/marker2.png' )
  63473. };
  63474. markerTex.default.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  63475. markerTex.ring.anisotropy = 4;
  63476. //有可能被点云遮住吗。
  63477. }
  63478. return new DepthBasicMaterial({opacity: markerOpacitys.default, side: DoubleSide , map:markerTex.default ,transparent:true,
  63479. clipDistance: 2, occlusionDistance:1, //不能设置太短,因为过渡时深度不准确
  63480. useDepth: !!(Potree.settings.useDepthTex && this.pointcloud.hasDepthTex),
  63481. autoDepthTest:true
  63482. //改为DepthBasicMaterial是因为原Basic的材质在有深度图时过渡会先隐藏后出现。 注:没有深度图时全景模式的marker无法遮挡
  63483. })
  63484. }
  63485. hoverOn(e={}) {
  63486. //console.log("hoverOn " + this.id )
  63487. transitions.start(lerp.property(this.marker.material, "opacity", markerOpacitys.hovered,()=>{
  63488. viewer.dispatchEvent('content_changed');
  63489. }), this.marker.visible ? 250 : 0);
  63490. if(!e.byMap) this.dispatchEvent({type:'hoverOn', byMainView:true});
  63491. if(!e.byImages360) this.images360.dispatchEvent({type:'markerHover', hovered:true, pano:this});
  63492. }
  63493. hoverOff(e={}){
  63494. //console.log("hoverOff " + this.id )
  63495. transitions.start(lerp.property(this.marker.material, "opacity", markerOpacitys.default,()=>{
  63496. viewer.dispatchEvent('content_changed');
  63497. }), this.marker.visible ? 250 : 0);
  63498. if(!e.byMap) this.dispatchEvent({type:'hoverOff', byMainView:true});
  63499. if(!e.byImages360) this.images360.dispatchEvent({type:'markerHover', hovered:false, pano:this});
  63500. }
  63501. setZoomed(zoomed){
  63502. this.zoomed = zoomed;
  63503. Potree.settings.displayMode == 'showPanos' && this.updateSkyboxForZoomLevel(); //放大后换成zoomTarget贴图
  63504. viewer.dispatchEvent({type:'panoSetZoom', zoomed});
  63505. }
  63506. enter(){
  63507. this.entered = true;
  63508. this.setZoomed(!1);
  63509. viewer.dispatchEvent({type:PanoramaEvents.Enter, oldPano:old, newPano:this } );
  63510. old = this;
  63511. //console.log("enter pano "+ this.id)
  63512. }
  63513. exit(){
  63514. this.clearWaitDeferreds();
  63515. this.minimumTiledPanoLoaded = !1;
  63516. this.tiledPanoRenderTarget = null;
  63517. this.setZoomed(!1);
  63518. this.images360.panoRenderer.deactivateTiledPano(this);
  63519. this.highestPartialTileRenderOpCompleted = 0;
  63520. this.highestFullTileRenderOpCompleted = 0;
  63521. this.depthTex && this.depthTex.dispose(); //贴图不使用后先dispose,下次到该点时会自动还原
  63522. this.entered = false; //add
  63523. //console.log("exit pano "+ this.id)
  63524. viewer.dispatchEvent({type:PanoramaEvents.Exit, pano:this});
  63525. }
  63526. updateSkyboxForZoomLevel(){
  63527. if(this.minimumTiledPanoLoaded){
  63528. this.images360.updateProjectedPanos();
  63529. }
  63530. }
  63531. getSkyboxTexture(){
  63532. if(this.minimumTiledPanoLoaded)
  63533. {
  63534. if(this.zoomed && this.images360.qualityManager.maxRenderTargetSize > this.images360.qualityManager.maxNavPanoSize)//change 如果放大后和不放大都是2k就不用这个
  63535. {
  63536. return this.images360.panoRenderer.zoomRenderTarget.texture;
  63537. }
  63538. else
  63539. {
  63540. this.tiledPanoRenderTarget.texture.mapping = UVMapping;//add
  63541. return this.tiledPanoRenderTarget.texture;
  63542. }
  63543. }
  63544. else
  63545. {
  63546. return null;
  63547. }
  63548. }
  63549. isLoaded(e){
  63550. if (e && "string" == typeof e)
  63551. console.error("Wrong panoSize given to Panorama.isLoaded(); a tiled pano uses PanoSizeClass");
  63552. return !!this.minimumTiledPanoLoaded && (!e || this.highestFullTileRenderOpCompleted >= e)//改:原本是:this.highestPartialTileRenderOpCompleted >= e, 希望这代表全部加载完
  63553. }
  63554. getWaitDeferred(size){//获取不同size的tile贴图的promiss
  63555. var t = this.resolutionPromise[this.id];
  63556. t || (t = {}, this.resolutionPromise[this.id] = t);
  63557. var i = t[size];
  63558. return i || (i = {
  63559. deferred: $.Deferred(),
  63560. active: !1
  63561. },
  63562. t[size] = i),
  63563. i
  63564. }
  63565. clearWaitDeferreds(){
  63566. var e = this.resolutionPromise[this.id];
  63567. e || (e = {},
  63568. this.resolutionPromise[this.id] = e);
  63569. for (var t in e)
  63570. if (e.hasOwnProperty(t)) {
  63571. var i = e[t];
  63572. i.active = !1,
  63573. i.deferred = $.Deferred();
  63574. }
  63575. }
  63576. resetWaitDeferred(e){
  63577. var t = this.getWaitDeferred(e);
  63578. t.active = !1;
  63579. t.deferred = $.Deferred();
  63580. }
  63581. onTileRendered(ev){
  63582. ev.id === this.id && this.dispatchEvent({
  63583. type:PanoramaEvents.TileLoaded,
  63584. size:ev.panoSize, index:ev.tileIndex, count:ev.totalTiles
  63585. });
  63586. }
  63587. onPanoRendered(ev) {
  63588. if(ev.id === this.id)
  63589. {
  63590. this.minimumTiledPanoLoaded = !0;
  63591. this.updateSkyboxForZoomLevel();//更新贴图 setProjected
  63592. ev.panoSize > this.highestPartialTileRenderOpCompleted && (this.highestPartialTileRenderOpCompleted = ev.panoSize);//应该是更新最高获取到的Partial size
  63593. ev.updateFullComplete && ev.panoSize > this.highestFullTileRenderOpCompleted && (this.highestFullTileRenderOpCompleted = ev.panoSize); //应该是更新最高获取到的Full size
  63594. //this.dispatchEvent("load", ev.panoSize);
  63595. viewer.ifAllLoaded( this);
  63596. this.dispatchEvent({type:PanoramaEvents.LoadComplete, size:ev.panoSize, count:ev.totalTiles});
  63597. }
  63598. }
  63599. onTileRenderFail(ev) {
  63600. ev.id === this.id && this.dispatchEvent({type:PanoramaEvents.LoadFailed });
  63601. }
  63602. onUploadAttemptedForAllTiles(ev) {
  63603. if (ev.id === this.id) {
  63604. var n = this.images360.qualityManager.getPanoSize(PanoSizeClass.BASE);
  63605. if(ev.panoSize === n && this.shouldRedrawOnBaseLoaded) //shouldRedrawOnBaseLoaded一直是false。在4dkk里只有初始点在quickstart后变为true。
  63606. {
  63607. this.shouldRedrawOnBaseLoaded = !1;
  63608. this.panoRenderer.resetRenderStatus(this.id, !0, !1);
  63609. this.panoRenderer.renderPanoTiles(this.id, null, !0, !0);
  63610. }
  63611. }
  63612. }
  63613. addLabel(){
  63614. this.removeTextLabel();
  63615. this.label = new TextSprite$2(Object.assign({},
  63616. labelProp, {text: this.id + "("+this.originID+")"}) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  63617. );
  63618. this.images360.node.add(this.label);
  63619. this.floorPosition && this.label.position.copy(this.floorPosition);
  63620. }
  63621. addLabel2(){
  63622. if(this.label2)return
  63623. this.label2 = new TextSprite$2(Object.assign({},
  63624. labelProp2, {text: /* this.originID */ parseInt(this.id)+1 }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  63625. );
  63626. //this.images360.node.add(this.label2);
  63627. this.marker.add(this.label2);
  63628. //this.floorPosition && this.label2.position.copy(this.floorPosition)
  63629. let s = 0.2;
  63630. this.label2.scale.set(s,s,s);
  63631. Potree.Utils.updateVisible(this.label2, 'notDisplay', false);
  63632. Potree.Utils.updateVisible(this.label2, 'panoVisi', this.visible);
  63633. //Potree.Utils.setObjectLayers(this.label2, 'bothMapAndScene')
  63634. }
  63635. removeTextLabel(){
  63636. if(this.label){
  63637. this.label.parent.remove(this.label);
  63638. }
  63639. }
  63640. dispose(){
  63641. let i = viewer.images360.panos.indexOf(this);
  63642. if(i==-1)return
  63643. this.marker.parent.remove(this.marker);
  63644. this.removeTextLabel();
  63645. if(this.depthTex) this.depthTex.dispose();
  63646. viewer.images360.panos.splice(i,1);
  63647. this.dispatchEvent('dispose');
  63648. //删除tile贴图、depthTex等以后再写
  63649. }
  63650. getCeilHeight(){//天花板高度值 (假设不存在depth为0的点,所有为0的要么是在盲区,要么是无穷远。)
  63651. if(this.ceilZ == void 0){
  63652. //const depthTiming = Potree.timeCollect.depthSampler.median //pc firefox达到4. chrome为0.01
  63653. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  63654. let rotMat = new Matrix4().makeRotationX((Potree.config.depthTexUVyLimit+0.01)*Math.PI);// 角度不能小于天花板中空的半径
  63655. let dir0 = new Vector3(0,0,1).applyMatrix4(rotMat);
  63656. let dirs = [
  63657. dir0,
  63658. dir0.clone().applyMatrix4(new Matrix4().makeRotationZ(Math.PI*2 / 3)),
  63659. dir0.clone().applyMatrix4(new Matrix4().makeRotationZ(-Math.PI*2 / 3))
  63660. ];
  63661. /* if(depthTiming < 1){
  63662. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  63663. dirs.push(dirs[0].clone().applyMatrix4(rotMat1))
  63664. }
  63665. if(depthTiming < 0.3){
  63666. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  63667. dirs.push(dirs[0].clone().applyMatrix4(rotMat2));
  63668. } */
  63669. let zs = dirs.map(dir_=>{
  63670. let dir = dir_.clone().applyMatrix4(this.panoMatrix2); //pano不一定是垂直的, 需要把之前的dirInPano先转成真实的dir,防止超出角度限制
  63671. let intersect = viewer.images360.getIntersect(this, dir);
  63672. let z = intersect ? intersect.location.z : Infinity;/* this.position.z+skyHeight */ //没有intersect代表可能是天空
  63673. return z
  63674. });
  63675. zs.sort((a,b)=>{return b-a});//得最大值 (不用中位数的原因:在屋檐处,如果仅有一个intersect是天空,因到了室外所以也用天空高度)
  63676. this.ceilZ = zs[0];
  63677. let min = this.position.z + 1; // 防止意外太低
  63678. this.ceilZ = Math.max(min, this.ceilZ);
  63679. //console.log(this.id, 'ceilZ:', this.ceilZ )
  63680. }
  63681. return this.ceilZ
  63682. }
  63683. };
  63684. Panorama.prototype.loadTiledPano = function() {
  63685. //var downloads = [] , t = [];
  63686. var downloaded = {} , eventAdded = {}, latestPartialRequest = {}; //每个pano对应一组这些
  63687. return function(size, dirs, fov, o, a, download) {
  63688. var dir = dirs.datasetsLocal.find(e=>e.datasetId == this.pointcloud.dataset_id).direction;
  63689. //var dir = dirs
  63690. null !== o && void 0 !== o || (o = !0),
  63691. null !== a && void 0 !== a || (a = !0);
  63692. var l = this.getWaitDeferred(size)
  63693. , c = l.deferred
  63694. , h = null
  63695. , u = null;
  63696. fov && ("number" == typeof fov ? h = fov : (h = fov.hFov, u = fov.vFov));
  63697. if (!this.isLoaded(size)) {
  63698. //console.log('loadTiledPano', this.id, size, fov)
  63699. if (!l.active) {
  63700. l.active = !0;
  63701. let name = this.id + ":" + size;
  63702. downloaded[name] = downloaded[name] || [];
  63703. /*
  63704. this.downloaded = downloaded
  63705. this.latestPartialRequest = latestPartialRequest
  63706. */
  63707. latestPartialRequest[name] = null;
  63708. if (fov) {
  63709. let tileArr = [];//add
  63710. var d = TileUtils.matchingTilesInDirection(this, size, dir, h, u, tileArr);
  63711. latestPartialRequest[name] = tileArr;
  63712. downloaded[name].forEach((e)=>{
  63713. let item = latestPartialRequest[name].find(a=>e.faceTileIndex == a.faceTileIndex && e.face == a.face);
  63714. if(item){
  63715. item.loaded = true;
  63716. }
  63717. });
  63718. if(!latestPartialRequest[name].some(e=>!e.loaded)){//所需要的全部加载成功
  63719. //let total = TileUtils.getTileCountForSize(size)
  63720. //this.onPanoRendered(this.id, size, total, !0);
  63721. c.resolve(size/* , total */);
  63722. this.resetWaitDeferred(size);
  63723. //console.log('该部分早已经加载好了'+size, this.id)
  63724. latestPartialRequest[name] = null;
  63725. }
  63726. //console.log("Loading partial pano: " + this.id + " with " + d + " tiles")
  63727. }
  63728. if(!eventAdded[this.id]) {
  63729. eventAdded[this.id] = !0;
  63730. this.addEventListener(PanoramaEvents.LoadComplete, function(ev/* e, t */) {//本次任务全部加载完毕
  63731. //console.warn('点位(可能部分)下载完成 ', 'id:'+this.id, 'size:'+ev.size )
  63732. var i = this.getWaitDeferred(ev.size).deferred;//"pending"为还未完成
  63733. i && "pending" === i.state() && this.highestPartialTileRenderOpCompleted >= ev.size && (i.resolve(ev.size, ev.count),
  63734. this.resetWaitDeferred(ev.size));//恢复active为false
  63735. }.bind(this));
  63736. this.addEventListener(PanoramaEvents.LoadFailed, function(ev) {
  63737. var t = this.getWaitDeferred(e).deferred;
  63738. t && "pending" === t.state() && this.highestPartialTileRenderOpCompleted >= ev.t && (t.reject(ev.t),
  63739. this.resetWaitDeferred(ev.t));//恢复active为false
  63740. }.bind(this));
  63741. this.addEventListener(PanoramaEvents.TileLoaded, function(ev/* t, i, n */) {//每张加载完时
  63742. //console.log('tileLoaded', 'id:'+this.id, 'size:'+ev.size, 'tileIndex:'+ev.index )
  63743. let tileIndex = ev.index;
  63744. let total = ev.count;
  63745. let size = ev.size;
  63746. let name = this.id + ":" + size;
  63747. downloaded[name] = downloaded[name] || []; //不是所有的加载都是从loadTiledPano获取的所以会有未定义的情况
  63748. let {faceTileIndex,face} = TileUtils.getTileLocation(size, tileIndex, {});
  63749. downloaded[name].push({faceTileIndex,face});
  63750. var r = this.getWaitDeferred(size).deferred;
  63751. if (r && "pending" === r.state()) {
  63752. r.notify(size, tileIndex, total);
  63753. if(latestPartialRequest[name]){
  63754. let item = latestPartialRequest[name].find(e=>e.faceTileIndex == faceTileIndex && e.face == face);
  63755. item && (item.loaded = true );
  63756. if(!latestPartialRequest[name].some(e=>!e.loaded)){//所需要的局部tiles全部加载成功
  63757. this.onPanoRendered(this.id, size, total, !0); //onPanoRendered还会触发 PanoramaEvents.LoadComplete
  63758. r.resolve(size, total);
  63759. this.resetWaitDeferred(size);
  63760. //console.log('该部分加载好了'+size, this.id)
  63761. latestPartialRequest[name] = null;
  63762. }
  63763. }
  63764. }
  63765. viewer.dispatchEvent('content_changed');
  63766. /* var r = this.getWaitDeferred(ev.size).deferred;
  63767. if (r && "pending" === r.state()) {
  63768. r.notify(ev.size, ev.index, ev.count);
  63769. var o = downloads[this.id + ":" + ev.size];
  63770. if(o){//如果有规定下载哪些tile,只需要下载这些tile则LoadComplete
  63771. o.tileCount++
  63772. if(o.tileCount === o.targetTileCount){//达到下载目标数
  63773. this.onPanoRendered(this.id, ev.size, ev.count, !0);
  63774. r.resolve(ev.size, ev.count);
  63775. this.resetWaitDeferred(ev.size)
  63776. }
  63777. }
  63778. } */
  63779. }.bind(this));
  63780. }
  63781. }
  63782. this.images360.tileDownloader.clearForceQueue();
  63783. this.images360.tileDownloader.forceQueueTilesForPano(this, size, dir, h, u, download);
  63784. this.tiledPanoRenderTarget = this.images360.panoRenderer.activateTiledPano(this, this.images360.qualityManager.getMaxNavPanoSize(), o);
  63785. this.images360.panoRenderer.renderPanoTiles(this.id, dirs, a);
  63786. }else {
  63787. //console.log('早已经全加载好了' +size, this.id)
  63788. c.resolve(size);
  63789. }
  63790. return c.promise()
  63791. }
  63792. }();
  63793. let {ModelManagerEvents,PanoSizeClass: PanoSizeClass$1} = Potree.defines;
  63794. class QualityManager {
  63795. constructor(e, t, i) {
  63796. this.maxNavPanoSize = -1;
  63797. this.maxZoomPanoSize = -1;
  63798. this.devicePixelDensity = e;
  63799. this.deviceScreenSize = t;
  63800. this.clientBandwidth = i;
  63801. this.panoSizeClassMap = {};
  63802. this.useHighResolutionPanos = !0; //是否能够使用2k及以上图
  63803. this.useUltraHighResolutionPanos = !1;
  63804. this.modelHasUltraHighPanos = !1;
  63805. this.qualityManager = this;
  63806. this.maxRenderTargetSize = browser.isMobile() ? 2048 : 4096; //add
  63807. this.init();
  63808. }
  63809. init(e ) {
  63810. //var metadata = store.getters['scene/metadata'] ;//有时候请求不到
  63811. //if(metadata.sceneSource == 11 || metadata.sceneScheme == 12){
  63812. /* if(config.tileClass == '1k'){
  63813. this.useHighResolutionPanos = false //xzw add 只加载1k
  63814. } */
  63815. this.buildPanoSizeClassMap(this.devicePixelDensity, this.deviceScreenSize, this.clientBandwidth);
  63816. this.ultraHighSize = this.getPanoSize(PanoSizeClass$1.ULTRAHIGH);
  63817. this.highSize = this.getPanoSize(PanoSizeClass$1.HIGH);
  63818. this.standardSize = this.getPanoSize(PanoSizeClass$1.STANDARD);
  63819. this.baseSize = this.getPanoSize(PanoSizeClass$1.BASE);
  63820. config$1.tiling.maxZoomPanoQuality && this.ultraHighSize <= config$1.tiling.maxZoomPanoQuality && (config$1.tiling.allowUltraHighResolution = !0);
  63821. this.highQualityThreshold = browser.valueFromHash("threshold2k", config$1.windowHeightHighQualityThreshold);
  63822. this.updateMaximums();
  63823. //e.on(ModelManagerEvents.ActiveModelChanged, this.onModelChanged.bind(this));
  63824. }
  63825. updateFromModel(e) {
  63826. //this.updateHighResolutionSettings(e)
  63827. this.updateUltraHighResolutionSettings(e);
  63828. }
  63829. /* updateHighResolutionSettings(e) {
  63830. this.useHighResolutionPanos = !0
  63831. this.updateMaximums()
  63832. } */
  63833. updateUltraHighResolutionSettings(e) {
  63834. if (config$1.tiling.allowUltraHighResolution && this.modelHasUltraHighPanos) {
  63835. this.useUltraHighResolutionPanos = !0;
  63836. } else {
  63837. this.useUltraHighResolutionPanos = !1;
  63838. }
  63839. this.updateMaximums();
  63840. }
  63841. enableUltraHighQualityMode() {
  63842. this.modelHasUltraHighPanos = !0;
  63843. this.updateUltraHighResolutionSettings(null);
  63844. }
  63845. ultraHighQualityModeEnabled() {
  63846. return this.modelHasUltraHighPanos
  63847. }
  63848. onModelChanged(e) {
  63849. this.updateFromModel(e.model),
  63850. this.updateMaximums();
  63851. }
  63852. updateMaximums() {
  63853. this.maxNavPanoSize = config$1.tiling.maxNavPanoQuality || this.detectMaxNavPanoSize(),
  63854. this.maxZoomPanoSize = config$1.tiling.maxZoomPanoQuality || this.detectMaxZoomPanoSize(),
  63855. this.maxZoomPanoSize < this.maxNavPanoSize && (this.maxNavPanoSize = this.maxZoomPanoSize);
  63856. }
  63857. buildPanoSizeClassMap() {
  63858. this.panoSizeClassMap[PanoSizeClass$1.BASE] = 512,
  63859. this.panoSizeClassMap[PanoSizeClass$1.STANDARD] = 1024,
  63860. this.panoSizeClassMap[PanoSizeClass$1.HIGH] = 2048,
  63861. this.panoSizeClassMap[PanoSizeClass$1.ULTRAHIGH] = 4096;
  63862. }
  63863. getPanoSize(e) {
  63864. return this.panoSizeClassMap[e]
  63865. }
  63866. getMaxPossiblePanoSize() {
  63867. return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH)
  63868. }
  63869. getMaxPanoSize() {
  63870. return this.maxZoomPanoSize
  63871. }
  63872. getMaxNavPanoSize() {
  63873. return this.maxNavPanoSize
  63874. }
  63875. getMaxZoomPanoSize() {
  63876. return this.maxZoomPanoSize
  63877. }
  63878. detectMaxNavPanoSizeClass() {
  63879. //return this.useHighResolutionPanos ? browser.isMobile() ? PanoSizeClass.STANDARD : window.innerHeight < this.highQualityThreshold ? PanoSizeClass.STANDARD : PanoSizeClass.HIGH : PanoSizeClass.STANDARD
  63880. /* if(config.name == 'decor'){
  63881. return PanoSizeClass.STANDARD
  63882. }
  63883. return PanoSizeClass.HIGH */
  63884. switch(Potree.settings.navTileClass){
  63885. case '1k':
  63886. return PanoSizeClass$1.STANDARD;
  63887. break;
  63888. case '2k':
  63889. default:
  63890. return PanoSizeClass$1.HIGH;
  63891. }
  63892. }
  63893. detectMaxNavPanoSize() {
  63894. var e = this.detectMaxNavPanoSizeClass();
  63895. return this.getPanoSize(e)
  63896. }
  63897. detectMaxZoomPanoSize() { //获取当前zoomRenderTarget应下载的最高级别
  63898. //若是有三个级别,每次只需要加载到当前的zoomLevel;而两级时因为有zoomed来判断是使用基本贴图还是zoomRenderTarget,所以只需要返回最大的即可
  63899. if(this.zoomLevelResolution){//有三个级别
  63900. if(this.zoomLevelResolution == '4k' && this.useUltraHighResolutionPanos){
  63901. return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH);
  63902. }else if(this.zoomLevelResolution == '1k' || !this.useHighResolutionPanos){
  63903. return this.getPanoSize(PanoSizeClass$1.STANDARD);
  63904. }else {
  63905. return this.getPanoSize(PanoSizeClass$1.HIGH);
  63906. }
  63907. }else {
  63908. if (this.useHighResolutionPanos) {
  63909. /* if (browser.isMobile()) {//手机版如果要2k的将这里去掉
  63910. if (settings.tiling.mobileHighQualityOverride) {
  63911. return this.getPanoSize(PanoSizeClass.HIGH);
  63912. } else {
  63913. return this.getPanoSize(PanoSizeClass.STANDARD);
  63914. }
  63915. } else */if (this.useUltraHighResolutionPanos ) {
  63916. return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH);
  63917. } else {
  63918. return this.getPanoSize(PanoSizeClass$1.HIGH);
  63919. }
  63920. } else {
  63921. return this.getPanoSize(PanoSizeClass$1.STANDARD);
  63922. }
  63923. }
  63924. }
  63925. }
  63926. let {DownloadStatus} = Potree.defines;
  63927. var h = Object.freeze({
  63928. None: 0,
  63929. DirectionalFOV: 1
  63930. });
  63931. var u = function () {
  63932. var e = function e(t, i) {
  63933. var n = e._panoSpaceDir,
  63934. r = e._fovThreshold,
  63935. o = e._fovThresholdNarrow,
  63936. a = Math.max(Math.min(n.dot(t.direction), 1), -1),
  63937. s = Math.max(Math.min(n.dot(i.direction), 1), -1);
  63938. return t._dot = a,
  63939. i._dot = s,
  63940. 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)
  63941. };
  63942. return e._panoSpaceDir = new Vector3,
  63943. e._fovThreshold = -1,
  63944. e._fovThresholdNarrow = -1,
  63945. e
  63946. }();
  63947. class TilePrioritizer {//优先级处理序列
  63948. constructor(e,t, i, o, a) {
  63949. this.qualityManager = e;
  63950. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize();
  63951. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  63952. this.baseSize = t;
  63953. this.standardSize = i;
  63954. this.highSize = o;
  63955. this.ultraHighSize = a;
  63956. this.priorityCriteria = new TilePrioritizer.PriorityCriteria(null, new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 0, -1));
  63957. }
  63958. updateCriteria(e, t, i, n) {//由player更新
  63959. this.priorityCriteria.pano = e,
  63960. this.priorityCriteria.cameraPosition.copy(t),
  63961. //this.priorityCriteria.cameraDir.copy(i),
  63962. this.priorityCriteria.cameraDirs = i;
  63963. this.priorityCriteria.upcomingPanos = n,
  63964. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize(),
  63965. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  63966. }
  63967. canDownloadSize(e) {
  63968. return this.maxNavQuality >= e || this.maxZoomQuality >= e && this.zoomingActive
  63969. }
  63970. /* populateNeighborPanos(e, t, i) {
  63971. i = i || [],
  63972. i.length = 0;
  63973. var n = t.getNeighbours(e);
  63974. for (var r in n)
  63975. if (n.hasOwnProperty(r)) {
  63976. var o = t.get(r);
  63977. if(!o){
  63978. console.log(1)
  63979. }
  63980. i.push(o)
  63981. }
  63982. return i
  63983. } */
  63984. populateScoredPanos(e, t, i, dirs, a, dontFilterDir) {
  63985. i = i || [],
  63986. i.length = 0;
  63987. var s = [Images360.filters.not(e)],
  63988. l = [Images360.scoreFunctions.distanceSquared(e), Images360.scoreFunctions.direction(e.position, dirs)],
  63989. c = Common$1.sortByScore(t, s, l);
  63990. if(!dontFilterDir){
  63991. s.push(Images360.filters.inPanoDirection(e.position, dirs, TilePrioritizer.DIRECTION_SCORE_STRICTNESS),);
  63992. }
  63993. if (c)
  63994. for (var h = 0; h < c.length && h < a; h++) {
  63995. var u = c[h].item;
  63996. i.push(u);
  63997. }
  63998. return i
  63999. }
  64000. queueTilesForPanos(e, t, i, n, r) {
  64001. for (var o = 0, a = 0; a < t.length; a++) {
  64002. var s = t[a],
  64003. l = this.queueTilesForPano(e, i, s, n);
  64004. if (o += l > 0 ? 1 : 0,
  64005. r && o >= r)
  64006. break
  64007. }
  64008. return o
  64009. }
  64010. /* queueTilesInDirectionForPanos(e, t, i, n, r, o, a, s) {//没用到
  64011. for (var l = 0, c = 0; c < i.length; c++) {
  64012. var h = i[c],
  64013. u = this.queueTilesInDirectionForPano(e, t, h, n, o, a);
  64014. if (l += u > 0 ? 1 : 0,
  64015. s && l >= s)
  64016. break
  64017. }
  64018. return l
  64019. }
  64020. */
  64021. canIncludeDescriptor(e) {
  64022. return e.status !== DownloadStatus.Downloading && e.status !== DownloadStatus.Downloaded
  64023. }
  64024. canIncludePano(e, t) {
  64025. return !e.isLoaded(t)
  64026. }
  64027. getFOVDotThreshold(e) {
  64028. return Math.cos(MathUtils.degToRad(e / 2))
  64029. }
  64030. setZoomingActive(e) {
  64031. e !== this.zoomingActive && (this.zoomingActive = e);
  64032. }
  64033. }
  64034. TilePrioritizer.PriorityCriteria = function (e, t, i, n, o) {
  64035. this.pano = e,
  64036. this.cameraPosition = (new Vector3).copy(t),
  64037. //this.cameraDir = (new THREE.Vector3).copy(i),
  64038. this.cameraDirs = [], //
  64039. this.panoSpaceDir = (new Vector3).copy(n),
  64040. this.upcomingPanos = o,
  64041. this.copy = function (e) {
  64042. this.pano = e.pano,
  64043. this.cameraPosition.copy(e.cameraPosition),
  64044. //this.cameraDir.copy(e.cameraDir),
  64045. this.cameraDirs = e.cameraDirs;
  64046. this.panoSpaceDir.copy(e.panoSpaceDir),
  64047. this.upcomingPanos = o;
  64048. },
  64049. this.zoomingActive = !1;
  64050. };
  64051. TilePrioritizer.DIRECTIONAL_FOV = 180;
  64052. TilePrioritizer.DIRECTIONAL_FOV_NARROW = 120;
  64053. TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER = 6;
  64054. TilePrioritizer.MAX_SCORED_PANOS_TOADD = 2;
  64055. TilePrioritizer.MAX_UPCOMING_PANOS_TOADD = 3;
  64056. TilePrioritizer.DIRECTION_SCORE_STRICTNESS = .75;
  64057. TilePrioritizer.appendQueue = function (e, t) {
  64058. if (e && t)
  64059. for (var i = 0; i < t.length; i++){
  64060. e.push(t[i]);
  64061. //console.log(t[i])
  64062. }
  64063. };
  64064. TilePrioritizer.sortPanoTiles = function (descriptors, pano, dir) {
  64065. if(dir.datasetsLocal) dir = dir.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  64066. u._panoSpaceDir.copy(dir);
  64067. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir); //应该是将dir根据quaternion转化下
  64068. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  64069. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  64070. descriptors.sort(u);
  64071. };
  64072. TilePrioritizer.insertSortedPanoTile = function (e, t, pano, dir) {
  64073. if(dir.datasetsLocal) dir = dir.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  64074. u._panoSpaceDir.copy(dir),
  64075. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir),
  64076. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW),
  64077. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  64078. for (var o = -1, a = 0; a < e.length; a++) {
  64079. var s = u(t, e[a]);
  64080. if (s <= 0) {
  64081. o = a;
  64082. break
  64083. }
  64084. }
  64085. if (o === -1)
  64086. e[e.length] = t;
  64087. else {
  64088. for (var h = e.length; h > o; h--)
  64089. e[h] = e[h - 1];
  64090. e[o] = t;
  64091. }
  64092. };
  64093. TilePrioritizer.prototype.filterDepthTex = function (panos ) {// 下载depthTex
  64094. if(!Potree.settings.useDepthTex || !this.priorityCriteria.pano || viewer.mainViewport.view.isFlying())return
  64095. let cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  64096. let nearPanos = []; //用于获得邻近点位序列
  64097. this.populateScoredPanos(this.priorityCriteria.pano, panos, nearPanos, cameraDirLocals , Infinity, true);
  64098. let dlCount = browser.isMobile() ? 1 : 2;
  64099. let loadingCount = panos.filter(p=>p.depthTexLoading).length;
  64100. if(viewer.mapViewer){
  64101. let mapLayer = viewer.mapViewer.mapLayer;
  64102. loadingCount += mapLayer.loadingInProgress * 1.5 + mapLayer.waitQueue.length;
  64103. }
  64104. if(loadingCount<dlCount){
  64105. nearPanos.filter(p=>!p.depthTex).slice(0, dlCount-loadingCount).forEach(p=>p.loadDepthImg());
  64106. }
  64107. this.nearPanos = nearPanos;
  64108. };
  64109. TilePrioritizer.prototype.filterAndPrioritize = function () {//挑选出优先加载的 pano和tile (有点复杂,没看很懂)
  64110. var e = [],
  64111. t = [],
  64112. i = [];
  64113. return function (queue, panos, tileDownloader) {
  64114. //this.populateNeighborPanos(this.priorityCriteria.pano, panos, e);
  64115. /* let cameraDirLocals = this.priorityCriteria.cameraDirs.map(e=>{ //add
  64116. var dataset = viewer.scene.pointclouds.find(u=>u.dataset_id == e.datasetId)
  64117. var matrix = new THREE.Matrix4().copy(dataset.rotateMatrix)
  64118. var direction = math.convertVector.YupToZup(e.direction)
  64119. return {
  64120. datasetId:e.datasetId,
  64121. direction: direction.clone().applyMatrix4(matrix)
  64122. }
  64123. }) */
  64124. let cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  64125. //获得视野范围内的邻近点位序列t
  64126. this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals , TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER);
  64127. //t.filter(p=>!p.depthTex).slice(0, Potree.config.depTexDlCount).forEach(p=>p.loadDepthImg()) //add
  64128. var s = this.baseSize //512
  64129. ,
  64130. l = this.standardSize //1024
  64131. ,
  64132. c = this.highSize //2048
  64133. ,
  64134. h = this.ultraHighSize; //4096
  64135. this.queueTilesForPano(queue, tileDownloader, this.priorityCriteria.pano, s); //把当前pano的512下载了
  64136. if (this.priorityCriteria.upcomingPanos) {// 添加即将走到的点(之前用于导览路线)512 tiles
  64137. this.queueTilesForPanos(queue, this.priorityCriteria.upcomingPanos, tileDownloader, s, TilePrioritizer.MAX_UPCOMING_PANOS_TOADD);
  64138. }
  64139. i.length = 0;
  64140. //把当前pano角度范围内的tile按照分辨率从低到高加入队列
  64141. if (this.canDownloadSize(l)) {//1024如果在限制范围内的话
  64142. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  64143. }
  64144. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序
  64145. TilePrioritizer.appendQueue(queue, i);
  64146. //添加邻近点t 512的tiles
  64147. this.queueTilesForPanos(queue, t, tileDownloader, s, TilePrioritizer.MAX_SCORED_PANOS_TOADD);
  64148. i.length = 0;
  64149. //NARROW :
  64150. if (this.canDownloadSize(c)) {//2048
  64151. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  64152. }
  64153. if (this.canDownloadSize(h)) {//4096
  64154. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  64155. }
  64156. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs);//排序
  64157. TilePrioritizer.appendQueue(queue, i);
  64158. i.length = 0;
  64159. if (this.canDownloadSize(l)) {//1024
  64160. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  64161. }
  64162. if (this.canDownloadSize(c)) {//2048
  64163. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  64164. }
  64165. if (this.canDownloadSize(h)) {//4096
  64166. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  64167. }
  64168. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs);//排序
  64169. TilePrioritizer.appendQueue(queue, i);
  64170. this.queueTilesForPanos(queue, e, tileDownloader, s); // 如果前面有populateNeighborPanos的话,这步就是加neibour
  64171. }
  64172. }();
  64173. TilePrioritizer.prototype.queueTilesInDirectionForPano = function () {
  64174. var e = {
  64175. filter: h.DirectionalFOV,
  64176. direction: new Vector3,
  64177. fov: 60
  64178. },
  64179. t = new Vector3;
  64180. return function (i, n, pano, o, a, dirs, c) {
  64181. var dir = dirs.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  64182. //var dir = dirs
  64183. t.copy(dir);
  64184. TileUtils.getRelativeDirection(pano.quaternion4dkk, t);
  64185. e.direction.copy(t);
  64186. e.fov = c;
  64187. return this.filterAndQueueTileDownloadDescriptors(i, n, pano, o, e)
  64188. }
  64189. }();
  64190. TilePrioritizer.prototype.filterAndQueueTileDownloadDescriptors = function () {
  64191. var e = [];
  64192. return function (t, i, n, r, o) {
  64193. var a = i.getTileDownloadDescriptors(n, r);
  64194. e.length = 0,
  64195. this.filterTileDownloadDescriptors(n, a, e, o);
  64196. for (var s = 0, l = 0; l < e.length; l++) {
  64197. var c = e[l];
  64198. if (c) {
  64199. t.push(c);
  64200. s++;
  64201. }
  64202. }
  64203. return s
  64204. }
  64205. }();
  64206. TilePrioritizer.prototype.filterTileDownloadDescriptors = function () {
  64207. new Vector3;
  64208. return function (e, t, i, n) {
  64209. var r, o;
  64210. switch (n.filter) {
  64211. case h.DirectionalFOV:
  64212. for (r = 0; r < t.length; r++)
  64213. o = t[r],
  64214. TileUtils.isTileWithinFOV(o.panoSize, o.tileSize, o.face, o.tileX, o.tileY, n.direction, n.fov) && i.push(o);
  64215. break;
  64216. default:
  64217. for (r = 0; r < t.length; r++)
  64218. o = t[r],
  64219. i.push(o);
  64220. }
  64221. for (r = 0; r < i.length; r++)
  64222. o = i[r],
  64223. this.canIncludeDescriptor(o) || (i[r] = null);
  64224. }
  64225. }();
  64226. TilePrioritizer.prototype.queueTilesForPano = function () {
  64227. var e = {
  64228. filter: h.None
  64229. };
  64230. return function (t, i, n, r) {
  64231. return this.filterAndQueueTileDownloadDescriptors(t, i, n, r, e)
  64232. }
  64233. }();
  64234. /* TilePrioritizer.prototype.queueTilesForPanosInDirection = function () { //没用到
  64235. var e = new THREE.Vector3;
  64236. return function (t, i, n, r, o, a, s, l) {
  64237. for (var h = 0, u = 0; u < n.length; u++) {
  64238. var d = n[u];
  64239. e.copy(d.position),
  64240. e.sub(o),
  64241. e.normalize();
  64242. var p = Math.max(Math.min(a.dot(e), 1), -1),
  64243. f = c.getFOVDotThreshold(s);
  64244. if (p >= f) {
  64245. var g = this.queueTilesInDirectionForPano(t, i, d, r, o, a, s);
  64246. if (h += g > 0 ? 1 : 0,
  64247. l && h >= l)
  64248. break
  64249. }
  64250. }
  64251. return h
  64252. }
  64253. }() */
  64254. //import { i18n } from "@/lang/index"
  64255. // 媒体名称
  64256. /* export const mediaTypes = {
  64257. image: i18n.t("common.photo"),
  64258. video: i18n.t("common.video"),
  64259. audio: i18n.t("common.voice"),
  64260. } */
  64261. // 媒体扩展类型
  64262. const mediaMimes = {
  64263. image: ["jpg", "png", "jpeg", "bmp", "gif"],
  64264. audio: ["mp3", "aac", "ogg", "wav" /* , "m4a" */],
  64265. video: ["mp4", "mov", "quicktime", "webm" /* "rmvb", "wmv" */], //ios:mov
  64266. };
  64267. // 媒体大小显示(MB)
  64268. const mediaMaxSize = {
  64269. image: 10,
  64270. video: 20,
  64271. audio: 5,
  64272. };
  64273. /**
  64274. * 获取媒体扩展类型
  64275. * @param {Stirng} filename 文件名称
  64276. */
  64277. const getMime = filename => {
  64278. if (!filename || filename.indexOf(".") === -1) {
  64279. return ""
  64280. }
  64281. return filename
  64282. .split(".")
  64283. .pop()
  64284. .toLowerCase()
  64285. };
  64286. /**
  64287. * 在路径中获取文件名
  64288. * @param {*} path
  64289. */
  64290. const getFilename = path => {
  64291. const segment = (path || "").split("/");
  64292. return segment[segment.length - 1]
  64293. };
  64294. /**
  64295. * 检测媒体文件是否超过预设限制
  64296. * @param {String} type 媒体类型
  64297. * @param {Number} size 文件大小
  64298. */
  64299. const checkSizeLimit = (type, size) => {
  64300. size = size / 1024 / 1024;
  64301. return size <= mediaMaxSize[type]
  64302. };
  64303. const checkSizeLimitFree = (size, limit) => {
  64304. size = size / 1024 / 1024;
  64305. return size <= limit
  64306. };
  64307. /**
  64308. * 检测媒体类型
  64309. * @param {String} type 媒体类型
  64310. * @param {String} filename 文件名称
  64311. */
  64312. const checkMediaMime = (type, filename) => {
  64313. const mime = getMime(filename);
  64314. const find = mediaMimes[type];
  64315. if (!find) {
  64316. return false
  64317. }
  64318. return find.indexOf(mime) !== -1
  64319. };
  64320. const checkMediaMimeByAccept = (accept, filename) => {
  64321. let mime = getMime(filename);
  64322. let type = accept;
  64323. if (type && type.indexOf("jpg") == -1 && type.indexOf("jpeg") != -1) {
  64324. type += ",image/jpg";
  64325. }
  64326. return (type || "").indexOf(mime) != -1
  64327. };
  64328. const base64ToBlob = base64 => {
  64329. let arr = base64.split(","),
  64330. mime = arr[0].match(/:(.*?);/)[1],
  64331. bstr = atob(arr[1]),
  64332. n = bstr.length,
  64333. u8arr = new Uint8Array(n);
  64334. while (n--) {
  64335. u8arr[n] = bstr.charCodeAt(n);
  64336. }
  64337. return new Blob([u8arr], { type: mime })
  64338. };
  64339. const base64ToDataURL = base64 => {
  64340. return window.URL.createObjectURL(base64ToBlob(base64))
  64341. };
  64342. const blobToBase64 = function(blob) {
  64343. return new Promise(resolve => {
  64344. var reader = new FileReader();
  64345. reader.onload = function() {
  64346. resolve(reader.result);
  64347. };
  64348. reader.readAsDataURL(blob);
  64349. })
  64350. };
  64351. /*
  64352. * @Author: Rindy
  64353. * @Date: 2019-08-06 16:25:08
  64354. * @LastEditors: Rindy
  64355. * @LastEditTime: 2021-08-27 12:33:49
  64356. * @Description: Request
  64357. */
  64358. //import { $alert, $confirm, $loginTips } from "@/components/shared/message"
  64359. //import { $waiting } from "@/components/shared/loading"
  64360. //import { checkLogin } from "@/api"
  64361. //import { LoginDetector } from "@/core/starter"
  64362. //import { i18n } from "@/lang"
  64363. //import { password } from "@/utils/string"
  64364. //import store from "../Store"
  64365. // 空函数
  64366. const noop = function() {};
  64367. // 请求回调队列
  64368. let postQueue = [];
  64369. /**
  64370. * @property {number} NEXT - 继续执行
  64371. * @property {number} SUCCESS - 成功
  64372. * @property {number} EXCEPTION - 异常错误
  64373. * @property {number} FAILURE_CODE_3001 - 缺少必要参数
  64374. * @property {number} FAILURE_CODE_3002 - 访问异常
  64375. * @property {number} FAILURE_CODE_3003 - 非法访问
  64376. * @property {number} FAILURE_CODE_3004 - 用户未登录
  64377. * @property {number} FAILURE_CODE_3005 - 验证码已过期
  64378. * @property {number} FAILURE_CODE_3006 - 验证码错误
  64379. * @property {number} FAILURE_CODE_3007 - 昵称已存在
  64380. * @property {number} FAILURE_CODE_3008 - 该手机已被注册
  64381. * @property {number} FAILURE_CODE_3009 - 两次输入的密码不一致
  64382. * @property {number} FAILURE_CODE_3010 - 昵称长度错误
  64383. * @property {number} FAILURE_CODE_3011 - 密码长度错误
  64384. * @property {number} FAILURE_CODE_3012 - 昵称包含敏感词
  64385. * @property {number} FAILURE_CODE_3013 - 手机号码格式错误
  64386. * @property {number} FAILURE_CODE_3014 - 账号或密码不正确
  64387. * @property {number} FAILURE_CODE_3015 - 用户不存在
  64388. * @property {number} FAILURE_CODE_3016 - 您没有权限,请联系管理员
  64389. * @property {number} FAILURE_CODE_3017 - 空文件
  64390. * @property {number} FAILURE_CODE_3018 - 需要上传或使用的文件不存在
  64391. * @property {number} FAILURE_CODE_5010 - 找不到该场景对应的相机
  64392. * @property {number} FAILURE_CODE_5012 - 数据不正常
  64393. * @property {number} FAILURE_CODE_5014 - 无权操作该场景
  64394. * @property {number} FAILURE_CODE_5005 - 场景不存在
  64395. */
  64396. const statusCode = {
  64397. NEXT: -999,
  64398. SUCCESS: 0,
  64399. EXCEPTION: -1,
  64400. FAILURE_CODE_3001: 3001,
  64401. FAILURE_CODE_3002: 3002,
  64402. FAILURE_CODE_3003: 3003,
  64403. FAILURE_CODE_3004: 3004,
  64404. FAILURE_CODE_3005: 3005,
  64405. FAILURE_CODE_3006: 3006,
  64406. FAILURE_CODE_3007: 3007,
  64407. FAILURE_CODE_3008: 3008,
  64408. FAILURE_CODE_3009: 3009,
  64409. FAILURE_CODE_3010: 3010,
  64410. FAILURE_CODE_3011: 3011,
  64411. FAILURE_CODE_3012: 3012,
  64412. FAILURE_CODE_3013: 3013,
  64413. FAILURE_CODE_3014: 3014,
  64414. FAILURE_CODE_3015: 3015,
  64415. FAILURE_CODE_3016: 3016,
  64416. FAILURE_CODE_3017: 3017,
  64417. FAILURE_CODE_3018: 3018,
  64418. FAILURE_CODE_5010: 5010,
  64419. FAILURE_CODE_5012: 5012,
  64420. FAILURE_CODE_5014: 5014,
  64421. FAILURE_CODE_5005: 5005,
  64422. };
  64423. /**
  64424. * 获取Token
  64425. * @function
  64426. */
  64427. function getToken() {
  64428. var urlToken = browser.urlHasValue("token", true);
  64429. if (urlToken) {
  64430. // 设置token共享给用户中心
  64431. localStorage.setItem("token", urlToken);
  64432. }
  64433. return urlToken || localStorage.getItem("token") || ""
  64434. }
  64435. /**
  64436. * 根据状态码的结果处理后续操作
  64437. * @function
  64438. * @param {number} code - 状态码
  64439. * @param {function} callback - 回调
  64440. */
  64441. function statusCodesHandler(code, callback) {
  64442. if (code == statusCode.EXCEPTION) {
  64443. return $alert({ content: i18n.t("tips.exception") })
  64444. }
  64445. if (
  64446. code == statusCode.FAILURE_CODE_3002 ||
  64447. code == statusCode.FAILURE_CODE_3003 ||
  64448. code == statusCode.FAILURE_CODE_3004
  64449. ) {
  64450. callback(code);
  64451. return showLoginTips()
  64452. }
  64453. if (code == statusCode.FAILURE_CODE_3001) {
  64454. callback(code);
  64455. return $alert({ content: i18n.t("tips.params_notfound") })
  64456. }
  64457. if (code == statusCode.FAILURE_CODE_3017) {
  64458. callback(code);
  64459. return $alert({ content: i18n.t("tips.file_notfound") })
  64460. }
  64461. if (code == statusCode.FAILURE_CODE_5005) {
  64462. /* if (!config.isEdit) {
  64463. return (location.href = config.pages.NotFound)
  64464. } */
  64465. callback(code);
  64466. return $alert({ content: i18n.t("tips.scene_notfound") })
  64467. }
  64468. if (code == statusCode.FAILURE_CODE_5010) {
  64469. callback(code);
  64470. return $alert({ content: i18n.t("tips.camera_notfound") })
  64471. }
  64472. if (code == statusCode.FAILURE_CODE_5012) {
  64473. callback(code);
  64474. return $alert({ content: i18n.t("tips.data_error") })
  64475. }
  64476. if (code == statusCode.FAILURE_CODE_5014) {
  64477. callback(code);
  64478. return $alert({ content: i18n.t("tips.auth_deny") })
  64479. }
  64480. return statusCode.NEXT
  64481. }
  64482. $.ajaxSetup({
  64483. headers: {},
  64484. beforeSend: function(xhr) {
  64485. const token = getToken();
  64486. if (token) {
  64487. xhr.setRequestHeader("token", token);
  64488. } else if (!token && this.url.indexOf("isLogin") != -1) {
  64489. showLoginTips();
  64490. }
  64491. /* if (config.oem == "localshow") {
  64492. // 本地版本兼容当前目录
  64493. if (this.url.indexOf("http") == -1 && this.url.indexOf("/") == 0) {
  64494. this.url = this.url.substr(1)
  64495. }
  64496. } */
  64497. // if(this.url.indexOf('http')==-1 && this.url.indexOf('/') !=0){
  64498. // this.url = '/'+this.url
  64499. // }
  64500. },
  64501. error: function(xhr, status, error) {
  64502. // 出错时默认的处理函数
  64503. if (this.url.indexOf("/scene.json") != -1 && xhr.status == 404) {
  64504. return $alert({ content: i18n.t("tips.scene_notfound") })
  64505. } else if (this.type === "POST") {
  64506. return $alert({ content: i18n.t("tips.network_error") })
  64507. }
  64508. },
  64509. success: function(result) {},
  64510. complete: function() {
  64511. // Post类型请求无论成功或失败都关闭等待提示
  64512. if (this.type === "POST") {
  64513. http.__loading && $waiting.hide();
  64514. }
  64515. http.__loading = true;
  64516. },
  64517. });
  64518. /**
  64519. * @namespace http
  64520. * @type {Object}
  64521. */
  64522. const http = {
  64523. statusCode,
  64524. __loading: true,
  64525. __request(xhr, method, url, data, done, fail) {
  64526. if (typeof done != "function") {
  64527. done = noop;
  64528. }
  64529. if (typeof fail != "function") {
  64530. fail = noop;
  64531. }
  64532. xhr.done(result => {
  64533. if (typeof result.code !== "undefined") {
  64534. const flag = statusCodesHandler(result.code, function(code) {
  64535. // 需要登录的状态
  64536. if (
  64537. code == statusCode.FAILURE_CODE_3001 ||
  64538. code == statusCode.FAILURE_CODE_3002 ||
  64539. code == statusCode.FAILURE_CODE_3003 ||
  64540. code == statusCode.FAILURE_CODE_3004
  64541. ) {
  64542. if (url.indexOf("isLogin") == -1 && url.indexOf("openSceneBykey") == -1) {
  64543. postQueue.push(function() {
  64544. http[method](url, data, done, fail);
  64545. });
  64546. }
  64547. }
  64548. fail();
  64549. });
  64550. if (flag === statusCode.NEXT) {
  64551. done(result, result.code == 0);
  64552. }
  64553. } else {
  64554. done(result);
  64555. }
  64556. });
  64557. xhr.fail(fail);
  64558. xhr.always(() => (xhr = null));
  64559. return xhr
  64560. },
  64561. /**
  64562. * Get请求
  64563. * @param {String} url 请求地址
  64564. * @param {Object?} data 请求参数
  64565. * @param {Function?} done 成功回调
  64566. * @param {Function?} fail 失败回调
  64567. */
  64568. get(url, data = {}, done, fail) {
  64569. if (/\.json/.test(url)) {
  64570. // json文件格式自动调用getJson方法
  64571. return this.getJson(url, data, done, fail)
  64572. }
  64573. return this.__request($.get(url, data), "get", url, data, done, fail)
  64574. },
  64575. /**
  64576. * Get Blob请求
  64577. * @param {String} url 请求地址
  64578. * @param {Object?} data 请求参数
  64579. * @param {Function?} done 成功回调
  64580. * @param {Function?} fail 失败回调
  64581. */
  64582. getText(url, data = {}, done, fail) {
  64583. return this.__request(
  64584. $.ajax({
  64585. url: url,
  64586. dataType: "text",
  64587. }),
  64588. "getText",
  64589. url,
  64590. data,
  64591. done,
  64592. fail
  64593. )
  64594. },
  64595. /**
  64596. * GetJson请求 读取json文件数据
  64597. * @param {String} url 请求地址
  64598. * @param {Object?} data 请求参数
  64599. * @param {Function?} done 成功回调
  64600. * @param {Function?} fail 失败回调
  64601. */
  64602. getJson(url, data = {}, done, fail) {
  64603. return this.__request($.getJSON(url, data), "get", url, data, done, fail)
  64604. },
  64605. /**
  64606. * Get Blob请求
  64607. * @param {String} url 请求地址
  64608. * @param {Object?} data 请求参数
  64609. * @param {Function?} done 成功回调
  64610. * @param {Function?} fail 失败回调
  64611. */
  64612. getBlob(url, data = {}, done, fail) {
  64613. return this.__request(
  64614. $.ajax({
  64615. url: url,
  64616. dataType: "blob",
  64617. }),
  64618. "getBlob",
  64619. url,
  64620. data,
  64621. done,
  64622. fail
  64623. )
  64624. },
  64625. /**
  64626. * Get Arraybuffer请求
  64627. * @param {String} url 请求地址
  64628. * @param {Object?} data 请求参数
  64629. * @param {Function?} done 成功回调
  64630. * @param {Function?} fail 失败回调
  64631. */
  64632. getArraybuffer(url, data = {}, done, fail) {
  64633. return this.__request(
  64634. $.ajax({
  64635. url: url,
  64636. dataType: "arraybuffer",
  64637. }),
  64638. "getArraybuffer",
  64639. url,
  64640. data,
  64641. done,
  64642. fail
  64643. )
  64644. },
  64645. /**
  64646. * Post 请求
  64647. * @param {String} url 请求地址
  64648. * @param {Object?} data 请求参数
  64649. * @param {Function?} done 成功回调
  64650. * @param {Function?} fail 失败回调
  64651. */
  64652. post(url, data = {}, done, fail) {
  64653. if (url.indexOf("isLogin") == -1) {
  64654. http.__loading && $waiting.show();
  64655. }
  64656. return this.__request($.post(url, data), "post", url, data, done, fail)
  64657. },
  64658. /**
  64659. * PostJson 请求
  64660. * @param {String} url 请求地址
  64661. * @param {Object?} data 请求参数
  64662. * @param {Function?} done 成功回调
  64663. * @param {Function?} fail 失败回调
  64664. */
  64665. postJson(url, data = {}, done, fail) {
  64666. http.__loading && $waiting.show();
  64667. return this.__request(
  64668. $.ajax({
  64669. type: "POST",
  64670. url: url,
  64671. contentType: "application/json",
  64672. data: JSON.stringify(data),
  64673. }),
  64674. "postJson",
  64675. url,
  64676. data,
  64677. done,
  64678. fail
  64679. )
  64680. },
  64681. /**
  64682. * Post 表单 支持文件上传
  64683. * @param {String} url 请求地址
  64684. * @param {FormData?} formData 请求参数
  64685. * @param {Function?} done 成功回调
  64686. * @param {Function?} fail 失败回调
  64687. */
  64688. postForm(url, formData, done, fail, onProgress) {
  64689. if (typeof onProgress === "function") {
  64690. return this.__request(
  64691. $.ajax({
  64692. type: "POST",
  64693. url: url,
  64694. processData: false,
  64695. contentType: false,
  64696. data: formData,
  64697. xhr: function() {
  64698. const xhr = new XMLHttpRequest();
  64699. xhr.upload.addEventListener("progress", function(e) {
  64700. onProgress((e.loaded / e.total) * 100 + "%");
  64701. });
  64702. return xhr
  64703. },
  64704. }),
  64705. "postForm",
  64706. url,
  64707. formData,
  64708. done,
  64709. fail
  64710. )
  64711. } else {
  64712. http.__loading && $waiting.show();
  64713. return this.__request(
  64714. $.ajax({
  64715. type: "POST",
  64716. url: url,
  64717. processData: false,
  64718. contentType: false,
  64719. data: formData,
  64720. }),
  64721. "postForm",
  64722. url,
  64723. formData,
  64724. done,
  64725. fail
  64726. )
  64727. }
  64728. },
  64729. /**
  64730. * 加载图片
  64731. * @param {String} url 请求地址
  64732. * @param {Number?} retry 重试次数,默认为3
  64733. */
  64734. loadImage(url, retry = 3) {
  64735. const def = $.Deferred();
  64736. const img = new Image();
  64737. /* if (process.env.VUE_APP_REGION == "AWS" && url.indexOf("x-oss-process=image") != -1) {
  64738. var arr = url.split("?")
  64739. url = arr[0] + encodeURIComponent("?" + arr[1].replace(/\//g, "@"))
  64740. } */
  64741. const load = () => {
  64742. console.warn("Retrying load image: " + url);
  64743. this.loadImage(url, retry - 1)
  64744. .done(def.resolve.bind(def))
  64745. .progress(def.notify.bind(def))
  64746. .fail(def.reject.bind(def));
  64747. };
  64748. img.onerror = function() {
  64749. retry > 0 ? setTimeout(() => load(), 1e3) : def.reject(`[${url}]加载失败`);
  64750. };
  64751. img.onload = function() {
  64752. def.resolve(img);
  64753. };
  64754. img.crossOrigin = "anonymous";
  64755. img.src = url;
  64756. return def
  64757. },
  64758. /**
  64759. * 上传文件
  64760. * @param {String} url 请求地址
  64761. * @param {Object?} data 请求参数
  64762. * @param {Function?} done 成功回调
  64763. * @param {Function?} fail 失败回调
  64764. */
  64765. uploadFile(url, data = {}, done, fail, onProgress) {
  64766. const form = new FormData();
  64767. // if (file.needTransfer) { //ie和苹果都不支持dataURLtoFile得传送,所以只能用blob
  64768. // form.append("file", common.dataURLtoBlob(file.file), file.name || file.file.name);
  64769. // } else {
  64770. // form.append("file", file.file, file.name || file.file.name);
  64771. // }
  64772. for (let key in data) {
  64773. if (key == "file") {
  64774. form.append("file", data[key], data.filename || data[key].name);
  64775. } else if (key != "filename") {
  64776. form.append(key, data[key]);
  64777. }
  64778. }
  64779. return this.postForm(url, form, done, fail, onProgress)
  64780. },
  64781. /**
  64782. * 上传文件
  64783. * @param {String} url 请求地址
  64784. * @param {Object?} data 请求参数 {file:'base64 string',filename:'image.jpg',...}
  64785. * @param {Function?} done 成功回调
  64786. * @param {Function?} fail 失败回调
  64787. */
  64788. uploadBlobFile(url, data = {}, done, fail) {
  64789. const form = new FormData();
  64790. for (let key in data) {
  64791. if (key === "file") {
  64792. form.append("file", base64ToBlob(data.file), data.filename);
  64793. } else if (key != "filename") {
  64794. form.append(key, data[key]);
  64795. }
  64796. }
  64797. return this.postForm(url, form, done, fail)
  64798. },
  64799. };
  64800. let {TileDownloaderEvents, DownloadStatus: DownloadStatus$1} = Potree.defines;
  64801. window.downloaded = {};
  64802. window.startdownloads = [];
  64803. class TileDownloader extends EventDispatcher{
  64804. constructor( ) {
  64805. super();
  64806. this.panos = null;
  64807. this.retryMinimumTime = 1e4;
  64808. this.panoLoadCallbacks = {};
  64809. this.downloadDescriptors = {};
  64810. this.priorityQueue = [];
  64811. this.forceQueue = [];
  64812. this.activeDownloads = [];
  64813. this.tilePrioritizer = null;
  64814. this.refreshInterval = null;
  64815. this.processPriorityQueue = !1;
  64816. this.concurrentDownloads = 6;//e.concurrentDownloads || 1;
  64817. this.downloadTestResults = {};
  64818. this.freeze = Object.freeze({
  64819. Testing: 1,
  64820. Success: 2,
  64821. Fail: 3
  64822. });
  64823. /* viewer.addEventListener('pageVisible', (e)=>{//不可见时不refreshUpdateInterval
  64824. //console.log('visibilitychange:', state)
  64825. Potree.Utils.updateVisible(this, 'pageVisible', e.v)
  64826. this.judgeStart()
  64827. })
  64828. this.visible = true //add 借用Potree.Utils.updateVisible来判断是否start
  64829. if(Potree.settings.useDepthTex){
  64830. this.judgeStart() //开始下载depthTex
  64831. }else{
  64832. Potree.Utils.updateVisible(this,'showPanos', false ) //默认visible = false
  64833. } */
  64834. }
  64835. setPanoData(e, t /* , i */) {
  64836. this.panos = e,
  64837. this.imagePanos = t;
  64838. // this.panoGroupId = i
  64839. }
  64840. start() {
  64841. this.downloadCubeTex = true;
  64842. /* if(!Potree.settings.useDepthTex){
  64843. Potree.Utils.updateVisible(this,'showPanos', true )
  64844. this.judgeStart()
  64845. }else{
  64846. //this.refreshInterval || this.judgeStart()
  64847. } */
  64848. }
  64849. stop() {
  64850. this.downloadCubeTex = false;
  64851. /* if(!Potree.settings.useDepthTex){
  64852. Potree.Utils.updateVisible(this,'showPanos', false )
  64853. this.judgeStart()
  64854. } */
  64855. }
  64856. /* judgeStart(){//add
  64857. if(this.visible){
  64858. //console.log('judgeStart true')
  64859. this.started = true
  64860. //this.refreshUpdateInterval(0)
  64861. }else{
  64862. //console.log('judgeStart false')
  64863. this.started = false
  64864. //window.clearTimeout(this.refreshInterval)
  64865. }
  64866. } */
  64867. /* refreshUpdateInterval(e) {
  64868. e || (e = 0),
  64869. this.refreshInterval = window.setTimeout(function() {
  64870. var e = this.update();
  64871. e ? this.refreshUpdateInterval(TileDownloader.ACTIVE_REFRESH_DELAY) : this.refreshUpdateInterval(TileDownloader.IDLE_REFRESH_DELAY)
  64872. }
  64873. .bind(this), e)
  64874. } */
  64875. update() {
  64876. if(this.downloadCubeTex){ //可以下载贴图
  64877. var e = this.forceQueue.length > 0;
  64878. this.processQueueForDownloading(this.forceQueue);
  64879. if (this.processPriorityQueue) {
  64880. Potree.Common.intervalTool.isWaiting('processPriorityQueue', ()=>{ //延时update,防止崩溃 , 未到时间就拦截(第一次直接执行)
  64881. this.queuePrioritizedTilesForPanos(this.panos); //这句比较耗时 降四倍时大概1-2毫秒
  64882. }, 66);
  64883. this.priorityQueue.length > 0 && (e = !0);
  64884. this.processQueueForDownloading(this.priorityQueue);
  64885. }
  64886. //return e
  64887. }
  64888. Potree.Common.intervalTool.isWaiting('filterDepthTex', ()=>{
  64889. this.tilePrioritizer.filterDepthTex(this.panos);//下载深度图
  64890. }, 77);
  64891. }
  64892. queuePrioritizedTilesForPanos(e) {
  64893. this.tilePrioritizer && (this.clearQueue(this.priorityQueue),
  64894. this.tilePrioritizer.filterAndPrioritize(this.priorityQueue, e, this),
  64895. this.clearFromQueue(this.priorityQueue, DownloadStatus$1.None, !0), //去除state为DownloadStatus.None的(可能是去除已经在下载的)
  64896. this.setStatusOrRemoveForAllDescriptors(this.priorityQueue, DownloadStatus$1.Queued));
  64897. }
  64898. clearQueue(e) {//停止下载并清空
  64899. this.setStatusForAllDescriptors(e, DownloadStatus$1.None),
  64900. e.length = 0;
  64901. }
  64902. clearForceQueue() {
  64903. this.clearQueue(this.forceQueue);
  64904. }
  64905. clearFromQueue(e, t, i) {
  64906. for (var n = 0; n < e.length; n++) {
  64907. var r = e[n];
  64908. r && (t === r.status && !i || t !== r.status && i) && (e[n] = null);
  64909. }
  64910. }
  64911. setStatusForAllDescriptors(e, t) {
  64912. for (var i = 0; i < e.length; i++) {
  64913. var n = e[i];
  64914. n && (n.status = t);
  64915. }
  64916. }
  64917. setStatusOrRemoveForAllDescriptors(e, t) {
  64918. for (var i = 0; i < e.length; i++) {
  64919. var n = e[i];
  64920. n && (n.status !== t ? n.status = t : e[i] = null);
  64921. }
  64922. }
  64923. getTileDownloadDescriptors(pano, size) {//获取该pano的该size的全部的tile的descriptor
  64924. var i = this.getAllTileDownloadDescriptorsForPano(pano),
  64925. n = i[size];
  64926. return n || (n = this.buildDownloadDescriptorArray(size),//创建的全部是空的
  64927. i[size] = n,
  64928. this.initTileDownloadDescriptors(n, pano, size)),//绑定到该pano size
  64929. n
  64930. }
  64931. getAllTileDownloadDescriptorsForPano(pano) {//新建空Descriptors
  64932. var t = this.downloadDescriptors[pano.id];
  64933. return t || (t = {},
  64934. this.downloadDescriptors[pano.id] = t),
  64935. t
  64936. }
  64937. processQueueForDownloading(e, t) {//执行下载任务
  64938. this.cleanupActiveDownloads();
  64939. if(e.length){
  64940. let concurrentDownloads = Potree.Common.getBestCount('concurrentDownloads',1,6, 1.8, 14/* ,true */); //flying ? (isMobile ? 2 : 3) : 6
  64941. if (this.activeDownloads.length < concurrentDownloads || t) {
  64942. var i = t ? e.length : concurrentDownloads - this.activeDownloads.length;
  64943. for (var n = 0, r = 0; n < i && e.length > 0; r++) {
  64944. var o = e.shift();
  64945. if(o){
  64946. //add 为了防止1024的在512前下载完,这里强行等待512下载完毕再开始下载
  64947. if(o.panoSize > 512 && !this.isPanoDownloaded(o.pano, 512) ){
  64948. //console.log('512的还没下载好呢!')
  64949. e.push(o);
  64950. break;//一般512的都是连续下载的,所以后面就都不是512了直接中断
  64951. }
  64952. this.startDownload(o);
  64953. n++;
  64954. }
  64955. }
  64956. }
  64957. }
  64958. }
  64959. testDownload(panoSize, tileSize, callback) {
  64960. var n = this.downloadTestResults[panoSize];
  64961. if (n)
  64962. return void(n === this.freeze.Success ? callback(!0) : n === this.freeze.Fail && callback(!1));
  64963. this.downloadTestResults[panoSize] = this.freeze.Testing;
  64964. var r = this.panos[0],
  64965. o = this.getTileUrl({pano:r, panoSize, tileSize, tileIndex:0} /* r.id, panoSize, tileSize, 0 */),
  64966. a = function(t) {
  64967. this.downloadTestResults[panoSize] = this.freeze.Success,
  64968. callback(!0);
  64969. }
  64970. .bind(this),
  64971. s = function() {
  64972. this.downloadTestResults[panoSize] = this.freeze.Fail,
  64973. callback(!1);
  64974. }
  64975. .bind(this);
  64976. this.loadImage(o, 0, a, s);
  64977. }
  64978. startDownload(e) {//开始下载啦
  64979. //console.log('startDownload')
  64980. startdownloads.push(e);
  64981. e.local2SrcFailed = this.local2SrcFailed;
  64982. e.status = DownloadStatus$1.Downloading;
  64983. var t = this.getTileUrl(e/* e.pano.id, e.panoSize, e.tileSize, e.tileIndex, e.pano.alignmentType */);//xzw add alignmentType
  64984. if(!t)return;
  64985. this.activeDownloads.push(e);
  64986. this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e));
  64987. }
  64988. downloadFailed(e, t) {
  64989. //add
  64990. if(Potree.settings.isLocal2 && !e.local2SrcFailed){//为了兼容旧的数据src,如果新src没加载成功,就加载旧的
  64991. e.local2SrcFailed = this.local2SrcFailed = true;
  64992. //this.startDownload(e)//重新下载
  64993. var t = this.getTileUrl(e);
  64994. this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e));
  64995. }
  64996. }
  64997. downloadComplete(e, t) {//下载成功时
  64998. //if (e.panoGroupId === this.panoGroupId) {
  64999. var i = this.getPanoLoadCallbacks(e.pano, e.panoSize);
  65000. e.status = DownloadStatus$1.Downloaded,
  65001. i && i.onProgress && i.onProgress(e.pano, e.panoSize);
  65002. var n = {
  65003. panoId: e.pano.id,
  65004. image: t,
  65005. tileSize: e.tileSize,
  65006. panoSize: e.panoSize,
  65007. tileIndex: e.tileIndex,
  65008. faceTileIndex: e.faceTileIndex,
  65009. totalTiles: e.totalTiles,
  65010. face: e.face,
  65011. tileX: e.tileX,
  65012. tileY: e.tileY,
  65013. direction: e.direction
  65014. };
  65015. downloaded[e.pano.id] || (downloaded[e.pano.id]={512:[],1024:[],2048:[]});
  65016. downloaded[e.pano.id][e.panoSize] || (downloaded[e.pano.id][e.panoSize] = []);
  65017. downloaded[e.pano.id][e.panoSize].push(e);
  65018. if(e.panoSize != 512 && downloaded[e.pano.id][512].length<6){
  65019. console.warn('没下完');
  65020. }
  65021. e.image = t,
  65022. this.dispatchEvent({type:TileDownloaderEvents.TileDownloadSuccess, desc:n} );
  65023. this.isPanoDownloaded(e.pano, e.panoSize) && (n = {
  65024. panoId: e.pano.id,
  65025. tileSize: e.tileSize,
  65026. panoSize: e.panoSize
  65027. },
  65028. this.dispatchEvent({type:TileDownloaderEvents.PanoDownloadComplete, desc:n}),
  65029. i && i.onLoad && i.onLoad(e.pano, e.panoSize));
  65030. //}
  65031. }
  65032. isPanoDownloaded(e, t) {
  65033. var i = this.getTileDownloadDescriptors(e, t);
  65034. if (i.length <= 0)
  65035. return !1;
  65036. for (var n = 0; n < i.length; n++) {
  65037. var r = i[n];
  65038. if (r.status !== DownloadStatus$1.Downloaded)
  65039. return !1
  65040. }
  65041. return !0
  65042. }
  65043. setPanoLoadCallbacks(e, t, i, n, r) {
  65044. var o = e.id + ":" + this.qualityManager.getPanoSize(t);
  65045. this.panoLoadCallbacks[o] = {
  65046. onLoad: i,
  65047. onFail: n,
  65048. onProgress: r
  65049. };
  65050. }
  65051. getPanoLoadCallbacks(e, t) {
  65052. var i = e.id + ":" + t;
  65053. return this.panoLoadCallbacks[i]
  65054. }
  65055. buildDownloadDescriptorArray(e) {
  65056. for (var t = TileUtils.getTileCountForSize(e), i = [], n = 0; n < t; n++) {
  65057. var r = this.buildDownloadDescriptor();
  65058. i.push(r);
  65059. }
  65060. return i
  65061. }
  65062. buildDownloadDescriptor() {//Descriptor!
  65063. var e = {
  65064. panoGroupId: null,
  65065. pano: null,
  65066. panoSize: -1,
  65067. tileSize: -1,
  65068. tileIndex: -1,
  65069. totalTiles: -1,
  65070. faceTileIndex: -1,
  65071. status: DownloadStatus$1.None,
  65072. url: null,
  65073. image: null,
  65074. direction: new Vector3, //该tile在cube中的方向
  65075. face: -1,
  65076. cubeFace: -1,
  65077. tileX: -1,
  65078. tileY: -1
  65079. };
  65080. return e
  65081. }
  65082. initTileDownloadDescriptors(e, t, i) {
  65083. for (var n = 0; n < e.length; n++) {
  65084. var r = e[n];
  65085. this.initTileDownloadDescriptor(r, t, i, n);
  65086. }
  65087. }
  65088. initTileDownloadDescriptor(desc, pano, size, index) {
  65089. var r = size >= TileUtils.TILE_SIZE ? TileUtils.TILE_SIZE : size;
  65090. desc.face = TileUtils.getFaceForTile(size, index);//根据顺序得到的face的index
  65091. desc.cubeFace = TileUtils.mapFaceToCubemapFace(desc.face);//为了贴图而转化的face index
  65092. //desc.panoGroupId = this.panoGroupId;//就是场景号
  65093. desc.pano = pano;
  65094. desc.panoSize = size;
  65095. desc.tileSize = r; //瓦片图size 512
  65096. desc.tileIndex = index;
  65097. desc.totalTiles = TileUtils.getTileCountForSize(size);
  65098. desc.status = DownloadStatus$1.None;
  65099. desc.image = null;
  65100. TileUtils.getTileLocation(desc.panoSize, desc.tileIndex, desc);//得到该tile在这个face中的具体位置(tileX等)
  65101. TileUtils.getTileVector(desc.panoSize, desc.tileSize, desc.cubeFace, desc.tileX, desc.tileY, TileUtils.LocationOnTile.Center, 0, desc.direction);
  65102. }
  65103. getTiles(d, sceneNum, useV4url, pointcloud){
  65104. if(Potree.settings.isLocal && !this.local2SrcFailed || useV4url){//新的地址 scene_view_data/场景码/images/tiles
  65105. if(pointcloud.datasetData.mapping && !Potree.settings.isLocal2){//非离线包的话加mapping
  65106. return `${Potree.settings.urls.prefix3}/${pointcloud.datasetData.mapping}/scene_view_data/${sceneNum}/images/${d}`
  65107. }else {
  65108. return `${Potree.settings.urls.prefix3}/scene_view_data/${sceneNum}/images/${d}`
  65109. }
  65110. }
  65111. return `${Potree.settings.urls.prefix3}/images/images${sceneNum}/${d}`
  65112. }
  65113. loadImage(e, t, i, n) {
  65114. //自己修改了ajax,把getImage改成了loadImg
  65115. http.loadImage(e, t).then(function(e) {
  65116. i(e);
  65117. }).fail(n);
  65118. }
  65119. }
  65120. TileDownloader.prototype.forceQueueTilesForPano = function() {//根据条件开始加载tile
  65121. var e = [],
  65122. t = [];
  65123. return function(pano, size, dir, hFov, vFov, download) {
  65124. e.length = 0;
  65125. for (var u = this.getTileDownloadDescriptors(pano, size), d = 0; d < u.length; d++) {
  65126. var p = u[d];
  65127. p.status !== DownloadStatus$1.None && p.status !== DownloadStatus$1.Queued || e.push(p);
  65128. }
  65129. if (dir && e.length > 0) {
  65130. TilePrioritizer.sortPanoTiles(e, pano, dir); //按最佳方向排序e
  65131. t.length = 0;
  65132. TileUtils.matchingTilesInDirection(pano, size, dir, hFov, vFov, t);//得到在符合视野标准的集合t
  65133. for (var f = 0, g = function(e) {
  65134. return e.face === m.face && e.faceTileIndex === m.faceTileIndex
  65135. }; f < e.length;) { //过滤掉不符合角度要求的
  65136. var m = e[f],
  65137. v = t.findIndex(g);
  65138. v < 0 ? e.splice(f, 1) : f++;
  65139. }
  65140. }
  65141. for (var A = 0; A < e.length; A++){
  65142. this.forceQueue.push(e[A]); //装载
  65143. }
  65144. /* if(e.length){
  65145. console.log(e)
  65146. } */
  65147. this.setStatusForAllDescriptors(this.forceQueue, DownloadStatus$1.ForceQueued);
  65148. this.clearFromQueue(this.priorityQueue, DownloadStatus$1.ForceQueued, !1);
  65149. download && this.processQueueForDownloading(this.forceQueue, !0);
  65150. }
  65151. }();
  65152. TileDownloader.prototype.cleanupActiveDownloads = function() {
  65153. var e = [];
  65154. return function() {
  65155. e.length = 0;
  65156. for (var t = 0; t < this.activeDownloads.length; t++) {
  65157. var i = this.activeDownloads[t];
  65158. i.status !== DownloadStatus$1.Downloaded && i.status !== DownloadStatus$1.Failed && e.push(i);
  65159. }
  65160. this.activeDownloads.length = 0,
  65161. this.activeDownloads.push.apply(this.activeDownloads, e);
  65162. }
  65163. }();
  65164. TileDownloader.prototype.getTileUrl = function() {
  65165. var e = {
  65166. 256: "256",
  65167. 512: "512",
  65168. 1024: "1k",
  65169. 2048: "2k",
  65170. 4096: "4k"
  65171. },
  65172. t = {
  65173. face: -1,
  65174. faceTileIndex: -1,
  65175. tileX: -1,
  65176. tileY: -1
  65177. };
  65178. return function(o={} ) {
  65179. var id = o.pano.originID, ////////
  65180. panoSize = o.panoSize,
  65181. tileSize = o.tileSize,
  65182. tileIndex = o.tileIndex,
  65183. sceneCode = o.pano.pointcloud.sceneCode,
  65184. useV4url = Potree.settings.useV4url && o.pano.pointcloud.datasetData.sceneVersion == 'V4'; //v4的全景图等路径不一样
  65185. var metadata = {sceneScheme:10};
  65186. TileUtils.getTileLocation(panoSize, tileIndex, t);
  65187. var s = Math.floor(panoSize / tileSize),
  65188. l = s * s,
  65189. h = Math.floor(tileIndex / l),
  65190. u = "",
  65191. d = '', g = '';
  65192. if(Potree.settings.tileOriginUrl){//原始规则
  65193. //1 === config.tiling.customCompression && (u = "_" + config.tiling["q" + e[panoSize]]);
  65194. //1 === o.tiling.customCompression && (u = "_" + o.tiling["q" + e[n]]);
  65195. d = "tiles/" + id + "/" + e[panoSize] + u + "_face" + h + "_" + t.tileX + "_" + t.tileY + ".jpg";
  65196. d = this.getTiles(d, sceneCode, useV4url, o.pano.pointcloud);
  65197. g = "?";
  65198. }else {//阿里云oss的规则 if (metadata.sceneScheme == 10)
  65199. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=';
  65200. if (e[panoSize] == '512') {
  65201. d += 'image/resize,h_512';
  65202. } else {
  65203. //4k的图,移动端是1k,pc端是2k,放大才是4k
  65204. if (e[panoSize] == '1k' || e[panoSize] == '2k') { //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
  65205. d += 'image/resize,m_lfit,w_' + panoSize + '/crop,w_512,h_512,';
  65206. } else {
  65207. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=image/crop,w_512,h_512,';
  65208. }
  65209. //起始位置
  65210. if (t.tileX == 0) {
  65211. d += 'x_0,';
  65212. } else {
  65213. d += 'x_' + (512 * t.tileX /* - 1 */) + ',';
  65214. }
  65215. if (t.tileY == 0) {
  65216. d += 'y_0';
  65217. } else {
  65218. d += 'y_' + (512 * t.tileY /* - 1 */);
  65219. }
  65220. }
  65221. d = this.getTiles(d, sceneCode, useV4url, o.pano.pointcloud);
  65222. g = "&";
  65223. }
  65224. //Potree.settings.panoVersion = 4
  65225. d += g + (Potree.settings.panoVersion ? 'version='+Potree.settings.panoVersion : 'time='+o.pano.pointcloud.timeStamp ); //加后缀
  65226. return d;
  65227. /* 4dkk
  65228. getViewImagesURL(url) {
  65229. if (url.indexOf('&_=') !== -1) {
  65230. return url
  65231. }
  65232. let version = url.indexOf('/panorama/') !== -1 ? this.linkVersion : this.imageVersion
  65233. if (url.indexOf('?') !== -1) {
  65234. return this.$app.config.resource + `scene_view_data/${this.num}/images/${url}&_=${version}`
  65235. }
  65236. return this.$app.config.resource + `scene_view_data/${this.num}/images/${url}?_=${version}`
  65237. }
  65238. /**
  65239. */
  65240. }
  65241. }();
  65242. TileDownloader.tilegen = true;
  65243. TileDownloader.IDLE_REFRESH_DELAY = 500;
  65244. TileDownloader.ACTIVE_REFRESH_DELAY = 16;
  65245. TileDownloader.DOWNLOAD_RETRIES = 4;
  65246. function Node$1(e, t) {
  65247. this.tree = e, //所属树(TileTree)
  65248. this.parent = t,
  65249. this.children = [],
  65250. this.id = ++u$1;
  65251. }
  65252. function o(e, t, i, r, a, s, l, h) {
  65253. if (e) {
  65254. l = l || TileTree.TraversalType.PreOrder;
  65255. var u = r * c + i;
  65256. if (l === TileTree.TraversalType.PreOrder && (a && a(e, t, u, i, r),
  65257. s && s.push(e)),
  65258. e.children && 0 !== e.children.length) {
  65259. for (var d = r * c, p = i * c, f = 0; f < c; f++)
  65260. for (var g = 0; g < c; g++)
  65261. o(e.children[g * c + f], t + 1, p + f, d + g, a, s, l, h);
  65262. l === TileTree.TraversalType.PostOrder && (a && a(e, t, u, i, r),
  65263. s && s.push(e));
  65264. }
  65265. }
  65266. }
  65267. function Plant(seed) {
  65268. seed.root = Branch(seed, null, 0);
  65269. }
  65270. function Branch(seed, parent, level) {
  65271. if (level > seed.levels)
  65272. return null;
  65273. var node = new Node$1(seed, parent);
  65274. seed.allNodes.push(node);
  65275. for (var o = 0; o < h$1; o++)
  65276. node.children[o] = Branch(seed, node, level + 1);
  65277. return node
  65278. }
  65279. function l(parent, t, level, n, r) {
  65280. if (!parent)
  65281. return null;
  65282. if (0 === level)
  65283. return parent;
  65284. if (!parent.children || 0 === parent.children.length)
  65285. return null;
  65286. var o = Math.pow(c, level),
  65287. a = o / c,
  65288. s = n % a,
  65289. h = r % a,
  65290. u = Math.floor(r / a),
  65291. d = Math.floor(n / a),
  65292. p = u * c + d,
  65293. f = parent.children[p];
  65294. return l(f, t + 1, level - 1, s, h)
  65295. }
  65296. /* cube每个面都有一个分层树 用于代表瓦片图的细分?
  65297. 树4096的分为三层,每层有4个子节点。(最后一层的四个子节点都是null)
  65298. */
  65299. var c = 2,
  65300. h$1 = c * c; //4个子节点
  65301. var u$1 = 0;
  65302. class TileTree {
  65303. constructor(e, t) {
  65304. this.levels = t,
  65305. this.tileSize = e,
  65306. this.root = null,
  65307. this.allNodes = [],
  65308. Plant(this);
  65309. }
  65310. getSubNode(e, t, i) {
  65311. (!t || e < this.tileSize) && (t = 0),
  65312. (!i || e < this.tileSize) && (i = 0),
  65313. e < this.tileSize && (e = this.tileSize);
  65314. var level = TileTree.getLevelCountForSize(this.tileSize, e),
  65315. o = l(this.root, 0, level, t, i);
  65316. return o
  65317. }
  65318. breadthFirst(e) {//广度优先搜索
  65319. e = e || {};
  65320. var t = !!e.nullLevelEnd,
  65321. i = e.maxLevel,
  65322. n = e.minLevel,
  65323. r = e.callback,
  65324. o = e.saveVisited,
  65325. a = [],
  65326. s = {},
  65327. l = 0,
  65328. c = 0;
  65329. for (a.push(this.root),
  65330. a.push(s); a.length > 0 && !(i && l > i);) {
  65331. var h = a.shift();
  65332. if (h === s)
  65333. (!n || l >= n) && (r && t && r(null),
  65334. o && t && o.push(null)),
  65335. a.length > 0 && a.push(s),
  65336. l++,
  65337. c = 0;
  65338. else {
  65339. if (h.children)
  65340. for (var u = 0; u < h.children.length; u++) {
  65341. var d = h.children[u];
  65342. d && a.push(h.children[u]);
  65343. }
  65344. var p = this.getFaceIndexFromNode(h);
  65345. (!n || l >= n) && (r && r(h, l, p),
  65346. o && o.push(h)),
  65347. c++;
  65348. }
  65349. }
  65350. }
  65351. getFaceIndexFromNode(e) {
  65352. if (!e)
  65353. return -1;
  65354. for (var t = 1, i = e, n = 0, r = 0;;) {
  65355. var o = i.parent;
  65356. if (!o)
  65357. break;
  65358. for (var a = -1, s = 0; s < o.children.length; s++)
  65359. o.children[s] === i && (a = s);
  65360. var l = a % c,
  65361. h = Math.floor(a / c);
  65362. n = l * t + n,
  65363. r = h * t + r,
  65364. t *= c,
  65365. i = o;
  65366. }
  65367. return r * t + n
  65368. }
  65369. depthFirst(e, t, i) {
  65370. o(this.root, 0, 0, 0, e, t, i, this.tileSize);
  65371. }
  65372. }
  65373. TileTree.TraversalType = Object.freeze({
  65374. PreOrder: 0,
  65375. PostOrder: 1
  65376. });
  65377. TileTree.getLevelCountForSize = function(tileSize, size) {//512->0 2024->1
  65378. var i = 0;
  65379. for (size < tileSize && (size = tileSize);;) {
  65380. if (size /= c,
  65381. size < tileSize)
  65382. break;
  65383. i++;
  65384. }
  65385. return i
  65386. };
  65387. TileTree.getSizeForLevel = function(e, t) {
  65388. return Math.pow(c, t) * e
  65389. };
  65390. /* let sid = 0
  65391. let getName = ()=>{
  65392. return sid ++
  65393. } */
  65394. class BasicMaterial extends ShaderMaterial{
  65395. constructor(o={}){
  65396. super( Object.assign({},{
  65397. uniforms:{
  65398. color: {type:'v3', value: o.color || new Color("#FFF")} ,
  65399. map: {type: 't', value: o.map },
  65400. opacity : {type:'f', value : o.opacity == void 0 ? 1 : o.opacity }
  65401. },
  65402. vertexShader: Shaders['basicTextured.vs'],
  65403. fragmentShader: Shaders['basicTextured.fs'],
  65404. defines:{HasColor:'' }
  65405. },o));
  65406. //this.name111 = getName()
  65407. }
  65408. copy(source){
  65409. super.copy(source);
  65410. //console.log('copy', source.name111, this.name111, !!source.map )
  65411. this.map = source.map;
  65412. return this
  65413. }
  65414. set opacity(o){
  65415. this.uniforms && (this.uniforms.opacity.value = o);
  65416. }
  65417. get opacity(){
  65418. return this.uniforms.opacity.value
  65419. }
  65420. set map(o){
  65421. this.uniforms.map.value = o;
  65422. if(o){
  65423. this.defines.HasMap = '';
  65424. }else {
  65425. delete this.defines.HasMap;
  65426. }
  65427. //可能需要needsUpdate
  65428. //console.log('hasMap', !!o, this.name111 )
  65429. }
  65430. get map(){
  65431. return this.uniforms.map.value
  65432. }
  65433. }
  65434. let {PanoSizeClass: PanoSizeClass$2, PanoRendererEvents: PanoRendererEvents$1 , Vectors,SceneRendererEvents,TileDownloaderEvents: TileDownloaderEvents$1, GLCubeFaces: GLCubeFaces$2} = Potree.defines;
  65435. function createDescriptor() {
  65436. var e = {
  65437. renderTarget: null,
  65438. inUse: !1,
  65439. size: -1,
  65440. pano: null
  65441. };
  65442. return e
  65443. }
  65444. /* function upload() {
  65445. if (!this.uploadIntervalCancelled) {
  65446. if (this.overlayTilesLoaded || !this.usingTileOverlay) {
  65447. b = !0
  65448. let maxNonBaseUploadsPerFrame = viewer.mainViewport.view.isFlying() ? 1 : this.maxNonBaseUploadsPerFrame //原先2。这是每帧uploadTile非512的瓦片tex的数量。之前的2太卡了,降为1。(检测卡顿方法:在一个pano点旋转至所有2048的tile都加载完,然后之后到这个点看看卡不卡。因为该点tiles都下载完了所以会在飞过来时陆续都加载,所以容易卡)
  65449. this.updateUploadQueue(maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame)
  65450. let time = viewer.mainViewport.view.isFlying() ? 60 : w //add 飞行有时候会卡,增长间隔
  65451. this.peekNextFromUploadQueue() ? this.refreshUploadInterval(time) : this.uploadInterval = null //定时下一次更新
  65452. } else {
  65453. this.refreshUploadInterval(this.uploadIntervalDelay)
  65454. }
  65455. }
  65456. } */
  65457. var b = !1,
  65458. w = config$1.tiling.uploadIntervalDelay,
  65459. _ = config$1.tiling.initialIntervalDelay,
  65460. T = config$1.tiling.maxNonBaseUploadsPerFrame,//2 size>512的每次只upload这么多个
  65461. x$1 = config$1.tiling.maxBaseUploadsPerFrame,//6
  65462. S = {
  65463. Base: 0,
  65464. Remaining: 1
  65465. };/* ,
  65466. M = []; */
  65467. class PanoRenderer extends EventDispatcher{
  65468. constructor(viewer, tileDownloader, qualityManager) {
  65469. super();
  65470. this.tileDirectory = {};
  65471. this.activeRenderTargetDescriptors = {};
  65472. this.activePanos = [];
  65473. this.panoLODDescriptors = {};
  65474. this.panoDescriptors = {};
  65475. this.tileTrees = {};
  65476. this.forceQueue = [];
  65477. this.uploadQueues = {};
  65478. this.uploadInterval = null;
  65479. this.uploadIntervalCancelled = true;//!1;
  65480. this.usingTileOverlay = !1;
  65481. this.overlayTilesLoaded = !1;
  65482. this.overlayTileBase = null;
  65483. this.overlayTilesBasic = {};
  65484. this.overlayTilesEnhanced = {};
  65485. this.zoomRenderTarget = null; //用于缩放的rendertarget
  65486. this.zoomPano = null;
  65487. this.zoomingActive = !1;
  65488. this.zoomPanoId = null;
  65489. this.zoomPanoRenderingDisabled = !1;
  65490. this.direction = [];//new THREE.Vector3;
  65491. this.maxBaseUploadsPerFrame = x$1;
  65492. this.maxNonBaseUploadsPerFrame = T;
  65493. this.M = [];//move M to here 似乎列表里会有两个
  65494. this.viewer = viewer;
  65495. this.tileDownloader = tileDownloader;
  65496. this.qualityManager = qualityManager;
  65497. this.initTime = performance.now();
  65498. this.bindEvents();
  65499. }
  65500. getActivePanoTextures(e) {
  65501. e = e || [];
  65502. for (var t = 0; t < M.length; t++) {
  65503. var i = M[t];
  65504. i.renderTarget && i.renderTarget.texture && e.push(i.renderTarget.texture);
  65505. }
  65506. }
  65507. hasQueuedTiles() {
  65508. var e = this.peekNextFromUploadQueue();
  65509. return null !== e && void 0 !== e
  65510. }
  65511. getActiveRenderTargetDescriptor(e) {
  65512. return this.activeRenderTargetDescriptors[e]
  65513. }
  65514. setActiveRenderTargetDescriptor(e, t) {
  65515. this.activeRenderTargetDescriptors[e] = t;
  65516. }
  65517. bindEvents() {
  65518. this.tileDownloader.addEventListener(TileDownloaderEvents$1.TileDownloadSuccess, this.onTileDownloaded.bind(this));
  65519. }
  65520. enableUltraHighQualityMode(e) {
  65521. if(config$1.tileClass == "2k"||config$1.tileClass == "1k")return this.enableHighQuality(e)//xzw add 濡傛灉鏈€澶氬彧瑕?k鐨勮瘽
  65522. if (!this.qualityManager.ultraHighQualityModeEnabled()) {
  65523. var t = this.qualityManager.getPanoSize(PanoSizeClass$2.ULTRAHIGH);
  65524. this.tileDownloader.testDownload(t, TileUtils.TILE_SIZE, function (t) {
  65525. t && (this.qualityManager.enableUltraHighQualityMode(),
  65526. this.setupZoomRenderTarget(),
  65527. e());
  65528. }
  65529. .bind(this));
  65530. }
  65531. }
  65532. activateTiledPano(pano, size, i) {
  65533. i && this.clearAllQueuedUploads();
  65534. for (var n = 0; n < TileUtils.FACES_PER_PANO; n++)
  65535. this.initTileTree(pano.id, n, this.qualityManager.getMaxPossiblePanoSize()); //得到this.tileTrees[pano.id],arr[6]
  65536. this.linkAllTilesAndNodes(pano);
  65537. var r = this.getActiveRenderTargetDescriptor(pano.id),
  65538. l = size;
  65539. l > this.qualityManager.getMaxNavPanoSize() && (l = this.qualityManager.getMaxNavPanoSize());
  65540. if ( !r || l !== r.size) {
  65541. r && this.deactiveDescripor(r.renderTarget);
  65542. r = this.activeDescripor(l);
  65543. if (!r) {
  65544. var ren = this.initTiledPano(l, !browser.isMobile() );
  65545. r = this.initDescriptor(ren.width);
  65546. r.renderTarget = ren;
  65547. }
  65548. r.pano = pano;
  65549. this.resetPanoDescriptor(pano.id);
  65550. this.resetPanoLODDescriptors(pano.id);
  65551. this.resetRenderStatus(pano.id, !0, !0);
  65552. }
  65553. this.setActiveRenderTargetDescriptor(pano.id, r);
  65554. var h = i ? 0 : 1;
  65555. this.updateActivePanos(pano, h);
  65556. //console.log(`index:${this.viewer.index} ${r.renderTarget.texture.id} ${pano.id}`)
  65557. return r.renderTarget
  65558. }
  65559. deactivateTiledPano(pano) {
  65560. var t = this.getActiveRenderTargetDescriptor(pano.id);
  65561. if(this.isRenderTargetDescriptorValid(t)){
  65562. this.deactiveDescripor(t.renderTarget);
  65563. this.setActiveRenderTargetDescriptor(pano.id, null);
  65564. }
  65565. var i = this.getUploadQueueForPano(pano.id);
  65566. this.clearUploadQueue(i);
  65567. this.updateActivePanos();
  65568. viewer.cancelLoad(pano);//add
  65569. }
  65570. getActivePanoCount() {
  65571. return this.activePanos.length
  65572. }
  65573. resetRenderStatus(e, t, i, n) {
  65574. var r = null;
  65575. n && (r = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, n) + 1);
  65576. for (var o = function (e, n, r, o) {
  65577. i && (n.tile.zoomUploaded = !1),
  65578. t && (n.tile.uploaded = !1);
  65579. }, a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  65580. var s = this.getTileTree(e, a);
  65581. s.breadthFirst({
  65582. callback: o.bind(this, a),
  65583. minLevel: r
  65584. });
  65585. }
  65586. }
  65587. copyBaseRenderStatusToZoomed(e) {
  65588. for (var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, this.qualityManager.getMaxNavPanoSize()), i = function (e, t, i, n) {
  65589. t.tile.zoomUploaded = t.tile.uploaded,
  65590. t.zoomCovered = t.covered;
  65591. }, n = 0; n < TileUtils.FACES_PER_PANO; n++) {
  65592. var r = this.getTileTree(e, n);
  65593. r.breadthFirst({
  65594. callback: i.bind(this, n),
  65595. maxLevel: t
  65596. });
  65597. }
  65598. }
  65599. isRenderTargetDescriptorValid(e) {
  65600. return e && e.renderTarget
  65601. }
  65602. isPanoActive(e) {
  65603. var t = this.getActiveRenderTargetDescriptor(e);
  65604. return this.isRenderTargetDescriptorValid(t)
  65605. }
  65606. isPanoZoomed(e) {
  65607. return this.zoomingActive && this.zoomPanoId === e
  65608. }
  65609. initTileTree(e, t, i) {
  65610. var n = this.tileTrees[e];
  65611. n || (n = [],
  65612. this.tileTrees[e] = n);
  65613. var r = n[t];
  65614. if (!r) {
  65615. var o = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i);
  65616. r = new TileTree(TileUtils.TILE_SIZE, o),
  65617. n[t] = r;
  65618. }
  65619. }
  65620. getTileTree(e, t) {
  65621. var i = this.tileTrees[e];
  65622. if (!i)
  65623. console.error("PanoRenderer.getTileTree() -> Tree array not yet initialized!");
  65624. var n = i[t];
  65625. if (!n)
  65626. console.error("PanoRenderer.getTileTree() -> Tree not yet initialized!");
  65627. return n
  65628. }
  65629. /*
  65630. * 创建tile的renderTarget, 包括pano.tiledPanoRenderTarget和zoomRenderTarget
  65631. * @param {number} size 当前的panoSize,每个面的分辨率
  65632. */
  65633. initTiledPano(size, ifNormalFilter) {//创建 RenderTargetCube
  65634. var renderer = this.viewer.renderer;
  65635. var renderTarget, texture;
  65636. renderTarget = new WebGLCubeRenderTarget(size,{ //THREE.WebGLRenderTargetCube(size, size, {
  65637. stencilBuffer: !1
  65638. });
  65639. texture = new CubeTexture([]);
  65640. texture.image = [null, null, null, null, null, null];
  65641. texture.flipY = !0,
  65642. texture.format = RGBAFormat;
  65643. ifNormalFilter ? (texture.generateMipmaps = !0,
  65644. texture.magFilter = LinearFilter,
  65645. texture.minFilter = LinearMipMapLinearFilter)
  65646. : (texture.generateMipmaps = !1,
  65647. texture.magFilter = LinearFilter, //LinearFilter更清晰,但锯齿噪点严重,相当于锐化,其实失真了。对于条纹状的画面移动镜头时锯齿明显 眩晕
  65648. texture.minFilter = LinearFilter);
  65649. //平时还是直接用LinearMipMapLinearFilter,其实并非不清晰,只是没有加锐化,像加了层柔光和抗锯齿,观感更好。放大后使用LinearFilter
  65650. // 如果抗锯齿的话,采用mipmap,会增加一倍的存储消耗。原版本都是不抗锯齿的。但是抗锯齿效果更柔和
  65651. renderTarget.texture = texture; //居然漏了一句,2022.10.9补
  65652. renderer.setRenderTarget(renderTarget);
  65653. renderer.setRenderTarget(null);
  65654. var o = renderer.properties.get(texture);
  65655. o.__image__webglTextureCube = o.__webglTexture;
  65656. //window.tex[r.id] = {texture:r, index:this.viewer.index }
  65657. return renderTarget
  65658. }
  65659. getUploadQueueForPano(e) {
  65660. var t = this.uploadQueues[e];
  65661. return t || (t = [],
  65662. this.uploadQueues[e] = t),
  65663. t
  65664. }
  65665. isTileUploaded(e) {
  65666. return this.isPanoZoomed(e.panoId) ? e.zoomUploaded : e.uploaded
  65667. }
  65668. setUploaded(e, t) {
  65669. this.isPanoZoomed(e.panoId) ? e.zoomUploaded = t : e.uploaded = t;
  65670. }
  65671. queueTileUpload(e, t, i) {
  65672. var n = this.getActiveRenderTargetDescriptor(e.panoId);
  65673. if (this.isRenderTargetDescriptorValid(n) && e.downloaded && !this.isTileUploaded(e) && (!e.uploadQueued || i)
  65674. && (!(e.panoSize > this.qualityManager.getMaxNavPanoSize())|| this.zoomingActive)) {
  65675. var r = this.getUploadQueueForPano(e.panoId);
  65676. //console.log(window.sceneName, 'queueTileUpload: ', e.panoId, e.tileIndex, i)
  65677. if(i){
  65678. //console.log('512下载好了直接uploadTile')
  65679. this.uploadTile(e, !1);//提交后该tile直接loaded了,无需等待
  65680. }else {
  65681. if(this.shoulPushToFrontOfQueue(e)){//如果是512的优先
  65682. this.forceQueue.push(e);
  65683. }else {
  65684. if(t && this.direction){
  65685. TilePrioritizer.insertSortedPanoTile(r, e, n.pano, this.direction);
  65686. }else r.push(e);
  65687. }
  65688. e.uploadQueued = !0;
  65689. this.uploadInterval || this.uploadIntervalCancelled || this.refreshUploadInterval(0);
  65690. }
  65691. }
  65692. }
  65693. shoulPushToFrontOfQueue(e) {
  65694. return 0 === TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize)
  65695. }
  65696. getTopUploadQueue() {
  65697. for (var e = null, t = null, i = S.Base; i <= S.Remaining; i++)
  65698. for (var n = 0; n < this.activePanos.length; n++)
  65699. if (e = this.activePanos[n],
  65700. t = this.getUploadQueueForPano(e.id),
  65701. t.length > 0)
  65702. switch (i) {
  65703. case S.Base:
  65704. if (0 === t[0].level)
  65705. return t;
  65706. break;
  65707. case S.Remaining:
  65708. return t
  65709. }
  65710. return null
  65711. }
  65712. peekNextFromUploadQueue() {
  65713. if (this.forceQueue.length > 0)
  65714. return this.forceQueue[0];
  65715. var e = this.getTopUploadQueue();
  65716. return e && e.length > 0 ? e[0] : null
  65717. }
  65718. clearAllQueuedUploads() {
  65719. this.clearAllUploadQueues(null, 0);
  65720. }
  65721. clearAllQueuedUploadsForPano(e) {
  65722. this.clearAllUploadQueues(e, 0);
  65723. }
  65724. clearAllUploadQueues(e, t) {
  65725. if (e)
  65726. this.clearUploadQueue(this.getUploadQueueForPano(e), t),
  65727. this.clearUploadQueue(this.forceQueue, t, e);
  65728. else {
  65729. for (var i = 0; i < this.activePanos.length; i++) {
  65730. var n = this.activePanos[i];
  65731. this.clearUploadQueue(this.getUploadQueueForPano(n.id), t);
  65732. }
  65733. this.clearUploadQueue(this.forceQueue, t);
  65734. }
  65735. }
  65736. clearUploadQueue(e, t, i) {
  65737. void 0 !== t && null !== t || (t = 0);
  65738. for (var n = 0; n < e.length;) {
  65739. var r = e[n];
  65740. (!i || i && i === r.tile.panoId) && r.level >= t ? (r.uploadQueued = !1,
  65741. e.splice(n, 1)) : n++;
  65742. }
  65743. //若报错, r.tile.panoId改为 r.panoId
  65744. }
  65745. updateUploadQueue(maxNPF,maxPF/* e, t */) {//参数是 maxNonBaseUploadsPerFrame and maxBaseUploadsPerFrame, 优先上传512
  65746. //maxNPF || (maxNPF = 1);
  65747. for (var i = 0, n = 0;;) {
  65748. //let old = this.forceQueue.slice(0)
  65749. if (n >= maxPF || i >= maxNPF)
  65750. break;
  65751. var r = this.getNextFromUploadQueue();
  65752. if (!r)
  65753. break;
  65754. //r.panoSize <2048 && console.log('panoId', r.panoId, 'panoSize', r.panoSize , old)
  65755. 0 !== r.level ? i++ : n++;
  65756. if (!(r.panoSize > this.qualityManager.getMaxNavPanoSize()) || this.zoomingActive) {
  65757. var o = this.getActiveRenderTargetDescriptor(r.panoId);
  65758. this.isRenderTargetDescriptorValid(o) && this.uploadTile(r, r.forceUpload);
  65759. }
  65760. }
  65761. }
  65762. updateDirection(e) {
  65763. if (e = e || this.direction) {
  65764. this.direction = e;
  65765. for (var t = 0; t < this.activePanos.length; t++) {
  65766. var i = this.activePanos[t],
  65767. n = this.getUploadQueueForPano(i.id);
  65768. TilePrioritizer.sortPanoTiles(n, i, this.direction);
  65769. }
  65770. }
  65771. }
  65772. anyUploaded(e) {
  65773. if (!e)
  65774. return !1;
  65775. if (e.tile && this.isTileUploaded(e.tile))
  65776. return !0;
  65777. if (e.children)
  65778. for (var t = 0; t < e.children.length; t++) {
  65779. var i = e.children[t];
  65780. if (this.anyUploaded(i))
  65781. return !0
  65782. }
  65783. return !1
  65784. }
  65785. setNodeCovered(e, t) {
  65786. this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered = t : e.covered = t;
  65787. }
  65788. isNodeCovered(e) {
  65789. return !!e && (this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered : e.covered)
  65790. }
  65791. addCoverageForNode(e) {
  65792. if (this.setNodeCovered(e, !0),
  65793. e.parent && e.covered) {
  65794. var t = e.parent;
  65795. this.nodeSubcovered(t) && this.addCoverageForNode(t, !0);
  65796. }
  65797. }
  65798. calcFullCoverage(e) {
  65799. var t = !1;
  65800. if (e.children)
  65801. for (var i = 0; i < e.children.length; i++) {
  65802. var n = e.children[i];
  65803. t = t || this.calcFullCoverage(n);
  65804. }
  65805. e.covered = e.tile.uploaded || t;
  65806. }
  65807. nodeSubcovered(e) {
  65808. if (!e.children)
  65809. return !1;
  65810. for (var t = 0; t < e.children.length; t++)
  65811. if (!e.children[t] || !this.isNodeCovered(e.children[t]))
  65812. return !1;
  65813. return !0
  65814. }
  65815. resetPanoDescriptor(e) {
  65816. this.getPanoDescriptor(e);
  65817. }
  65818. getPanoDescriptor(e) {
  65819. var t = this.panoDescriptors[e];
  65820. return t || (t = {},
  65821. this.panoDescriptors[e] = t),
  65822. t
  65823. }
  65824. resetPanoLODDescriptors(e) {
  65825. var t = this.getPanoLODDescriptors(e);
  65826. for (var i in t)
  65827. if (t.hasOwnProperty(i)) {
  65828. var n = t[i];
  65829. n.uploadCount = 0,
  65830. n.uploadAttempts = 0;
  65831. n.uploaded = [];
  65832. }
  65833. }
  65834. getPanoLODDescriptor(e, t) {
  65835. var i = this.getPanoLODDescriptors(e),
  65836. n = i[t];
  65837. return n || (n = {
  65838. uploadCount: 0,
  65839. uploadAttempts: 0,
  65840. uploaded:[],//add
  65841. },
  65842. i[t] = n),
  65843. n
  65844. }
  65845. getPanoLODDescriptors(e) {
  65846. var t = this.panoLODDescriptors[e];
  65847. return t || (t = {},
  65848. this.panoLODDescriptors[e] = t),
  65849. t
  65850. }
  65851. onTileDownloaded(o) {
  65852. var e = o.desc;
  65853. var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize),
  65854. i = this.getTileDirectoryEntry(e.panoId, e.face, t, e.faceTileIndex);
  65855. i.downloaded = !0;
  65856. i.image = e.image;
  65857. i.panoSize = e.panoSize;
  65858. i.tileX = e.tileX;
  65859. i.tileY = e.tileY;
  65860. i.totalTiles = e.totalTiles;
  65861. i.tileIndex = e.tileIndex;
  65862. i.faceTileIndex = e.faceTileIndex;
  65863. i.face = e.face;
  65864. i.cubeFace = TileUtils.mapFaceToCubemapFace(e.face);
  65865. i.panoId = e.panoId;
  65866. i.tileSize = e.tileSize;
  65867. i.direction = (new Vector3).copy(e.direction);
  65868. i.node = null;
  65869. i.level = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i.panoSize);
  65870. if (this.isPanoActive(i.panoId)) {
  65871. var n = this.getTileTree(i.panoId, i.face);
  65872. var r = n.getSubNode(i.panoSize, i.tileX, i.tileY);
  65873. this.linkTileAndNode(i, r);
  65874. this.queueTileUpload(i, !0);
  65875. }
  65876. }
  65877. getTileDirectoryEntry(panoId, t, i, n) {
  65878. var r = this.tileDirectory[panoId];
  65879. r || (r = {}, this.tileDirectory[panoId] = r);
  65880. var o = 16384 * t + 1024 * i + n, //t:4096级别
  65881. a = r[o];
  65882. return a || (a = {
  65883. downloaded: !1,
  65884. uploaded: !1,
  65885. zoomUploaded: !1
  65886. },
  65887. r[o] = a),
  65888. a._key = panoId + ":" + t + ":" + i + ":" + n,//panoId : face : level : faceTileIndex
  65889. a._tileKey = o,
  65890. a
  65891. }
  65892. setZoomingActive(active, pano, i) {//设置当前正在zoom的pano
  65893. this.zoomPanoRenderingDisabled || active === this.zoomingActive && this.zoomPanoId === pano.id || (this.zoomingActive = active,
  65894. this.zoomPanoId = pano.id,
  65895. this.zoomingActive && (this.zoomPanoId !== pano.id || i) && this.updateZoomedPanoFromBase(pano));
  65896. }
  65897. updateZoomedPanoFromBase(pano) {//因更换pano所以将pano的rendertarget渲染到panoRenderer的zoomRenderTarget上
  65898. if (!this.zoomPanoRenderingDisabled) {
  65899. var t = this.getActiveRenderTargetDescriptor(pano.id);
  65900. if (t && t.renderTarget ) {
  65901. if(this.zoomRenderTarget){
  65902. var i = Math.min(this.qualityManager.maxRenderTargetSize, this.qualityManager.getMaxZoomPanoSize()), //change
  65903. n = t.renderTarget,
  65904. r = t.size;
  65905. this.copyCubeMap(n.texture, this.zoomRenderTarget, r, r, i, i);
  65906. }
  65907. this.copyBaseRenderStatusToZoomed(pano.id);
  65908. }
  65909. }
  65910. }
  65911. add(e) {
  65912. this.M.push(e);
  65913. }
  65914. initDescriptor(size) {
  65915. var t = createDescriptor();
  65916. t.inUse = !0;
  65917. t.size = size;
  65918. this.add(t);
  65919. return t
  65920. }
  65921. activeDescripor(e) {
  65922. for (var t = 0; t < this.M.length; t++) {
  65923. var i = this.M[t];
  65924. if (!i.inUse && i.size === e){
  65925. i.inUse = !0;
  65926. return i
  65927. }
  65928. }
  65929. return null
  65930. }
  65931. deactiveDescripor(e) {
  65932. for (var t = 0; t < this.M.length; t++) {
  65933. var i = this.M[t];
  65934. if (i.renderTarget === e){
  65935. i.inUse = !1;
  65936. return !0
  65937. }
  65938. }
  65939. return !1
  65940. }
  65941. enableHighQuality(e){//xzw add 如果最多只要2k图的话enableUltraHighQualityMode替换成这个
  65942. if (!this.qualityManager.highQualityModeStarted) {
  65943. this.setupZoomRenderTarget();
  65944. e();
  65945. //this.qualityManager.updateHighResolutionSettings(e)////////?
  65946. this.qualityManager.highQualityModeStarted = true;
  65947. }
  65948. }
  65949. linkTileAndNode(e, t) {
  65950. t.tile = e,
  65951. e.node = t;
  65952. }
  65953. linkAllTilesAndNodes(e) {
  65954. var t = function (t, i, n, r, o) {
  65955. var a = this.getTileDirectoryEntry(e.id, i, r, o);
  65956. this.linkTileAndNode(a, n);
  65957. };
  65958. for (var i = 0; i < TileUtils.FACES_PER_PANO; i++) {
  65959. var n = this.getTileTree(e.id, i);
  65960. n.breadthFirst({
  65961. callback: t.bind(this, n, i)
  65962. });
  65963. }
  65964. }
  65965. //--------------sceneRenderer
  65966. initSizedTexture2D(e, t, i) {
  65967. var renderer = this.viewer.renderer,
  65968. o = renderer.getContext(),
  65969. a = renderer.state,
  65970. s = new Texture(null);
  65971. s.flipY = !1,
  65972. i !== !0 && (i = !1),
  65973. s.generateMipmaps = i;
  65974. var l = renderer.paramThreeToGL(s.format),
  65975. c = renderer.paramThreeToGL(s.type),
  65976. h = renderer.properties.get(s),
  65977. u = o.createTexture();
  65978. a.bindTexture(o.TEXTURE_2D, u),
  65979. o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL, s.flipY),
  65980. o.texImage2D(o.TEXTURE_2D, 0, l, e, e, 0, l, c, null),
  65981. s.wrapS = t,
  65982. s.wrapT = t;
  65983. var d = renderer.paramThreeToGL(t);
  65984. return o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_S, d),
  65985. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_T, d),
  65986. i ? (s.magFilter = LinearFilter,
  65987. s.minFilter = LinearMipMapLinearFilter,
  65988. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR),
  65989. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR_MIPMAP_NEAREST),
  65990. o.generateMipmap(o.TEXTURE_2D)) : (s.magFilter = LinearFilter,
  65991. s.minFilter = LinearFilter,
  65992. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR),
  65993. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR)),
  65994. a.bindTexture(o.TEXTURE_2D, null),
  65995. h.__webglTexture = u,
  65996. s
  65997. }
  65998. deallocateCubeTexture(e) {
  65999. var t = this.viewer.renderer,
  66000. i = t.getContext(),
  66001. renderer = t.properties.get(e);
  66002. i.deleteTexture(renderer.__image__webglTextureCube);
  66003. }
  66004. uploadTexture2D(img, tex, startX, startY, width, height) {
  66005. var renderer = this.viewer.renderer,
  66006. gl = renderer.getContext(),
  66007. webglState = renderer.state,
  66008. c = renderer.properties.get(tex);
  66009. webglState.bindTexture(gl.TEXTURE_2D, c.__webglTexture),
  66010. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, tex.flipY),
  66011. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, tex.premultiplyAlpha),
  66012. gl.pixelStorei(gl.UNPACK_ALIGNMENT, tex.unpackAlignment),
  66013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, renderer.paramThreeToGL(tex.wrapS)),
  66014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, renderer.paramThreeToGL(tex.wrapT)),
  66015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, renderer.paramThreeToGL(tex.magFilter)),
  66016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, renderer.paramThreeToGL(tex.minFilter)),
  66017. gl.texSubImage2D(gl.TEXTURE_2D, 0, startX, startY, gl.RGBA, gl.UNSIGNED_BYTE, img),
  66018. tex.generateMipmaps && gl.generateMipmap(gl.TEXTURE_2D),
  66019. webglState.bindTexture(gl.TEXTURE_2D, null);
  66020. }
  66021. getCubeOrientationForCubeFace(e, t) {
  66022. switch (e) {
  66023. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  66024. t.set(0, -Math.PI / 2, 0);
  66025. break;
  66026. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  66027. t.set(0, Math.PI / 2, 0);
  66028. break;
  66029. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  66030. t.set(Math.PI / 2, Math.PI, 0);
  66031. break;
  66032. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  66033. t.set(-Math.PI / 2, Math.PI, 0);
  66034. break;
  66035. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  66036. t.set(0, -Math.PI, 0);
  66037. break;
  66038. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  66039. t.set(0, 0, 0);
  66040. }
  66041. }
  66042. }
  66043. PanoRenderer.prototype.setupZoomRenderTarget = function(){
  66044. var targets = {};
  66045. return function(){
  66046. if(this.qualityManager.maxRenderTargetSize == 2048 && this.qualityManager.getMaxNavPanoSize()==2048)return; //不使用zoomTarget 直接用pano的tiledPanoRenderTarget,防崩溃
  66047. if (this.qualityManager.getMaxZoomPanoSize() >= this.qualityManager.getMaxNavPanoSize() ) {
  66048. //部分手机2k时copyCubeMap会重载 , 所以如果没有超出当前分辨率,就不使用zoomRenderTarget。但在微信依旧会重载,只是优化了些,safari几乎不会。
  66049. if (this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize())
  66050. return;
  66051. var e = this.zoomRenderTarget;
  66052. var size = this.qualityManager.getMaxZoomPanoSize();
  66053. if(size > this.qualityManager.maxRenderTargetSize){
  66054. return
  66055. }
  66056. if(targets[size]){
  66057. this.zoomRenderTarget = targets[size];
  66058. }else {
  66059. this.zoomRenderTarget = this.initTiledPano(size, false ); //放大后不使用抗锯齿,否则消
  66060. targets[size] = this.zoomRenderTarget;
  66061. }
  66062. if (e) {//将旧的zoomRenderTarget渲染到新zoomRenderTarget上
  66063. var t = e.width,
  66064. i = this.zoomRenderTarget.width;
  66065. this.copyCubeMap(e.texture, this.zoomRenderTarget, t, t, i, i),
  66066. e.texture.dispose(),
  66067. e.texture.loaded = !1,
  66068. e.texture.version = 0,
  66069. this.deallocateCubeTexture(e.texture),
  66070. e.texture = null;
  66071. }
  66072. this.zoomPanoRenderingDisabled = !1;
  66073. } else
  66074. this.zoomPanoRenderingDisabled = !0;
  66075. }
  66076. }();
  66077. PanoRenderer.prototype.updateActivePanos = function () {
  66078. var e = [];
  66079. return function (t, i) {
  66080. e.length = 0;
  66081. for (var n = 0; n < this.activePanos.length; n++) {
  66082. t && e.length === i && e.push(t);
  66083. var r = this.activePanos[n],
  66084. o = this.getActiveRenderTargetDescriptor(r.id);
  66085. t && r.id === t.id || !this.isRenderTargetDescriptorValid(o) || e.push(r);
  66086. }
  66087. t && i >= e.length && e.push(t),
  66088. this.activePanos.length = 0,
  66089. this.activePanos.push.apply(this.activePanos, e);
  66090. }
  66091. }();
  66092. PanoRenderer.prototype.renderPanoTiles = function () {
  66093. var e = [];
  66094. return function (panoId, i, n, r) {
  66095. this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize() || this.zoomPanoRenderingDisabled || this.setupZoomRenderTarget(),//如果ZoomRenderTarget大小需要变动就重新创建
  66096. i = i || this.direction || Vectors.FORWARD; // [{1:Vectors.FORWARD}]?
  66097. var o = this.getActiveRenderTargetDescriptor(panoId);
  66098. if (!this.isRenderTargetDescriptorValid(o))
  66099. console.error("PanoRenderer.renderPanoTiles() -> Cannot render to a pano that is not activated.");
  66100. for (var a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  66101. var s = this.getTileTree(panoId, a);
  66102. e.length = 0;
  66103. s.breadthFirst({//获取该面所有node 85个 = 1+4+16+64
  66104. saveVisited: e
  66105. });
  66106. for (var l = 0; l < e.length; l++) {
  66107. var c = e[l];
  66108. this.queueTileUpload(c.tile, !1, r || 0 === l && n);// 第0个是512的,会直接uploadTile
  66109. }
  66110. }
  66111. this.updateDirection(i);
  66112. }
  66113. }();
  66114. PanoRenderer.prototype.getNextFromUploadQueue = function () {
  66115. var e = function (e) {
  66116. var t = e.shift();
  66117. return t.uploadQueued = !1,
  66118. t
  66119. };
  66120. return function () {
  66121. if (this.forceQueue.length > 0)
  66122. return e(this.forceQueue);
  66123. var t = this.getTopUploadQueue();
  66124. return t && t.length > 0 ? e(t) : null
  66125. }
  66126. }();
  66127. /* PanoRenderer.prototype.refreshUploadInterval = function () {
  66128. var e = null;
  66129. return function (t) {
  66130. this.uploadIntervalCancelled || (e || (e = upload.bind(this)),
  66131. null !== t && void 0 !== t || (t = w),
  66132. b || (t = _),
  66133. this.uploadInterval = window.setTimeout(e, t),
  66134. this.uploadIntervalDelay = t)
  66135. }
  66136. }()
  66137. PanoRenderer.prototype.update = function () {
  66138. var e = performance.now(),
  66139. t = 0;
  66140. return function () {
  66141. this.uploadIntervalCancelled = !0;
  66142. window.clearTimeout(this.uploadInterval);
  66143. this.uploadInterval = null;
  66144. var i = performance.now() - e;
  66145. //!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay || (this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame),
  66146. //e = performance.now()),
  66147. if (!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay) {} else {
  66148. this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame);
  66149. e = performance.now();
  66150. }
  66151. t++;
  66152. }
  66153. }() */
  66154. PanoRenderer.prototype.update = function () {
  66155. //this.uploadIntervalCancelled = true ; //不使用setTimeout,而是在sceneRenderer每帧都update
  66156. if(viewer.images360.latestRequestMode == 'showPanos'){
  66157. let maxNonBaseUploadsPerFrame = viewer.lastFrameChanged ? Common$1.getBestCount('maxStandard', 0, 2, 1, 10 /* ,true */ ) : 2; // 这是每帧uploadTile非512的瓦片tex的数量。 手机在前进时可能会总是0,直到到漫游点后为2
  66158. let maxBaseUploadsPerFrame = viewer.lastFrameChanged ? Common$1.getBestCount('maxBase',1,6, 1, 14 /* ,true */ ) : 6; //this.maxBaseUploadsPerFrame //原先6. 但持续前进过程中会请求加载下一个漫游图,一次加6张会卡的。
  66159. this.updateUploadQueue(maxNonBaseUploadsPerFrame, maxBaseUploadsPerFrame);
  66160. //注:静止时看不出卡顿所以全速加载
  66161. }
  66162. };
  66163. /* function upload() {
  66164. if (!this.uploadIntervalCancelled) {
  66165. if (this.overlayTilesLoaded || !this.usingTileOverlay) {
  66166. b = !0
  66167. let maxNonBaseUploadsPerFrame = viewer.mainViewport.view.isFlying() ? 1 : this.maxNonBaseUploadsPerFrame //原先2。这是每帧uploadTile非512的瓦片tex的数量。之前的2太卡了,降为1。(检测卡顿方法:在一个pano点旋转至所有2048的tile都加载完,然后之后到这个点看看卡不卡。因为该点tiles都下载完了所以会在飞过来时陆续都加载,所以容易卡)
  66168. this.updateUploadQueue(maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame)
  66169. let time = viewer.mainViewport.view.isFlying() ? 60 : w //add 飞行有时候会卡,增长间隔
  66170. this.peekNextFromUploadQueue() ? this.refreshUploadInterval(time) : this.uploadInterval = null //定时下一次更新
  66171. } else {
  66172. this.refreshUploadInterval(this.uploadIntervalDelay)
  66173. }
  66174. }
  66175. } */
  66176. PanoRenderer.prototype.uploadTile = function () {//重写
  66177. var collection = {},
  66178. overlayStyle = config$1.tiling.overlayStyle;
  66179. var failHistory = {};
  66180. return function (info, n) {
  66181. var id = info.panoId,
  66182. img = info.image,
  66183. tileSize = info.tileSize,
  66184. panoSize = info.panoSize,
  66185. tileIndex = info.tileIndex,
  66186. totalTiles = info.totalTiles,
  66187. tileX = info.tileX,
  66188. tileY = info.tileY,
  66189. p = !0,
  66190. g = !1,
  66191. ignore = false, //add
  66192. LodDescripor = (this.getPanoDescriptor(id), this.getPanoLODDescriptor(id, panoSize)),
  66193. activeDescripor = this.getActiveRenderTargetDescriptor(id),
  66194. renderTarget = activeDescripor.renderTarget,
  66195. size = activeDescripor.size;//当前要渲染的面的分辨率,也就是MaxNavPanoSize
  66196. if (this.isPanoZoomed(id) && this.zoomRenderTarget) {
  66197. renderTarget = this.zoomRenderTarget;
  66198. size = this.zoomRenderTarget.width; //this.qualityManager.getMaxZoomPanoSize(); //放大后可能2048或4096
  66199. }
  66200. //console.log(window.sceneName, 'uploadTile ', id, tileIndex)
  66201. let done = ()=>{
  66202. if(!LodDescripor.uploaded.includes(tileIndex)){//已经upload过(本来这时候直接返回,但发现缩放后这不会归零,导致清晰度不更新,所以还是redraw且emit吧)
  66203. //console.log('try to reupload and return',tileIndex)
  66204. LodDescripor.uploaded.push(tileIndex);
  66205. LodDescripor.uploadCount++;
  66206. }
  66207. this.dispatchEvent({type:PanoRendererEvents$1.TileRenderSuccess, id, panoSize, tileIndex, totalTiles});
  66208. LodDescripor.uploadCount === totalTiles && this.dispatchEvent({type:PanoRendererEvents$1.PanoRenderComplete, id, panoSize, totalTiles, updateFullComplete:true});
  66209. this.setUploaded(info, !0);
  66210. this.addCoverageForNode(info.node);
  66211. };
  66212. {//已经uploadTile过了不再uploadTile
  66213. if(!this.isRenderTargetDescriptorValid(activeDescripor)){
  66214. p = !1; g = !1;
  66215. }
  66216. if(!n){
  66217. this.anyUploaded(info.node) && (p = !1, g = !0,ignore = true ); //包括子集也uploadTile了
  66218. this.isTileUploaded(info) && (p = !1, g = !1,ignore = true ); //当前tile uploadTile了
  66219. }
  66220. }
  66221. if (p) {
  66222. /*if(failHistory[id+':'+ panoSize+ ':' +tileIndex]){
  66223. console.log('uploadTile retry',id, panoSize, tileIndex)
  66224. }
  66225. console.log('uploadTile 成功', id, panoSize, tileIndex) */
  66226. var C = tileX * tileSize,
  66227. I = tileY * tileSize,
  66228. E = tileSize / panoSize * size, // tile在renderTarget上渲染出的宽度
  66229. b = C / panoSize * size, // tile在renderTarget上渲染的startX
  66230. w = I / panoSize * size; // tile在renderTarget上渲染的startY
  66231. if(panoSize > this.qualityManager.maxRenderTargetSize ){ //4096 改
  66232. /* var tex = this.initSizedTexture2D(tileSize, THREE.ClampToEdgeWrapping);
  66233. var loaded = this.viewer.images360.isHighMapLoaded(info.cubeFace, tileX,tileY) */
  66234. this.viewer.images360.getHighImage(img, info.cubeFace, tileX, tileY);
  66235. }else {
  66236. collection[tileSize] || (collection[tileSize] = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping));
  66237. var tex = collection[tileSize];
  66238. this.uploadTexture2D(img, tex, 0, 0, tileSize, tileSize);//只替换tex对应的img,不新建
  66239. if(panoSize > this.qualityManager.maxRenderTargetSize){
  66240. loaded || this.viewer.images360.updateHighMap(tex, info.cubeFace, tileX,tileY);
  66241. }else {
  66242. if (1 === overlayStyle || 2 === overlayStyle) {
  66243. var T = 1 === overlayStyle ? this.overlayTilesBasic : this.overlayTilesEnhanced;
  66244. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  66245. this.renderToCubeMap(T[panoSize], renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace, NormalBlending, !0, .5);
  66246. } else {
  66247. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  66248. }
  66249. }
  66250. }
  66251. done();
  66252. }else if(ignore){
  66253. //console.log('finish because anyUploaded',id,panoSize,tileIndex)
  66254. done(); //改: 如果因为这部分更高清的贴图已加载所以才不绘制的话,直接完成
  66255. }else {
  66256. //console.log('uploadTile 失败', id, panoSize, tileIndex)
  66257. if(panoSize == 512){
  66258. //console.log("!!!!!!!!!!!!!")
  66259. }
  66260. failHistory[id+':'+ panoSize+ ':' +tileIndex] = true;
  66261. this.setUploaded(info, !1);
  66262. }
  66263. info.uploadAttempted || (LodDescripor.uploadAttempts++, this.dispatchEvent({type:PanoRendererEvents$1.TileUploadAttempted, id, panoSize, tileIndex, totalTiles})),
  66264. info.uploadAttempted = !0;
  66265. LodDescripor.uploadAttempts === totalTiles && this.dispatchEvent({type:PanoRendererEvents$1.UploadAttemptedForAllTiles, id, panoSize, totalTiles});
  66266. return g;
  66267. }
  66268. }();
  66269. /*
  66270. 注:tileY的方向同UV,从下到上
  66271. renderToCubeMap里的画布or镜头的xy范围是-0.5到0.5
  66272. */
  66273. PanoRenderer.prototype.renderToCubeMap = function() {
  66274. var inited = !1,
  66275. scene = null,
  66276. camera = null,
  66277. material = null,
  66278. geo = null,
  66279. plane = null,
  66280. l = 1;
  66281. return function(texture, renderTarget, tileWidth, tileHeight, startXinTile, startYinTile, widthinTile, heightinTile, startX, startY, width, height, cubeFace, E, b, w) {
  66282. var renderer = this.viewer.renderer;
  66283. inited || (camera = new OrthographicCamera(l / -2, l / 2, l / 2, l / -2, -200, 200),
  66284. camera.position.z = 150,
  66285. scene = new Scene,
  66286. scene.add(camera),
  66287. material = new BasicMaterial({ depthWrite: !1, depthTest: !1, side: 0,}),
  66288. geo = new PlaneBufferGeometry(l, l),
  66289. plane = new Mesh(geo, material),
  66290. plane.position.z = 0,
  66291. scene.add(plane),
  66292. inited = !0);
  66293. var uv = geo.getAttribute("uv");
  66294. uv.setDynamic(!0), //setUsage
  66295. uv.needsUpdate = !0;
  66296. var uvArr = uv.array,
  66297. S = startXinTile / tileWidth, //uv这几个值基本是固定的startXinTile:0,startYinTile:0,widthinTile:512,widthinTile:512,tileWidth:512,tileHeight:512 也就是说uv不会变、每张tile的有效范围是100%
  66298. M = startYinTile / tileHeight,
  66299. R = widthinTile / tileWidth,
  66300. P = heightinTile / tileHeight;
  66301. uvArr[0] = S,
  66302. uvArr[1] = M + P,
  66303. uvArr[2] = S + R,
  66304. uvArr[3] = M + P,
  66305. uvArr[4] = S,
  66306. uvArr[5] = M,
  66307. uvArr[6] = S + R,
  66308. uvArr[7] = M;
  66309. //修改posistion,使该plane只占据需要绘制的部分。类似拼图。
  66310. //startX startY width height 都是在画布上的大小,比如画布大小为2048*2048,此tile为16分之一,tileX是1,tileY是1,则startX=2048/4,startY=2048/4
  66311. var pos = geo.getAttribute("position");
  66312. pos.setDynamic(!0),
  66313. pos.needsUpdate = !0;
  66314. var posArr = pos.array,
  66315. D = startX / renderTarget.width - l / 2 // 起始x
  66316. ,
  66317. N = startY / renderTarget.height - l / 2 // 起始y
  66318. ,
  66319. B = width / renderTarget.width // 宽
  66320. ,
  66321. F = height / renderTarget.height; // 高
  66322. posArr[0] = D,
  66323. posArr[1] = N + F,
  66324. posArr[3] = D + B,
  66325. posArr[4] = N + F,
  66326. posArr[6] = D,
  66327. posArr[7] = N,
  66328. posArr[9] = D + B,
  66329. posArr[10] = N;
  66330. //renderer.properties.get(scene);
  66331. material.map = texture;//material.uniforms.map.value = texture;
  66332. material.blending = E || NoBlending,
  66333. material.transparent = !!b;
  66334. void 0 !== w && null !== w || (w = 1),
  66335. material.uniforms.opacity.value = w,
  66336. // material.needUpdate = !0
  66337. //renderTarget.activeCubeFace = cubeFace, //0-5 应该是指定渲染h中的面 失效
  66338. /* renderer.setScissorTest(!0)
  66339. //指定绘制区域,类似遮罩(相对于屏幕)
  66340. renderer.setScissor(startX,startY,width,height) //加上这个会不会快一些,尤其是spherical
  66341. //指定绘制视口位置和大小(相对于屏幕)
  66342. */
  66343. renderTarget.viewport.set(0, 0, renderTarget.width, renderTarget.height);
  66344. var V = renderer.autoClear;
  66345. var oldTarget = renderer.getRenderTarget();
  66346. renderer.autoClear = !1;
  66347. renderer.setRenderTarget(renderTarget, cubeFace);
  66348. renderer.render(scene, camera/* , renderTarget, !1 */);
  66349. renderer.setRenderTarget(oldTarget);
  66350. renderer.autoClear = V;
  66351. //renderer.setScissorTest(!1)
  66352. /* this.renderer.render(scene, camera, this.planeTargets[cubeFace], !1),//针对有的场景app第一个点图加载不成功的问题
  66353. console.log(`图index ${cubeFace} , ${startX}, ${startY}, ${width}, ${height}`)
  66354. this.targetList[cubeFace] || (this.targetList[cubeFace] = [])
  66355. this.targetList[cubeFace].push([startX,startY,width,height])*/
  66356. }
  66357. }();
  66358. /*
  66359. * 将texture渲染到zoomRenderTarget上(目的是复制贴图到zoomRenderTarget)
  66360. */
  66361. PanoRenderer.prototype.copyCubeMap = function() {//将texture渲染到zoomRenderTarget上
  66362. var inited = !1,
  66363. scene = null,
  66364. camera = null,
  66365. material = null,
  66366. geo = null,
  66367. mesh = null,
  66368. testCube = null, //add
  66369. c = new Euler;
  66370. return function(texture, renderTarget, tWidth, tHeight, rWidth, rHeight, m, v, A) {
  66371. if(rWidth > this.qualityManager.maxRenderTargetSize) return; //add
  66372. if (!inited) {
  66373. var w = 2;
  66374. camera = new OrthographicCamera(w / -2, w / 2, w / 2, w / -2, 0, 200),
  66375. camera.position.set(0, 0, 0),
  66376. scene = new Scene,
  66377. scene.add(camera);
  66378. material = new ShaderMaterial({
  66379. uniforms: {
  66380. tDiffuse: {
  66381. type: "t",
  66382. value: null
  66383. },
  66384. alpha: {
  66385. type: "f",
  66386. value: 1
  66387. }
  66388. },
  66389. vertexShader: Shaders['copyCubeMap.vs'],
  66390. fragmentShader:Shaders['copyCubeMap.fs'],
  66391. depthWrite: !1,
  66392. depthTest: !1,
  66393. side: DoubleSide
  66394. });
  66395. geo = new BoxGeometry(w, w, w),
  66396. mesh = new Mesh(geo, material),
  66397. scene.add(mesh);
  66398. inited = !0;
  66399. /* testCube = mesh.clone();
  66400. viewer.scene.scene.add(testCube);
  66401. Potree.Utils.setObjectLayers(testCube, 'sceneObjects')
  66402. */
  66403. }
  66404. let autoClear = this.viewer.renderer.autoClear;
  66405. let oldTarget = this.viewer.renderer.getRenderTarget();
  66406. this.viewer.renderer.autoClear = false;
  66407. material.uniforms.tDiffuse.value = texture;
  66408. material.blending = m || NoBlending;
  66409. material.transparent = !!v;
  66410. void 0 !== A && null !== A || (A = 1);
  66411. material.uniforms.alpha.value = A;
  66412. material.needUpdate = !0;
  66413. for (var C = 0; C < 6; C++){
  66414. this.getCubeOrientationForCubeFace(C, c);
  66415. mesh.rotation.copy(c);
  66416. mesh.matrixWorldNeedsUpdate = !0;
  66417. mesh.updateMatrixWorld();
  66418. renderTarget.viewport.set(0, 0, rWidth, rHeight);
  66419. this.viewer.renderer.setRenderTarget(renderTarget, C ); //renderTarget.activeCubeFace = C//失效
  66420. this.viewer.renderer.render(scene, camera);
  66421. }
  66422. //console.warn('copyCubeMap' + rWidth)
  66423. this.viewer.renderer.autoClear = autoClear;
  66424. this.viewer.renderer.setRenderTarget(oldTarget);
  66425. }
  66426. }();
  66427. class DepthImageSampler extends EventDispatcher{
  66428. constructor(){
  66429. super();
  66430. var canvas = document.createElement("canvas");
  66431. this.canvas = canvas;
  66432. this.context = canvas.getContext("2d");
  66433. this.imgDatas = [];
  66434. /* document.getElementsByTagName('body')[0].appendChild(canvas);
  66435. canvas.style.position = 'fixed';
  66436. canvas.style.width = '1024px';
  66437. canvas.style.top = canvas.style.left = 0
  66438. canvas.style['z-index'] = 100
  66439. */
  66440. this.maxDataCount = browser.isMobile() ? 6 : 20; //手机会崩溃. 平均每张图为8M数据量(以200个点的园区为例,加载时间久一些后,总内存=700 + 每张图的8M * maxDataCount)
  66441. this.maxNeighCount = browser.isMobile() ? 3 : 14; //包含在maxDataCount内的nearPanos最大个数.至少比maxDataCount少3个,留出空位给最近更新的pano
  66442. this.nearPanos = [];
  66443. }
  66444. updateNearPanos(panos){
  66445. this.nearPanos = panos.slice(0,this.maxNeighCount);
  66446. }
  66447. changeImg(img, pano){
  66448. this.pano = pano;
  66449. let item = this.imgDatas.find(p=>p.pano == pano);
  66450. if(/* this.img == img || */item){
  66451. //最新的在末尾,所以换到末尾
  66452. let index = this.imgDatas.indexOf(item);
  66453. this.imgDatas.splice(index,1);
  66454. this.imgDatas.push(item);
  66455. //console.log('重复使用',item.pano.id)
  66456. return
  66457. }
  66458. Potree.timeCollect.depthSamChangeImg.start = true; //不过在刚启动时得到的用时较大
  66459. try{
  66460. viewer.addTimeMark('depthSamChangeImg','start');
  66461. this.canvas.width = img.width;
  66462. this.canvas.height = img.height;
  66463. this.context.drawImage(img, 0, 0);
  66464. let data = this.context.getImageData(0, 0, img.width , img.height ).data; //getImageData 1px时 : pc chrome 耗时0.01毫秒左右(排除第一次的50) , 但firefox: 4。但换贴图之后就多达5甚至几十
  66465. //console.log('changeImg',pano.id )
  66466. //this.img = img
  66467. if(this.imgDatas.length >= this.maxDataCount){
  66468. let old = this.imgDatas.find(e=>!this.nearPanos.includes(e.pano));
  66469. //console.log('推出',old.pano.id)
  66470. this.imgDatas.splice(this.imgDatas.indexOf(old), 1);//推出使用时间最早的一个非nearPano
  66471. }
  66472. this.imgDatas.push({pano, data});
  66473. this.dispatchEvent({type:'changeImg',pano});
  66474. viewer.addTimeMark('depthSamChangeImg','end'); //耗时chrome 25ms,firefox: 38ms, iphoneX:33ms
  66475. }catch(e){
  66476. console.error(e ); //内存不足 Failed to execute 'getImageData' on 'CanvasRenderingContext2D': Out of memory at ImageData creation
  66477. return false
  66478. }
  66479. /* pano.depthData = {}
  66480. for(let h=0; h<img.height; h++){
  66481. for(let w=0; w<img.width; w++){
  66482. let blockIndex = img.width * h + w
  66483. let r = data.slice(blockIndex*4, (blockIndex+1)*4)
  66484. let depth = r[1] + r[0] / 256
  66485. if(depth>0) pano.depthData[h+'|'+w] = depth
  66486. }
  66487. } */
  66488. }
  66489. getDepth( UVx, UVy) {//根据图片像素获取深度值
  66490. var x = Math.round(UVx * (this.canvas.width - 1))
  66491. , y = Math.round(UVy * (this.canvas.height - 1));
  66492. if (!(x < 0 || y < 0 || x >= this.canvas.width || y >= this.canvas.height)) {
  66493. /* viewer.addTimeMark('depthSampler','start')
  66494. var r = this.context.getImageData(x, y, 1, 1).data; //pc chrome 耗时0.01毫秒左右(排除第一次的50) , 但firefox: 4。但换贴图之后就多达5甚至几十
  66495. viewer.addTimeMark('depthSampler','end')
  66496. //console.log('color', r, x,y)
  66497. return r[1] + r[0] / 256 */
  66498. let imgData = this.imgDatas.find(p=>p.pano == this.pano);
  66499. let blockIndex = this.canvas.width * y + x;
  66500. let color = imgData.data.slice(blockIndex*4, (blockIndex+1)*4);
  66501. return color[1] + color[0] / 256
  66502. }
  66503. }
  66504. sample( intersect, currentPano, onlyPos ) {//通过和skybox的intersect得到真实的intersect的位置
  66505. if(!intersect)return
  66506. let location = new Vector3;
  66507. let normal;
  66508. currentPano = currentPano || viewer.images360.currentPano;
  66509. if(currentPano != this.currentPano){
  66510. if(!currentPano.depthTex/* || !currentPano.depthTex.image */) return //未加载
  66511. if(this.changeImg(currentPano.depthTex.image, currentPano) === false){
  66512. console.log('失败', currentPano.id);
  66513. return false //失败
  66514. }
  66515. this.currentPano = currentPano;
  66516. }
  66517. let origin = currentPano.position;
  66518. let dir = intersect.dir || new Vector3().subVectors(intersect.point, origin).normalize();
  66519. //var uv = intersect.uv
  66520. //let dirInPano = math.getNormalDir(dir, currentPano)//转化为考虑漫游点旋转的方向
  66521. let dirInPano = dir.clone().applyMatrix4(currentPano.panoMatrix2Inverse).normalize(); //转化为考虑漫游点旋转的方向
  66522. let uv = math.getUVfromDir(dirInPano);//转化为uv
  66523. let distance = this.getDepth( uv.x, uv.y);
  66524. //viewer.addTimeMark(markName,'end')
  66525. if (!distance){
  66526. const margin = 0.1;
  66527. if(uv.y > 1-Potree.config.depthTexUVyLimit){//漫游点底部识别不到的区域,给一个地板高度
  66528. distance = (currentPano.floorPosition.z - origin.z - margin) / dir.z;
  66529. location.copy(dir).multiplyScalar(distance).add(origin);
  66530. let normal = new Vector3(0,0,1);
  66531. return {location, normal, distance}
  66532. }else if(uv.y < Potree.config.depthTexUVyLimit){
  66533. let ceilZ = currentPano.getCeilHeight();
  66534. if(ceilZ == Infinity)return !1
  66535. else {
  66536. distance = (ceilZ - origin.z - margin) / dir.z;
  66537. location.copy(dir).multiplyScalar(distance).add(origin);
  66538. let normal = new Vector3(0,0,-1);
  66539. return {location, normal, distance}
  66540. }
  66541. }
  66542. //console.log('无穷远')
  66543. return !1; //应该是天空或模型外 , 因为很少有漫游点的地方还拍不到地板
  66544. }
  66545. //console.log('distance', distance, dirInPano.clone().multiplyScalar(distance))
  66546. location.copy(dir).multiplyScalar(distance).add(origin);
  66547. if(!onlyPos){
  66548. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  66549. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  66550. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  66551. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  66552. normal = this.planeFit(dir,location, pL,pR,pB,pT );
  66553. }
  66554. /* if(normal.x != normal.x ){
  66555. console.log('NAN', normal)
  66556. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  66557. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  66558. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  66559. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  66560. } */
  66561. //console.log(location, normal, distance)
  66562. return {location, normal, distance}
  66563. }
  66564. getNearbyPoint( origin, uv, x, y) { //获取附近的若干像素距离的点
  66565. let uv2 = uv.clone();
  66566. uv2.x += x/(this.canvas.width-1);
  66567. uv2.x = this.clampUV(uv2.x);
  66568. uv2.y += y/(this.canvas.height-1);
  66569. uv2.y = this.clampUV(uv2.y);
  66570. /* if(uv2.x < 0 || uv2.y < 0 || uv2.x > 1 || uv2.y > 1){
  66571. console.log('will nan')
  66572. } */
  66573. let dir = math.getDirFromUV(uv2);//从uv获取到方向
  66574. dir.applyMatrix4(viewer.images360.currentPano.panoMatrix2);
  66575. let depth = this.getDepth(uv2.x, uv2.y);
  66576. /* if(Math.abs(depth - this.mainDepth) > 0.3){
  66577. console.log('Math.abs(depth - this.mainDepth) > 0.3')
  66578. } */
  66579. //let dir = new THREE.Vector3().subVectors(intersect.point, origin).normalize()
  66580. let position = new Vector3().copy(dir).multiplyScalar(depth).add(origin);
  66581. //console.log('getNearbyPoint', uv2, depth, dir, position )
  66582. return position
  66583. }
  66584. clampUV(v){
  66585. return (v + 1) % 1; // 使输出在 0-1
  66586. }
  66587. planeFit(dir, position, pL,pR,pB,pT ) {//求平均法线
  66588. let normal = new Vector3;
  66589. let plane = new Plane;
  66590. function addNormal(p1, p2) {//根据临接的四个点,分别求法线,然后法线相加能得到平均法线
  66591. if(!p1 || !p2)return
  66592. plane.setFromCoplanarPoints(position, p1, p2);
  66593. //console.log('normalSub', plane.normal)
  66594. normal.addScaledVector(plane.normal, dir.dot(plane.normal) < 0 ? 1 : -1);//根据面的朝向判断加还是减
  66595. }
  66596. addNormal(pL, pB);
  66597. addNormal(pL, pT);
  66598. addNormal(pR, pB);
  66599. addNormal(pR, pT);
  66600. if(0 !== normal.x || 0 !== normal.y || 0 !== normal.z){
  66601. normal.normalize();
  66602. //console.log(normal)
  66603. return normal
  66604. }
  66605. /* 四个面拼成一个菱形 */
  66606. }
  66607. }
  66608. let {PanoSizeClass: PanoSizeClass$3,Vectors: Vectors$1,GLCubeFaces: GLCubeFaces$3, PanoramaEvents: PanoramaEvents$1} = Potree.defines;
  66609. var rot90$1 = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
  66610. let raycaster = new Raycaster();
  66611. //let currentlyHovered = null;
  66612. let texLoader$6 = new TextureLoader();
  66613. let tileArr = [];
  66614. let previousView = {
  66615. controls: null,
  66616. position: null,
  66617. target: null,
  66618. };
  66619. const HighMapCubeWidth = 1;
  66620. const directionFactor = 400; //原先10,几乎只往距离近的走了;设置太大容易略过近处漫游点走向下坡,因为鼠标一般在地面,下坡的漫游点更有利
  66621. class Images360 extends EventDispatcher{
  66622. constructor(viewer ){
  66623. super();
  66624. this.viewer = viewer;
  66625. this.panos = [];
  66626. this.neighbourMap = {};
  66627. this.node = new Object3D();
  66628. this.node.name = 'ImagesNode';
  66629. this.cubePanos = [];
  66630. {
  66631. this.cube = new Mesh(new BoxBufferGeometry(1,1,1,1),new ModelTextureMaterial());
  66632. Potree.Utils.updateVisible(this.cube,'showSkybox', false );
  66633. this.cube.layers.set(Potree.config.renderLayers.skybox);
  66634. this.cube.name = 'skyboxCube';
  66635. viewer.scene.scene.add(this.cube);
  66636. }
  66637. if(Potree.settings.testCube){
  66638. this.cubeTest = this.cube.clone();
  66639. this.cubeTest.material = new MeshBasicMaterial({
  66640. wireframe:true,
  66641. color:'#FF3377',
  66642. transparent:true,
  66643. opacity:0.7,
  66644. depthWrite:false,
  66645. depthTest:false,
  66646. });
  66647. viewer.scene.scene.add(this.cubeTest);
  66648. this.cubeTest.visible = true;
  66649. }
  66650. this.flying_ = false;
  66651. this.currentPano = null;
  66652. this.mouseLastMoveTime = Date.now();
  66653. this.scrollZoomSpeed = 0.06;
  66654. this.zoomLevel = 1;
  66655. this.tileDownloader = new TileDownloader;
  66656. this.qualityManager = new QualityManager;
  66657. this.panoRenderer = new PanoRenderer(viewer, this.tileDownloader, this.qualityManager);
  66658. this.basePanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.BASE);
  66659. this.standardPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.STANDARD);
  66660. this.highPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.HIGH);
  66661. this.ultraHighPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.ULTRAHIGH);
  66662. this.tileDownloader.processPriorityQueue = !1;
  66663. this.tileDownloader.tilePrioritizer = new TilePrioritizer(this.qualityManager, this.basePanoSize, this.standardPanoSize, this.highPanoSize, this.ultraHighPanoSize);
  66664. {//高分辨率cube 放大
  66665. this.addHighMapCube();
  66666. viewer.addEventListener(PanoramaEvents$1.Enter,(e)=>{
  66667. this.setHighMap(e.newPano);
  66668. });
  66669. viewer.addEventListener('panoSetZoom',(e)=>{
  66670. if(Potree.settings.displayMode == 'showPanos'){
  66671. e.zoomed ? this.showHighMap() : this.hideHighMap(); //add
  66672. }
  66673. });
  66674. }
  66675. this.depthSampler = new DepthImageSampler();
  66676. viewer.fpControls.addEventListener('dollyStopCauseUnable',(e)=>{
  66677. if(/* e.hoverViewport != viewer.mainViewport || */!Potree.settings.zoom.enabled)return
  66678. if(e.scale != void 0){//触屏
  66679. this.zoomBy(e.scale, e.pointer);
  66680. }else {//滚轮
  66681. let zoom;
  66682. if(e.delta > 0){
  66683. zoom = 1 + this.scrollZoomSpeed;
  66684. }else {
  66685. zoom = 1 - this.scrollZoomSpeed;
  66686. }
  66687. e.delta != 0 && this.zoomBy(zoom);
  66688. }
  66689. });
  66690. let click = (e) => {//不用"mouseup" 是因为 mouseup有drag object时也会触发
  66691. if(e.clickElement ||
  66692. Potree.settings.unableNavigate || this.flying || !e.isTouch && e.button != MOUSE.LEFT || e.drag && e.drag.object //拖拽结束时不算
  66693. || Potree.settings.editType == 'pano' && viewer.modules.PanoEditor.activeViewName != 'mainView'
  66694. || Potree.settings.editType == 'merge' && !e.intersectPoint || viewer.inputHandler.hoveredElements[0] && viewer.inputHandler.hoveredElements[0].isModel && e.intersectPoint.distance > viewer.inputHandler.hoveredElements[0].distance
  66695. ) return
  66696. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  66697. if( e.hoverViewport == viewer.mapViewer.viewports[0]){
  66698. return viewer.mapViewer.dispatchEvent(e/* {type:'global_click',e } */)
  66699. }else if(e.hoverViewport != viewer.mainViewport){ //如数据集校准其他viewport
  66700. return
  66701. }
  66702. }
  66703. if(!Potree.settings.dblToFocusPoint/* && this.currentPano */){//双击不会focus点云 或者 已经focusPano了
  66704. this.flyToPanoClosestToMouse();
  66705. }
  66706. };
  66707. viewer.addEventListener('global_click' , click);
  66708. viewer.addEventListener("global_mousemove", (e) => {
  66709. if(!Potree.settings.unableNavigate && Potree.settings.ifShowMarker && e.hoverViewport == viewer.mainViewport){//如果不显示marker,就在点击时再更新
  66710. this.updateClosestPano(e.intersect);
  66711. }
  66712. });
  66713. this.addEventListener('markerHover',(e)=>{
  66714. this.updateClosestPano(e.pano, e.hovered);
  66715. });
  66716. if(!Potree.settings.isOfficial){
  66717. this.domRoot = viewer.renderer.domElement.parentElement;
  66718. let elUnfocus = $("<input type='button' value='unfocus'></input>");
  66719. elUnfocus.css({
  66720. position : "absolute",
  66721. right : '25%',
  66722. bottom: '20px',
  66723. zIndex: "10000",
  66724. fontSize:'1em', color:"black",
  66725. display:'none',
  66726. background:'rgba(255,255,255,0.8)',
  66727. });
  66728. elUnfocus.on("click", () => this.unfocus());
  66729. this.elUnfocus = elUnfocus;
  66730. this.domRoot.appendChild(elUnfocus[0]);
  66731. if(Potree.settings.editType != 'merge'){
  66732. let elHide = $("<input type='button' value='隐藏点云'></input>");
  66733. elHide.css({
  66734. position : "absolute",
  66735. right : '40%',
  66736. bottom: '20px',
  66737. zIndex: "10000",
  66738. fontSize:'1em' ,color:"black",
  66739. width : '100px',
  66740. background:'rgba(255,255,255,0.8)',
  66741. });
  66742. this.domRoot.appendChild(elHide[0]);
  66743. elHide.on("click", (e) => {
  66744. let visi = Potree.Utils.getObjVisiByReason(viewer.scene.pointclouds[0], 'force');
  66745. viewer.scene.pointclouds.forEach(e=>{
  66746. Potree.Utils.updateVisible(e, 'force', !visi);
  66747. });
  66748. elHide.val(!visi ? "隐藏点云" : "显示点云");
  66749. });
  66750. }
  66751. let elDisplayModel = $("<input type='button' value='>>全景'></input>");
  66752. elDisplayModel.css({
  66753. position : "absolute",
  66754. right : '65%',
  66755. bottom: '20px',
  66756. zIndex: "10000",
  66757. fontSize:'1em',color:"black",
  66758. width : '100px',
  66759. background:'rgba(255,255,255,0.8)',
  66760. });
  66761. this.domRoot.appendChild(elDisplayModel[0]);
  66762. elDisplayModel.on("click", (e) => {
  66763. if(Potree.settings.displayMode == 'showPointCloud' && this.panos.length == 0)return
  66764. Potree.settings.displayMode = Potree.settings.displayMode == 'showPointCloud' ? 'showPanos' : 'showPointCloud';
  66765. });
  66766. this.elDisplayModel = elDisplayModel;
  66767. if(viewer.mapViewer){
  66768. let mapStyleBtn = $("<input type='button' value='普通'></input>");
  66769. mapStyleBtn.css({
  66770. position : "absolute",
  66771. right : '50%',
  66772. bottom: '20px',
  66773. zIndex: "10000",
  66774. fontSize:'1em' ,color:"black",
  66775. width : '100px',
  66776. background:'rgba(255,255,255,0.8)',
  66777. });
  66778. this.domRoot.appendChild(mapStyleBtn[0]);
  66779. let map = viewer.mapViewer.mapLayer.maps.find(e=>e.name == 'map');
  66780. mapStyleBtn.on("click", (e) => {
  66781. map.switchStyle(map.style == 'satellite' ? 'standard' : 'satellite');
  66782. mapStyleBtn.val(map.style == 'satellite' ? '卫星' : '普通');
  66783. });
  66784. }
  66785. }
  66786. {//切换模式
  66787. let displayMode = '';
  66788. this.latestRequestMode = '';//因为可能延迟,所以记录下每次的请求模式,延迟后判断这个
  66789. Object.defineProperty(Potree.settings , "displayMode",{
  66790. get: function() {
  66791. return displayMode
  66792. },
  66793. set: (mode)=> {
  66794. this.latestRequestMode = mode;
  66795. console.warn('Request setMode: ' + mode);
  66796. let config2;
  66797. let config = Potree.config.displayMode[mode];
  66798. if(this.isAtPano() && !this.latestToPano){
  66799. config2 = config.atPano;
  66800. }else {
  66801. config2 = config.transition;
  66802. }
  66803. let changeTileDownload = ()=>{
  66804. if(config2.showSkybox || config2.showPoint && config2.pointUsePanoTex){
  66805. this.tileDownloader.start();
  66806. this.currentPano && this.currentPano.enter();
  66807. }else {
  66808. this.tileDownloader.stop();
  66809. this.currentPano && this.currentPano.exit();
  66810. }
  66811. };
  66812. if(mode != displayMode){
  66813. let camera = viewer.scene.getActiveCamera();
  66814. if(mode == 'showPanos' && viewer.mainViewport.view.isFlying()){//飞完才能切换全景
  66815. let f = ()=>{
  66816. if(this.latestRequestMode == mode){//如果ui还是停在这个模式的话
  66817. Potree.settings.displayMode = mode;
  66818. }
  66819. viewer.mainViewport.view.removeEventListener('flyingDone', f);
  66820. };
  66821. viewer.mainViewport.view.addEventListener('flyingDone', f); //once
  66822. return
  66823. }
  66824. if(this.isAtPano() && !this.latestToPano){
  66825. config2 = config.atPano;
  66826. }else {
  66827. config2 = config.transition;
  66828. if(mode == 'showPanos'){//自动飞入一个pano
  66829. //要改成飞进最近的。。。
  66830. if(this.panos.length == 0)return
  66831. //this.modeChanging = true //主要是因为到全景图不会立刻成功
  66832. let wait = (e)=>{
  66833. console.log('flyToPanoDone');
  66834. this.removeEventListener('flyToPanoDone',wait);
  66835. setTimeout(()=>{
  66836. if(this.latestRequestMode == mode ){
  66837. Potree.settings.displayMode = mode;
  66838. }
  66839. },e.makeIt ? 1 : 50);
  66840. };
  66841. this.addEventListener('flyToPanoDone',wait); //等待飞行完毕。flyToPano的callback可能不执行所以换这个。但也可能被cancel
  66842. this.flyToPano({
  66843. pano: this.findNearestPano(),
  66844. //dealDoneWhenCancel:true,
  66845. /* callback: ()=>{
  66846. setTimeout(()=>{ //防止循环,所以延迟
  66847. if(this.latestRequestMode == mode ){
  66848. Potree.settings.displayMode = mode
  66849. }
  66850. },1)
  66851. } */
  66852. });
  66853. return;
  66854. }else {
  66855. }
  66856. }
  66857. changeTileDownload();
  66858. if(config2.showSkybox || config2.pointUsePanoTex){
  66859. let wait = ( )=> {
  66860. console.log('waitdone');
  66861. //if(e.pano && e.pano != this.currentPano)return //loadedDepthImg
  66862. setTimeout( ()=>{
  66863. if(this.latestRequestMode == mode ){
  66864. Potree.settings.displayMode = mode;
  66865. }
  66866. },1);
  66867. };
  66868. //this.updateDepthTex()
  66869. if(this.checkAndWaitForPanoLoad(this.currentPano, this.basePanoSize, wait)){
  66870. console.log('等待贴图加载2', this.currentPano.id);
  66871. return
  66872. }
  66873. }
  66874. viewer.scene.pointclouds.forEach(e=>{
  66875. Potree.Utils.updateVisible(e, 'displayMode', config2.showPoint, 2 );
  66876. });
  66877. if(config2.pointUsePanoTex){
  66878. viewer.scene.pointclouds.forEach(e=>{
  66879. e.material.setProjectedPanos(this.currentPano,this.currentPano, 1);
  66880. });
  66881. }else {
  66882. viewer.scene.pointclouds.forEach(e=>{
  66883. e.material.stopProjectedPanos();
  66884. });
  66885. }
  66886. Potree.Utils.updateVisible(this.cube,'showSkybox',config2.showSkybox );// this.cube.visible = config2.showSkybox
  66887. //this.cube.visible = config.atPano.showSkybox
  66888. if(this.cube.visible){
  66889. //this.cube.material.setProjectedPanos(this.currentPano, this.currentPano, 1)
  66890. this.setProjectedPanos({
  66891. progress:1,
  66892. ifSkybox: true,
  66893. ifPointcloud : false,
  66894. easeInOutRatio : 0,
  66895. pano0:this.currentPano,
  66896. pano1:this.currentPano
  66897. });
  66898. }else {
  66899. this.smoothZoomTo(1);
  66900. this.resetHighMap();
  66901. this.hideHighMap();
  66902. }
  66903. /* viewer.dispatchEvent({
  66904. type: "enableChangePos",
  66905. canLeavePano : config.canLeavePano ,
  66906. viewport:
  66907. }) */
  66908. //viewer.mainViewport.unableChangePos = !config.canLeavePano
  66909. displayMode = mode;
  66910. if(mode == 'showPanos'){
  66911. camera.far = viewer.farWhenShowPano; //修改far
  66912. Potree.settings.pointDensity = 'panorama';
  66913. if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
  66914. viewer.scene.pointclouds.forEach(e=>{
  66915. e.material.pointSizeType = 'FIXED';
  66916. });
  66917. }
  66918. this.updateCube(this.currentPano);
  66919. }else {
  66920. if(camera.limitFar) camera.far = Potree.settings.cameraFar;//修改far
  66921. Potree.settings.pointDensity = Potree.settings.UserPointDensity;
  66922. //Potree.sdk && Potree.sdk.scene.changePointOpacity()
  66923. if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
  66924. viewer.scene.pointclouds.forEach(e=>{
  66925. e.material.pointSizeType = Potree.config.material.pointSizeType;
  66926. });
  66927. }
  66928. }
  66929. camera.updateProjectionMatrix();
  66930. if(this.elDisplayModel){
  66931. this.elDisplayModel.val( mode == 'showPointCloud' ? ">>全景" : '>>点云');
  66932. }
  66933. /* this.panos.forEach(e=>{
  66934. Potree.Utils.updateVisible(e, 'modeIsShowPanos', mode == 'showPanos', 1, mode == 'showPanos' ? 'add':'cancel') //
  66935. }) */
  66936. this.dispatchEvent({type:'endChangeMode',mode});
  66937. console.log('setModeSuccess: ' + mode);
  66938. }else {
  66939. changeTileDownload();
  66940. //this.dispatchEvent({type:'endChangeMode',mode})
  66941. }
  66942. }
  66943. });
  66944. Potree.settings.displayMode = 'showPointCloud';
  66945. }// 切换模式 end
  66946. {//
  66947. let currentPano = null;
  66948. Object.defineProperty(this , "currentPano",{
  66949. get: function() {
  66950. return currentPano
  66951. },
  66952. set: function(e) {
  66953. if(e != currentPano){
  66954. console.log('set currentPano ', e.id);
  66955. currentPano && currentPano.exit();
  66956. e && e.enter();
  66957. currentPano = e;
  66958. }
  66959. }
  66960. });
  66961. }
  66962. {//是否显示marker
  66963. let ifShowMarker = true;
  66964. Object.defineProperty(Potree.settings, "ifShowMarker",{
  66965. get: function() {
  66966. return ifShowMarker
  66967. },
  66968. set: (show)=>{
  66969. show = !!show;
  66970. if(show != ifShowMarker){
  66971. this.panos.forEach(pano=>{
  66972. Potree.Utils.updateVisible(pano, 'ifShowMarker', show, 1 );
  66973. });
  66974. //this.emit('markersDisplayChange', show)
  66975. ifShowMarker = show;
  66976. viewer.dispatchEvent('showMarkerChanged');
  66977. viewer.dispatchEvent('content_changed');
  66978. }
  66979. }
  66980. });
  66981. }
  66982. viewer.addEventListener("update", () => {
  66983. this.update(viewer);
  66984. });
  66985. //viewer.inputHandler.addInputListener(this);
  66986. var keys = {
  66987. FORWARD: ['W'.charCodeAt(0), 38],
  66988. BACKWARD: ['S'.charCodeAt(0), 40],
  66989. LEFT: ['A'.charCodeAt(0), 37],
  66990. RIGHT: ['D'.charCodeAt(0), 39],
  66991. };
  66992. viewer.inputHandler.addEventListener('keydown',(e)=>{
  66993. if(Potree.settings.displayMode == 'showPanos'){
  66994. for(let i in keys){
  66995. if(keys[i].some(a => a == e.keyCode)){
  66996. switch(i){
  66997. case 'FORWARD':
  66998. this.flyLocalDirection(Vectors$1.FORWARD.clone());
  66999. break;
  67000. case 'BACKWARD':
  67001. this.flyLocalDirection(Vectors$1.BACK.clone());
  67002. break;
  67003. case 'LEFT':
  67004. this.flyLocalDirection(Vectors$1.LEFT.clone());
  67005. break;
  67006. case 'RIGHT':
  67007. this.flyLocalDirection(Vectors$1.RIGHT.clone());
  67008. break;
  67009. }
  67010. break;
  67011. }
  67012. }
  67013. }
  67014. });
  67015. };
  67016. updateDepthTex(pano){
  67017. if(this.currentPano != pano || !pano.depthTex)return
  67018. //this.depthSampler.changeImg(pano.depthTex.image); //pick sampler要飞到了才能切换图,而skybox贴图是随着全景图切换而切换的
  67019. this.cube.material.updateDepthTex(pano); //确保一下
  67020. }
  67021. findNearestPano(pos){
  67022. pos = pos ? new Vector3().copy(pos) : this.position;
  67023. let result = Common$1.sortByScore(this.panos,[Images360.filters.isEnabled()],[e=>-e.position.distanceTo(pos)]);
  67024. let pano = result[0] && result[0].item;
  67025. return pano
  67026. }
  67027. /* set flying(v){//正在飞向pano
  67028. this.flying_ = !!v
  67029. //console.log('this.flying_ ', !!v )
  67030. //this.emit('flying', this.flying_)
  67031. let config = Potree.config.displayMode[Potree.settings.displayMode]
  67032. viewer.mainViewport.unableChangePos = !config.canLeavePano || !!v
  67033. }
  67034. get flying(){
  67035. return this.flying_
  67036. } */
  67037. flyLocalDirection(dir) {
  67038. var direction = this.getDirection(dir),
  67039. option1 = 1 === dir.y ? .4 : .75,
  67040. option2 = 1 === Math.abs(dir.x);
  67041. return this.flyDirection(direction, option1, option2, true)
  67042. }
  67043. getDirection(e) {
  67044. if(!e){
  67045. return viewer.scene.view.direction
  67046. }else {
  67047. return e = e ? e : (new Vector3).copy(Vectors$1.FORWARD),
  67048. e.applyQuaternion(viewer.mainViewport.camera.quaternion)
  67049. }
  67050. }
  67051. get position(){
  67052. return this.viewer.scene.view.position.clone()
  67053. }
  67054. isAtPano(precision){//是否在某个漫游点上
  67055. if(precision){
  67056. return this.currentPano && math.closeTo(viewer.scene.view.position, this.currentPano.position, precision)
  67057. }
  67058. return this.currentPano && viewer.scene.view.position.equals(this.currentPano.position)
  67059. }
  67060. updateProjectedPanos(){//更新材质贴图
  67061. //console.warn('updateProjectedPanos')
  67062. this.projectedPano0 && this.projectedPano1 && this.setProjectedPanos({pano0:this.projectedPano0, pano1:this.projectedPano1});
  67063. }
  67064. setProjectedPanos(o={}){//设置cube和点云的材质贴图
  67065. this.cube.material.setProjectedPanos(o.pano0, o.pano1, o.progress);
  67066. if(o.ifPointcloud){
  67067. viewer.scene.pointclouds.forEach(e=>{
  67068. e.material.setProjectedPanos(o.pano0, o.pano1, o.progress, o.easeInOutRatio);
  67069. });
  67070. }
  67071. //console.warn('setProjectedPanos ', o.pano0.id , o.pano1.id)
  67072. this.projectedPano0 = o.pano0;
  67073. this.projectedPano1 = o.pano1;
  67074. }
  67075. cancelFlyToPano(toPano){//取消当前已有的飞行准备,前提是相机还未移动
  67076. if(viewer.mainViewport.view.isFlying() || toPano && this.latestToPano != toPano)return
  67077. Potree.Log('cancelFlyToPano', this.latestToPano && this.latestToPano.pano.id);
  67078. this.nextPano = null;
  67079. this.latestToPano = null;
  67080. }
  67081. flyToPano(toPano) { //飞向漫游点
  67082. if(!toPano)return
  67083. if(toPano instanceof Panorama){
  67084. toPano = {pano: toPano};
  67085. }
  67086. let done = (makeIt, disturb)=>{
  67087. //console.log('flyToPano done ', toPano.pano.id, makeIt, disturb )
  67088. if(makeIt || disturb) { // disturb已经开始飞行但中途取消
  67089. toPano.callback && toPano.callback(makeIt);
  67090. //this.flying = false
  67091. this.cancelFlyToPano(toPano);
  67092. this.updateClosestPano(this.closestPano,false); //飞行结束后取消点击漫游点时得到的closestPano
  67093. }else {
  67094. }
  67095. this.dispatchEvent({type:'flyToPanoDone', makeIt, disturb});
  67096. toPano.deferred && toPano.deferred.resolve(makeIt); //测量线截图时发现,resolve需要写在flying=false 后才行。
  67097. };
  67098. if(!toPano.pano.enabled)return done(false,true);
  67099. //Potree.Log('hope flyToPano: '+toPano.pano.id, toPano.pano.position.toArray() )
  67100. if(this.latestToPano && this.latestToPano != toPano && (//还在飞
  67101. this.latestToPano.pano != this.currentPano || !this.isAtPano())){//如果旧的toPano只在pano旋转镜头,就直接取消旧的,继续执行
  67102. return done(false)
  67103. }
  67104. if(this.currentPano == toPano.pano && this.isAtPano() && !toPano.target && !toPano.quaternion ){
  67105. //已在该pano
  67106. this.dispatchEvent({type:'flyToPano', toPano});
  67107. return done(true);
  67108. }
  67109. //Potree.Log('flyToPano: '+toPano.pano.id, toPano.pano.position.toArray() /* this.latestToPano && this.latestToPano.pano.id */ )
  67110. let target = toPano.target;
  67111. let config = Potree.config.displayMode[Potree.settings.displayMode];
  67112. let pointcloudVisi = config.atPano.showPoint; //viewer.scene.pointclouds[0].visible
  67113. let pano = toPano.pano;
  67114. let dis = pano.position.distanceTo(this.position);
  67115. this.nextPano = pano;
  67116. this.latestToPano = toPano;
  67117. //this.flying = true //防止新的请求
  67118. //Potree.Log('flyToPano:'+pano.id + ' , duration:'+toPano.duration, null, 12)
  67119. {//不飞的话是否不要执行这段?
  67120. let wait = (e)=> {
  67121. //console.log('wait done', pano.id)
  67122. if(/* e.pano && */this.latestToPano && pano != this.latestToPano.pano)return//loadedDepthImg
  67123. if(this.latestToPano != toPano)return Potree.Log('已经取消', pano.id) //如果取消了
  67124. setTimeout(()=>{
  67125. if(this.latestToPano != toPano)return
  67126. this.flyToPano(toPano);
  67127. },1);
  67128. };
  67129. if(!pano.depthTex && pano.pointcloud.hasDepthTex){ //点云模式也要加载depthTex,因获取neighbour需要用到
  67130. console.log('等待加载depthtex', pano.id);
  67131. pano.addEventListener('loadedDepthImg', wait, {once:true});
  67132. return pano.loadDepthImg()
  67133. }
  67134. if(config.atPano.showSkybox || config.atPano.pointUsePanoTex){
  67135. let a = this.updateCube(this.currentPano, toPano.pano);
  67136. if(a == 'useBound'){
  67137. toPano.useBound = true;
  67138. }
  67139. if(this.checkAndWaitForPanoLoad(pano, toPano.basePanoSize || this.basePanoSize, wait )){
  67140. //console.log('等待贴图加载',pano.id)
  67141. return
  67142. }
  67143. }
  67144. }
  67145. Potree.Utils.updateVisible(this.cube,'showSkybox', config.atPano.showSkybox ); // this.cube.visible = config.atPano.showSkybox
  67146. //console.log('开始飞1')
  67147. if(config.transition.showPoint){
  67148. viewer.scene.pointclouds.forEach(e=>{
  67149. Potree.Utils.updateVisible(e, 'displayMode', true);
  67150. });
  67151. }
  67152. if(config.transition.showSkybox || config.transition.pointUsePanoTex){
  67153. this.setProjectedPanos({
  67154. progress:0,
  67155. ifSkybox: this.cube.visible,
  67156. ifPointcloud : config.transition.pointUsePanoTex,
  67157. easeInOutRatio : pointcloudVisi ? 0.3 : 0,
  67158. pano0:this.currentPano,
  67159. pano1:pano
  67160. });
  67161. }
  67162. const endPosition = pano.position.clone();
  67163. let T = Potree.config.transitionsTime;
  67164. /* let maxTime = this.isAtPano() ? T.panoToPanoMax : T.flyIn
  67165. let duration = toPano.duration == void 0 ? (T.flyMinTime+Math.min(T.flytimeDistanceMultiplier * dis, maxTime)) : toPano.duration
  67166. */
  67167. let maxDis = this.isAtPano() ? T.maxDistanceThreshold : T.maxDistanceThresholdFlyIn;
  67168. let duration = toPano.duration == void 0 ? Math.min(dis, T.maxDistanceThreshold) * T.flytimeDistanceMultiplier + T.flyMinTime : toPano.duration;
  67169. if(toPano.useBound){
  67170. duration = Math.min(1500, duration);
  67171. toPano.easeName = 'easeInOutQuad';
  67172. }else {
  67173. if(endPosition.equals(this.position))toPano.easeName = 'easeOutSine';
  67174. }
  67175. {
  67176. toPano.easeName = toPano.easeName || 'linearTween';
  67177. toPano.duration = duration;
  67178. this.beforeFlyToPano(toPano);
  67179. }
  67180. /* let fly = ()=>{
  67181. this.dispatchEvent({type:'flyToPano', toPano})
  67182. viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration,
  67183. callback:()=>{
  67184. if(!config.atPano.pointUsePanoTex){
  67185. viewer.scene.pointclouds.forEach(e=>{
  67186. e.material.stopProjectedPanos()
  67187. })
  67188. }
  67189. this.currentPano = pano;
  67190. this.nextPano = null;
  67191. if(Potree.settings.displayMode == 'showPanos'){
  67192. viewer.scene.pointclouds.forEach(e=>{
  67193. Potree.Utils.updateVisible(e, 'displayMode',pointcloudVisi)
  67194. })
  67195. }
  67196. done(true);
  67197. this.updateDepthTex(this.currentPano)
  67198. }, onUpdate:(progress)=>{
  67199. //console.log('uniforms progress',progress)
  67200. this.cube.material.uniforms.progress.value = progress
  67201. viewer.scene.pointclouds.forEach(e=>{
  67202. e.material.uniforms.progress.value = progress
  67203. })
  67204. },
  67205. cancelFun:()=>{ done(false, true) },
  67206. Easing:easeName
  67207. })
  67208. //duration > 0 && (this.flying = true) //再写一遍 防止cancel其他项目导致flying为false
  67209. } */
  67210. let onUpdate = (progress)=>{
  67211. this.cube.material.uniforms.progress.value = progress;
  67212. viewer.scene.pointclouds.forEach(e=>{
  67213. e.material.uniforms.progress.value = progress;
  67214. });
  67215. };
  67216. let fly = ()=>{
  67217. let startProgress = toPano.progress = toPano.progress || 0;
  67218. let loadNextProgress = MathUtils.clamp(1 - 2.5 / dis, 0.3, 0.8);
  67219. //console.log(loadNextProgress, (1-loadNextProgress) * dis )
  67220. this.dispatchEvent({type:'flyToPano', toPano});
  67221. viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration:toPano.duration,
  67222. onUpdate:(progress_, delta)=>{
  67223. let progress = startProgress + progress_ * (1 - startProgress);
  67224. let currentSpeed;
  67225. if (progress_ != 1 && progress_ != 0) { // 1的时候不准,往往偏小, 0的时候速度为0,也不记录
  67226. currentSpeed = ((progress - toPano.progress) * dis) / delta; //记录下当前速度,当变为匀速时可以过渡到flySpeed
  67227. } else {
  67228. currentSpeed = toPano.currentSpeed || 0;
  67229. }
  67230. toPano.currentSpeed = currentSpeed;
  67231. toPano.progress = progress;
  67232. //console.log('progress_', progress_, 'delta',delta , 'progress', progress/*, 'currentSpeed', currentSpeed, */ )
  67233. if (progress > loadNextProgress && toPano.easeName == 'linearTween' && currentSpeed){// 减速. 如果仅旋转就不停止
  67234. //console.log('减速', /* currentSpeed , */progress_ )
  67235. toPano.easeName = 'easeOutSine';
  67236. let restDis = (1 - progress) * dis;
  67237. toPano.duration = (Math.PI / 2 * restDis) / currentSpeed; // 这样能保证初始速度为currentSpeed
  67238. viewer.scene.view.cancelFlying('all',false); //为了防止执行cancelFun先主动cancel
  67239. toPano.flyCount = 2;
  67240. fly(toPano);
  67241. }
  67242. onUpdate(progress);
  67243. },
  67244. callback:()=>{
  67245. if(!config.atPano.pointUsePanoTex){
  67246. viewer.scene.pointclouds.forEach(e=>{
  67247. e.material.stopProjectedPanos();
  67248. });
  67249. }
  67250. this.lastPano = this.currentPano; //记录,调试
  67251. this.currentPano = pano;
  67252. this.nextPano = null;
  67253. if(Potree.settings.displayMode == 'showPanos'){
  67254. viewer.scene.pointclouds.forEach(e=>{
  67255. Potree.Utils.updateVisible(e, 'displayMode',pointcloudVisi);
  67256. });
  67257. }
  67258. done(true);
  67259. this.updateDepthTex(this.currentPano); //删除dispose的depthTex
  67260. },
  67261. cancelFun:()=>{ done(false, true); },
  67262. Easing:toPano.easeName,
  67263. ignoreFirstFrame : toPano.flyCount != 2 //变换transition时不停一帧
  67264. });
  67265. };
  67266. if(Potree.settings.displayMode == 'showPanos'){
  67267. setTimeout(fly, 40); //更新geo后缓冲
  67268. }else {
  67269. fly();
  67270. }
  67271. //console.log('flyToPano:', toPano.pano.id)
  67272. }
  67273. beforeFlyToPano(toPano){
  67274. if(this.currentPano != toPano.pano) {
  67275. if(Potree.settings.displayMode == 'showPanos'){
  67276. this.resetHighMap();
  67277. }
  67278. this.smoothZoomTo(toPano.zoomLevel || 1, toPano.duration / 2);
  67279. }
  67280. }
  67281. /* updateCube(pano0, pano1){
  67282. if(Potree.settings.displayMode != 'showPanos')return
  67283. if(!viewer.scene.pointclouds.some(e=>!e.hasDepthTex)) return this.updateCube2(pano0, pano1) //都hasDepthTex的话
  67284. let useBound = (bound, size)=>{
  67285. size = size || bound.getSize(new THREE.Vector3)
  67286. let center = bound.getCenter(new THREE.Vector3)
  67287. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  67288. this.cube.scale.copy(size)
  67289. this.cube.position.copy(center)
  67290. }
  67291. let getPanoBound = (pano)=>{//因漫游点可能在点云外部,如室外平地,所以需要union进漫游点
  67292. let panoBound = new THREE.Box3
  67293. panoBound.expandByPoint(pano.position)
  67294. panoBound.expandByVector(new THREE.Vector3(10,10,10));//give pano a margin
  67295. return pano.pointcloud.bound.clone().union(panoBound)
  67296. }
  67297. let getDis = (bound1, bound2)=>{ //获取bound1边界到bound2边界距离
  67298. if(bound1.intersectsBox(bound2))return 0
  67299. let center1 = bound1.getCenter(new THREE.Vector3)
  67300. let center2 = bound2.getCenter(new THREE.Vector3)
  67301. let dis = center1.distanceTo(center2)
  67302. let dis1 = bound1.distanceToPoint(center2)
  67303. let dis2 = bound2.distanceToPoint(center1)
  67304. return dis1 + dis2 - dis
  67305. }
  67306. if(pano1){//过渡
  67307. if(pano0.pointcloud == pano1.pointcloud){//同一个数据集内的过渡
  67308. useBound(getPanoBound(pano0))
  67309. }else{//非同一个数据集内的过渡
  67310. let bound = getPanoBound(pano0).union(getPanoBound(pano1))
  67311. if(getDis(pano0.pointcloud.bound, pano1.pointcloud.bound) < 100){
  67312. useBound(bound)
  67313. }else{//如果两个数据集boundingbox距离大于这个距离,扩大一下,防止精度问题导致失真//对很远的数据集似乎没有什么用
  67314. let size = bound.getSize(new THREE.Vector3)
  67315. let max = Math.max(size.x, size.y, size.z)
  67316. size.set(max,max,max)
  67317. useBound(pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound), size)
  67318. }
  67319. }
  67320. }else{
  67321. useBound(getPanoBound(pano0)) //假定一个数据集不会太大,否则会造成失真,且bump时移动距离看起来很小。或者可以考虑用固定大小
  67322. }
  67323. } */
  67324. getIntersect(pano, dir, origin){
  67325. if(pano && pano.pointcloud.hasDepthTex ){
  67326. return this.depthSampler.sample( {dir }, pano, true )
  67327. }else {
  67328. origin = origin || pano.position;
  67329. return viewer.inputHandler.getIntersect({
  67330. viewport:viewer.inputHandler.hoverViewport,
  67331. onlyGetIntersect:true, usePointcloud:true,
  67332. point: origin.clone().add(dir),
  67333. cameraPos: origin
  67334. })
  67335. }
  67336. }
  67337. /* updateCube(pano0, pano1){//增加细分的版本,且垂直方向上也分多个
  67338. if(Potree.settings.displayMode != 'showPanos')return
  67339. console.log('updateCube',pano0.id, pano1&&pano1.id)
  67340. let f = (bound, size)=>{
  67341. size = size || bound.getSize(new THREE.Vector3)
  67342. let center = bound.getCenter(new THREE.Vector3)
  67343. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  67344. this.cube.scale.copy(size)
  67345. this.cube.position.copy(center)
  67346. }
  67347. this.cube.geometry.dispose();
  67348. if(pano1){//过渡
  67349. let count1, count2;
  67350. let panoIndex = 0
  67351. let add = (pano, dir )=>{
  67352. let getPI = function(index, panoIndex_){
  67353. if(panoIndex_ == void 0) panoIndex_ = panoIndex
  67354. return (count1 * count2 + 2 ) * panoIndex_ + index + 2
  67355. }
  67356. let minZ, maxZ
  67357. minZ = pano.floorPosition.z
  67358. {//天花板高度值
  67359. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  67360. let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  67361. let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
  67362. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  67363. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  67364. let dir2 = dir1.clone().applyMatrix4(rotMat1)
  67365. let dir3 = dir1.clone().applyMatrix4(rotMat2)
  67366. let zs = [dir1,dir2,dir3].map(dir_=>{
  67367. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  67368. let z = intersect ? intersect.location.z : pano.position.z
  67369. return z
  67370. })
  67371. zs.sort((a,b)=>{return b-a});//得最大值
  67372. maxZ = zs[0]
  67373. let min = pano.position.z + 1
  67374. if(maxZ < pano.position.z + 0.04){//户外
  67375. maxZ = pano.position.z + 50
  67376. }
  67377. maxZ = Math.max(min,maxZ)
  67378. console.log(pano.id, 'maxZ:',maxZ )
  67379. console.log(pano.id, 'minZ:',minZ )
  67380. }
  67381. [maxZ, minZ ].forEach(z=>{
  67382. posArr.push(pano.position.clone().setZ(z))
  67383. })
  67384. const angle = Math.PI/8
  67385. let getDir = (angle_)=>{
  67386. let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
  67387. return dir.clone().applyMatrix4(rotMat)
  67388. }
  67389. 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度
  67390. count1 = dirs.length
  67391. dirs.forEach((dir, index)=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
  67392. let dirs_ = [
  67393. dir.clone().setZ(Math.tan(THREE.Math.degToRad(30))).normalize(),
  67394. dir.clone().setZ(Math.tan(THREE.Math.degToRad(15))).normalize(),
  67395. dir.clone(), // 水平方向
  67396. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(15))).normalize(),
  67397. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  67398. ];
  67399. count2 = dirs_.length
  67400. dirs_.forEach((dir_, i) =>{
  67401. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  67402. let location
  67403. if(!intersect){ //超级远
  67404. let distance = 100
  67405. location = dir_.clone().multiplyScalar(distance).add(pano.position)
  67406. intersect = {distance,location}
  67407. }
  67408. //intersect.distance
  67409. location = intersect.location.clone()
  67410. let shouldZ// = THREE.Math.clamp(intersect.location.z, minZ, maxZ);
  67411. let needShrink = false
  67412. if(i == 0){//最上方的点高度直接等于天花板
  67413. shouldZ = maxZ
  67414. if(location.z<maxZ)location.z = maxZ
  67415. else needShrink = true
  67416. }else if(i == count2-1){//最下方的点高度直接等于地板
  67417. shouldZ = minZ
  67418. if(location.z>minZ)location.z = minZ
  67419. else needShrink = true
  67420. }
  67421. if(needShrink ){//需要在保持dir_不变的情况下修改z
  67422. let len = (shouldZ - pano.position.z) / (intersect.location.z - pano.position.z) * intersect.distance
  67423. location = dir_.clone().multiplyScalar(len).add(pano.position)
  67424. }
  67425. posArr.push(location)
  67426. if(index!=0 && i!=0){//加入一块四方面
  67427. let curIndex = getPI(count2 * index + i);
  67428. faceArr.push([curIndex-1, curIndex-count2-1, curIndex-count2],
  67429. [curIndex-1, curIndex, curIndex-count2])
  67430. }
  67431. })
  67432. if(index!=0){
  67433. let top = -2;
  67434. let btm = -1
  67435. faceArr.push([getPI(count2*(index-1) ), getPI(count2*index ), getPI(top) ])//天花板扇形
  67436. faceArr.push([getPI(count2*index-1), getPI(count2*(index+1)-1), getPI(btm) ] )//地板扇形
  67437. }else{
  67438. //加入和另一个pano连接的其中一个侧边
  67439. let panoIndex2 = (panoIndex + 1) % 2;
  67440. for(let i=1;i<count2;i++){
  67441. faceArr.push([getPI(i-1), getPI(i), getPI((count1-1)*count2 +i, panoIndex2)],
  67442. [getPI(i-1), getPI((count1-1)*count2+i , panoIndex2) , getPI((count1-1)*count2+i-1 ,panoIndex2)])
  67443. }
  67444. faceArr.push([getPI(0), getPI((count1-1)*count2), getPI(0, panoIndex2)])//加入顶部的一半
  67445. faceArr.push([getPI(count2-1), getPI(count1*count2-1), getPI(count2-1, panoIndex2)])//加入底部的一半
  67446. }
  67447. });
  67448. panoIndex ++
  67449. }
  67450. let posArr = [];
  67451. let faceArr = []
  67452. //两点连线的水平向量
  67453. let vec = new THREE.Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize()
  67454. add(pano0, vec)
  67455. add(pano1, vec.negate())
  67456. let geo = MeshDraw.createGeometry(posArr, faceArr)
  67457. this.cube.geometry = geo
  67458. this.cube.scale.set(1,1,1);
  67459. this.cube.position.set(0,0,0)
  67460. }else{
  67461. this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
  67462. f(pano0.pointcloud.bound)
  67463. }
  67464. } */
  67465. isNeighbour(pano0, pano1, {dontCompute, onlyUseTex, computeDirFirst, computeTwoDir}={}){//是否之间没有遮挡(在加载visibles之前,自己算) 最好pano0是currentPano
  67466. if(!pano0 || !pano1 )return
  67467. let margin = 0.1;
  67468. let map0 = this.neighbourMap[pano0.id]; //主
  67469. let map1 = this.neighbourMap[pano1.id]; //副
  67470. //三个方向 : position0到position1, position0到floorPosition1, position1到floorPosition0。 只要有一个满足ifNeighbour就为true。 不过为了不使sampler总换图,先只考虑从主pano到副pano的方向
  67471. //0能看到1不代表1能看到0; 但只要有一方能完全看到另一方,无论是position还是floorPosition都算是neighbor
  67472. //也正因此,全部计算完两两之间的neighbour后,neighbourMap也看起来有缺的样子,必须得通过isNeighbour函数来判断是否是邻居
  67473. let ifNeighbour;
  67474. if(map0[pano1.id] != void 0){
  67475. ifNeighbour = map0[pano1.id];
  67476. }
  67477. if(!ifNeighbour && map1[pano0.id] != void 0){
  67478. ifNeighbour = map1[pano0.id];
  67479. }
  67480. if(dontCompute) return ifNeighbour
  67481. let getNeighbour = (mainPano, subPano, jumpStep1, simpleJudge)=>{
  67482. //暂时只判断到pano,不判断到marker的方向
  67483. let dirPoints = [];
  67484. if(!jumpStep1){//跳过此步骤,因为之前算过不成功(虽然用另一个漫游点算的可能拍摄时间不同所以有概率不一样,如人走动)
  67485. dirPoints.push([subPano.position, mainPano.position]);
  67486. }
  67487. if(!simpleJudge){
  67488. dirPoints.push([subPano.floorPosition.clone().add(new Vector3(0,0,0.1)), mainPano.position]);
  67489. }
  67490. for(let i=0; i<dirPoints.length; i++){
  67491. let dir = new Vector3().subVectors(dirPoints[i][0], dirPoints[i][1]).normalize();
  67492. let intersectPoint = viewer.images360.depthSampler.sample({dir}, mainPano, true);
  67493. if(!intersectPoint || intersectPoint.distance+margin > pano0.position.distanceTo(pano1.position)){
  67494. return true
  67495. }
  67496. }
  67497. };
  67498. if(!ifNeighbour && (map0[pano1.id] == void 0 || (computeTwoDir && map1[pano0.id] == void 0))) {//主方向为空且不为邻居
  67499. let simpleJudge = pano0.position.distanceToSquared(pano1.position) > 300; //在远处去掉对floorPosition的判断
  67500. if(pano0.depthTex || pano1.depthTex){
  67501. if(map0[pano1.id] == void 0 && pano0.depthTex){
  67502. let is = getNeighbour(pano0, pano1, null, simpleJudge);
  67503. if(is){
  67504. ifNeighbour = true;
  67505. }else if(simpleJudge){
  67506. ifNeighbour = false;
  67507. }
  67508. map0[pano1.id] = !!is;
  67509. }
  67510. if(map1[pano0.id] == void 0 && pano1.depthTex){
  67511. let is = getNeighbour(pano1, pano0, !ifNeighbour, simpleJudge);
  67512. if(is){
  67513. ifNeighbour = true;
  67514. }else if(simpleJudge){
  67515. ifNeighbour = false;
  67516. }
  67517. map1[pano0.id] = !!is;
  67518. }
  67519. ifNeighbour = !!ifNeighbour;
  67520. //console.log('isNeighbour', pano0, pano1, ifNeighbour)
  67521. /* if(ifNeighbour){ //需要标记成全部true吗,不标记也能get到,但标记了更直观,不标记保留信息更多
  67522. map0[pano1.id] = map1[pano0.id] = true
  67523. } */
  67524. }else if(!onlyUseTex){//使用点云判断(有深度贴图时不会执行到这)
  67525. /* if(this.panos.length > 15 && !force){
  67526. return 'noCompute' //数量过多会卡
  67527. }else{ */
  67528. /* ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({point:pano1.position, margin, cameraPos:pano0.position})
  67529. //console.log('使用点云判断')
  67530. if(ifNeighbour){//点云模式下未加载的点云会判断为true
  67531. let dir = new THREE.Vector3().subVectors(pano1.position,pano0.position).normalize()
  67532. let dis = pano1.position.distanceTo(pano0.position)
  67533. let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true );
  67534. let max = Math.cos(THREE.Math.degToRad(10))
  67535. let min = Math.cos(THREE.Math.degToRad(80))
  67536. if(this.getDirection().dot(dir) < THREE.Math.clamp(Math.cos(hfov/2 ) * dis / 10, min, max )){//距离越远要求和视线角度越接近
  67537. }
  67538. }*/
  67539. let inDirection = ()=>{
  67540. let dir = new Vector3().subVectors(pano1.position,pano0.position).normalize();
  67541. let dis = pano1.position.distanceTo(pano0.position);
  67542. let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true );
  67543. let max = Math.cos(MathUtils.degToRad(10));
  67544. let min = Math.cos(MathUtils.degToRad(80));
  67545. if(this.getDirection().dot(dir) > MathUtils.clamp(Math.cos(hfov/2 ) * dis / 10, min, max )){//距离越远要求和视线角度越接近
  67546. return true
  67547. }
  67548. };
  67549. if(computeDirFirst){//先计算方向,防止重复计算ifBlockedByIntersect
  67550. if(inDirection()){
  67551. ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({point:pano1.position, margin, cameraPos:pano0.position});
  67552. }
  67553. }else {
  67554. ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({point:pano1.position, margin, cameraPos:pano0.position});
  67555. if(ifNeighbour && !inDirection()){
  67556. ifNeighbour = undefined; //不确定
  67557. }
  67558. }
  67559. //}
  67560. map0[pano1.id] = map1[pano0.id] = ifNeighbour ? 'byCloud' : ifNeighbour;//写简单点
  67561. }
  67562. }
  67563. if(ifNeighbour){
  67564. pano0.neighbours.includes(pano1) || pano0.neighbours.push(pano1);
  67565. pano1.neighbours.includes(pano0) || pano1.neighbours.push(pano0);
  67566. }
  67567. return ifNeighbour
  67568. }
  67569. bump(direction) {//撞墙弹回效果
  67570. if (!this.bumping && !this.latestToPano) {
  67571. let distance = Potree.settings.displayMode == 'showPanos' ? 0.15 : 0.12;//感觉点云模式比全景模式更明显,所以降低
  67572. let currentPos = this.position.clone();
  67573. let endPosition = new Vector3().addVectors(this.position, direction.clone().multiplyScalar(distance));
  67574. let duration = 150;
  67575. viewer.scene.view.setView({position:endPosition, duration,
  67576. callback:()=>{
  67577. viewer.scene.view.setView({position:currentPos, duration: duration*5,
  67578. callback: ()=>{
  67579. this.bumping = false;
  67580. //this.dispatchEvent('cameraMoveDone')
  67581. },
  67582. Easing:'easeInOutSine',
  67583. cancelFun:()=>{this.bumping = false;}
  67584. });
  67585. this.bumping = true;
  67586. },
  67587. cancelFun:()=>{this.bumping = false;},
  67588. Easing:'easeInOutSine'
  67589. });
  67590. this.bumping = true;
  67591. }
  67592. //备注:将4dkk中的‘前后方向变化fov、左右方向移动镜头’ 都改为移动镜头。 因为这里无法判断左右离壁距离。
  67593. }
  67594. flyToPanoClosestToMouse() {
  67595. /* if (Date.now() - this.mouseLastMoveTime > 50) {
  67596. //this.intersect = this.getMouseIntersect();
  67597. this.intersect && this.updateClosestPano(this.intersect);
  67598. } */
  67599. if(!Potree.settings.ifShowMarker){//不显示marker的时候mousemove没更新鼠标最近点所以更新
  67600. this.updateClosestPano(viewer.inputHandler.intersect);
  67601. }
  67602. //console.log('flyToPanoClosestToMouse',this.closestPano)
  67603. if (this.closestPano) {
  67604. let pano = this.closestPano;
  67605. return this.flyToPano({
  67606. pano, easeName: this.isAtPano() ? 'linearTween' : 'easeInOutQuad'
  67607. });
  67608. }
  67609. var direction = this.viewer.inputHandler.getMouseDirection().direction;
  67610. this.flyDirection(direction);
  67611. }
  67612. flyDirection(direction, option1, option2, byKey) {
  67613. if(viewer.mainViewport.view.isFlying()){// closestPanoInDirection函数耗时长,飞行时运行会卡顿(如果以后加无缝过渡再说)
  67614. return
  67615. }
  67616. var deferred = $.Deferred();
  67617. //this.history.invalidate();
  67618. var panoSet = this.closestPanoInDirection(direction, option1, option2, byKey);
  67619. if (panoSet) {
  67620. this.flyToPano({
  67621. pano: panoSet,
  67622. callback: deferred.resolve.bind(deferred, !0)
  67623. } );
  67624. } else {
  67625. //如果离数据集较远,转动也很难找到点云,就飞到就近点:
  67626. let po = viewer.scene.pointclouds.find(e=>e.visibleNodes.some(a=>a.getLevel() > Math.ceil(e.maxLevel * 0.15) )); //虽然当点云在前方很远的地方也可能符合
  67627. if(!po){//无可见点云
  67628. //console.log('no visi cloud')
  67629. if(!this.panos.length){//如果场景中没有漫游点,如SG-t-XPf1k9pv3Zg 点击后回到可见区域
  67630. let map = new Map();
  67631. let clouds = viewer.scene.pointclouds.filter(e=>e.root.geometryNode);
  67632. clouds.forEach(e=>map.set(e, e.bound.distanceToPoint(this.position)));
  67633. clouds.sort((a,b)=>map.get(a) - map.get(b));
  67634. viewer.flyToDataset({focusOnPoint:true, pointcloud:clouds[0], duration:500 });//飞最近的一个点云
  67635. return deferred.promise();
  67636. }
  67637. this.flyToPano({
  67638. pano: this.findNearestPano(),
  67639. duration:500,
  67640. callback: deferred.resolve.bind(deferred, !0)
  67641. });
  67642. return deferred.promise();
  67643. }
  67644. this.bump(direction);
  67645. deferred.resolve(!1);
  67646. }
  67647. return deferred.promise();
  67648. }
  67649. closestPanoInDirection(direction, option1, option2, byKey) {
  67650. return this.rankedPanoInDirection(0, direction, option1, option2, byKey)
  67651. }
  67652. rankedPanoInDirection(t, direction, option1, option2, byKey){
  67653. //此direction为mouseDirection,是否需要加上相机角度的权重
  67654. let startTime = Date.now();
  67655. var panoSet = {
  67656. pano: null,
  67657. candidates: [] //缓存顺序--如果需要打印的话
  67658. };
  67659. t || (t = 0);
  67660. option1 = void 0 !== option1 ? option1 : .75;
  67661. var o = option2 ? "angle" : "direction";
  67662. var floor = viewer.modules.SiteModel.currentFloor;
  67663. var entity = viewer.modules.SiteModel.inEntity;
  67664. var getHeightDis = (pano)=>{
  67665. if(floor && !floor.panos.includes(pano) && pano.position.z < this.position.z){ //若是上方的漫游点,就正常走。因为一般不会点击天花板。
  67666. return this.position.z - pano.position.z
  67667. }else {
  67668. return 0
  67669. }
  67670. };
  67671. let disSquareMap = new Map();
  67672. this.panos.forEach(pano=>{
  67673. let dis2 = pano.position.distanceToSquared(this.position); //距离目标点
  67674. disSquareMap.set(pano, dis2);
  67675. });
  67676. let changeTexCount = 0, maxWaitDur = 300;
  67677. //maxSamplerChangeTex = THREE.Math.clamp( maxWaitDur / Potree.timeCollect.depthSampler.median, 2, 10) //计算换贴图最大数目
  67678. var request = [//必要条件
  67679. Images360.filters.not(this.currentPano),
  67680. Images360.filters.isEnabled(),
  67681. Images360.filters.inFloorDirection( this.position, direction, option1 ), //原先用inPanoDirection,但容易穿楼层,当mouse较低或较高
  67682. (pano)=>{
  67683. /* let isNeighbour = this.isNeighbour(this.currentPano, pano, true, true); //不计算的
  67684. if(isNeighbour == void 0){
  67685. let willChangeTex = pano.depthTex && !this.depthSampler.imgDatas.some(e=>e.pano == pano)
  67686. if(changeTexCount < maxSamplerChangeTex || !willChangeTex ){
  67687. isNeighbour = this.isNeighbour(this.currentPano, pano, false, true);//计算
  67688. if(willChangeTex && isNeighbour != void 0) changeTexCount++
  67689. }else{
  67690. if(disSquareMap.get(pano) < 500)return true //因为费时,超过一定个数就不计算了,距离近的话先可通行。
  67691. }
  67692. } */
  67693. // 不会再changeTex了
  67694. let isNeighbour = this.isNeighbour(this.currentPano, pano, {onlyUseTex:true});
  67695. if(isNeighbour || pano.noNeighbour && disSquareMap.get(pano) < 200){//在靠近孤立点时可以通行。但是不好把握这个距离,太远的话很多地方都会不小心到孤立点,太近的话可能永远到不了。
  67696. return true
  67697. }
  67698. },
  67699. /* (pano)=>{ //防止不小心穿越地板到下一层, 尽量走楼梯,实在没有楼梯或楼梯漫游点稀疏的话就通过楼层按钮。
  67700. let dis = getHeightDis(pano)
  67701. //console.log('getHeightDis',pano.id,dis)
  67702. if(dis < 3){//不能超过最大高度差( 最大高度差暂定为接近一层楼的高度。)(最好的解决方案是设置漫游可行)
  67703. return true
  67704. }else{
  67705. return this.isNeighbour(this.currentPano, pano)
  67706. }
  67707. } */
  67708. ];
  67709. if(!byKey){
  67710. Images360.filters.inPanoDirection( this.position, this.getDirection(), option1/* , true */); //垂直方向上再稍微限制一下, 要接近视线方向,避免点击前方时因无路而到下一楼。但不能太高,否则楼梯上稍微朝下点击都到不了上方。之所以使用视线方向是因为镜头方向比鼠标方向目的性更强。
  67711. }
  67712. var list = [//决胜项目
  67713. (pano)=>{
  67714. return -disSquareMap.get(pano)
  67715. },
  67716. Images360.scoreFunctions[o]( this.position, direction, true),
  67717. (pano)=>{
  67718. let neighbour = this.isNeighbour(this.currentPano, pano, {dontCompute:true, isNeighbour:true}); //不计算的
  67719. return neighbour ? directionFactor : 0;
  67720. } ,
  67721. /* (pano)=>{//尽量不穿越地板到下一层
  67722. let dis = getHeightDis(pano)
  67723. return -dis * directionFactor * 0.1;
  67724. }, */
  67725. /* (pano)=>{ //尽量在一个建筑内行走,这样不易穿墙
  67726. let score = 0
  67727. if(entity ){
  67728. if(!entity.panos.includes(pano) ) score -= directionFactor * 0.01; //不能设置太高,否则会走不进大房间的小房间中,因为容易穿过小房间的一个门到另一个门外
  67729. if(!floor.panos.includes(pano)) {//避免穿楼层
  67730. let heightDiff = Math.abs(pano.position.z - this.position.z);
  67731. if(heightDiff > 2){
  67732. score -= directionFactor * 0.1 * heightDiff;
  67733. }
  67734. }
  67735. }
  67736. return score
  67737. } */
  67738. ];
  67739. if(!byKey && viewer.inputHandler.intersect && this.currentPano ){//方便上下楼, 考虑panos之间的角度差
  67740. let pos1 = this.currentPano.floorPosition;
  67741. let vec1 = new Vector3().subVectors(viewer.inputHandler.intersect.location, pos1 ).normalize();//应该只有atPano时才会执行到这吧?
  67742. list.push( function(pano) {
  67743. var pos2 = pano.floorPosition;
  67744. var vec2 = pos2.clone().sub(pos1).normalize();
  67745. return vec2.dot(vec1) * directionFactor * 4
  67746. });
  67747. }
  67748. this.findRankedByScore(t,request,list,panoSet);
  67749. //console.log( 'costTime:',Date.now() - startTime)
  67750. return panoSet.pano;
  67751. }
  67752. findRankedByScore(e, t, i, n) {
  67753. n && (n.candidates = null, //candidates 缓存顺序--如果需要打印的话
  67754. n.pano = null),
  67755. e || (e = 0);
  67756. var r = Common$1.sortByScore(this.panos, t, i);
  67757. //console.log('findRankedByScore', r && r.map(u=>u.item.id + '| ' + math.toPrecision(u.score,4) + " | " + math.toPrecision(u.scores,4)))
  67758. return !r || 0 === r.length || e >= r.length ? null : (n && (n.candidates = r,
  67759. n.pano = r[e].item),
  67760. r[e].item)
  67761. }
  67762. updateClosestPano(intersect, state) {//hover到的pano 大多数时候是null
  67763. var pano;
  67764. if(intersect instanceof Panorama){ //漫游模式
  67765. pano = state ? intersect : null;
  67766. }else {
  67767. if(this.isAtPano() || this.bumping){
  67768. return
  67769. }else {
  67770. var filterFuncs = [];
  67771. intersect = intersect && intersect.location;
  67772. if(!intersect)return
  67773. let sortFuncs = Potree.settings.editType != 'pano'? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)];
  67774. pano = Common$1.find(this.panos, filterFuncs, sortFuncs);
  67775. }
  67776. }
  67777. if (pano != this.closestPano) {
  67778. pano && (this.isPanoHover = !0);
  67779. this.closestPanoChanging(this.closestPano, pano); // 高亮marker
  67780. //console.log('closestPano '+ (pano ? pano.id : 'null' ))
  67781. this.closestPano = pano;
  67782. } else {
  67783. this.isPanoHover = !1;
  67784. }
  67785. }
  67786. closestPanoChanging(oldPano, newPano){
  67787. if(!Potree.settings.ifShowMarker)return
  67788. oldPano && oldPano.hoverOff({byImages360:true});
  67789. newPano && newPano.hoverOn({byImages360:true});
  67790. }
  67791. getTileDirection(){//根据不同dataset的来存储
  67792. var vectorForward = viewer.scene.view.direction.clone();
  67793. var vectorForwards = viewer.scene.pointclouds.map(e=>{
  67794. var inv = new Matrix4().copy(e.rotateMatrix).invert();//乘上dataset的旋转的反转
  67795. var direction = vectorForward.clone().applyMatrix4(inv);
  67796. return {
  67797. datasetId: e.dataset_id,
  67798. direction: math.convertVector.ZupToYup(direction)
  67799. }
  67800. });
  67801. //return vectorForwards[0].direction
  67802. return {
  67803. datasetsLocal: vectorForwards,
  67804. vectorForward
  67805. }
  67806. }
  67807. update(){
  67808. //if(this.tileDownloader.started){
  67809. var vectorForwards = this.getTileDirection();
  67810. //vectorForwards = vectorForwards[0].direction
  67811. this.updateTileDownloader(tileArr, vectorForwards);
  67812. this.updatePanoRenderer(vectorForwards);
  67813. //}
  67814. this.updateZoomPano();
  67815. }
  67816. updateTileDownloader(t, vectorForward) {
  67817. var i = this.nextPano || this.currentPano;
  67818. if(i){
  67819. this.tileDownloader.tilePrioritizer.updateCriteria(i, viewer.scene.view.position.clone() , vectorForward, t.length > 0 ? t : null),
  67820. this.tileDownloader.processPriorityQueue = !0;
  67821. }
  67822. }
  67823. updatePanoRenderer(vectorForward) {
  67824. var i = this.nextPano || this.currentPano;
  67825. if(i){
  67826. if (this.panoRenderer.hasQueuedTiles() && i) {
  67827. this.panoRenderer.updateDirection(vectorForward);
  67828. }
  67829. }
  67830. }
  67831. //等待部分加载完
  67832. checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, l) {
  67833. if (!pano) {
  67834. console.error("Player.checkAndWaitForTiledPanoLoad() -> Cannot load texture for null pano.");
  67835. }
  67836. var vectorForward = this.getTileDirection();
  67837. if (!pano.isLoaded(basePanoSize)) {
  67838. iswait && viewer.waitForLoad(pano, function() {//发送loading
  67839. return pano.isLoaded(basePanoSize)
  67840. });
  67841. /* var fov = {//test for direction 预加载的边缘有一丢丢不准确,尤其在相机倾斜时(4dkk也是)。
  67842. hFov: cameraLight.getHFOVForCamera(viewer.scene.getActiveCamera() ),
  67843. vFov: viewer.scene.getActiveCamera().fov
  67844. }//原先是null,不要求方向 */
  67845. var fov = null; //若不为null的话,因为可能可见范围的tile下载过了从而无法触发下载,然后得不到下载成功的消息,怎么办
  67846. pano.loadTiledPano(/* 1024 */ basePanoSize , vectorForward, fov, isclear, l, null).done(function(e, t) {
  67847. callback1 && callback1(e, t);
  67848. }
  67849. .bind(this)).fail(function(msg) {
  67850. callback2 && callback2(msg);
  67851. }
  67852. .bind(this)).progress(function(e, t, i) {
  67853. progressCallback && progressCallback(e, t, i);
  67854. }
  67855. .bind(this));
  67856. return !0;
  67857. }
  67858. }
  67859. fitPanoTowardPoint(o){ //寻找最适合的点位
  67860. var point = o.point, //相机最佳位置
  67861. target = o.target || o.point, //实际要看的位置
  67862. require = o.require || [],
  67863. rank = o.rank || [],
  67864. force = o.force,
  67865. getAll = o.getAll,
  67866. bestDistance = o.bestDistance || 0,
  67867. sameFloor = o.sameFloor,
  67868. maxDis = o.maxDis,
  67869. dir = o.dir;
  67870. let camera = viewer.scene.getActiveCamera();
  67871. if(target && !dir){
  67872. dir = new Vector3().subVectors(target,point).normalize();
  67873. }
  67874. let atFloor = sameFloor && viewer.modules.SiteModel.pointInWhichEntity(point, 'floor');
  67875. //if(o.floor)require.push(Panorama.filters.atFloor(o.floor))
  67876. let checkIntersect = o.checkIntersect;
  67877. let base = Math.max(300, viewer.bound.boundSize.length()*3);
  67878. if(o.boundSphere){//只接受boundSphere
  67879. let aspect = 1;//size.x / size.y
  67880. let dis;
  67881. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  67882. dis = /* size.y */o.boundSphere.radius/* / 2 *// MathUtils.degToRad(camera.fov / 2);
  67883. }else {
  67884. let hfov = cameraLight.getHFOVForCamera(camera , true );
  67885. dis = /* size.x */ o.boundSphere.radius /* / 2 */ / (hfov / 2);
  67886. }
  67887. bestDistance = dis;//*0.8
  67888. }
  67889. let disSquareMap = new Map();
  67890. let bestDisSquared = bestDistance * bestDistance;
  67891. let maxDisSquared = maxDis && (maxDis * maxDis);
  67892. this.panos.forEach(pano=>{
  67893. let dis2 = pano.position.distanceToSquared(target); //距离目标点
  67894. disSquareMap.set(pano, dis2);
  67895. });
  67896. let panos = this.panos.sort((p1,p2)=>{return disSquareMap.get(p1)-disSquareMap.get(p2)});
  67897. if(maxDisSquared){//热点超过最大距离不可见的
  67898. let panos2 = [], pano, i=0;
  67899. while(pano = panos[i], disSquareMap.get(pano) < maxDisSquared){
  67900. panos2.push(pano);
  67901. i++;
  67902. }
  67903. if(panos2.length == 0)return {pano, msg:'tooFar'} //全部都大于maxDis, 就返回最近的
  67904. panos = panos2;
  67905. }
  67906. rank.push((pano)=>{
  67907. let dis1 = Math.abs(pano.position.distanceToSquared(point) - bestDisSquared); //距离最佳位置
  67908. disSquareMap.set(pano, dis1);
  67909. if(!target){
  67910. return -dis1
  67911. }else {
  67912. let dis2 = disSquareMap.get(pano);
  67913. if(o.gotoBestView){//忽略和当前视线的角度
  67914. return -(dis1 + dis2*0.3)
  67915. }
  67916. let vec2 = new Vector3().subVectors(target,pano.position).normalize();
  67917. let cos = dir.dot(vec2);
  67918. //let result = (- dis1 - Math.pow(dis2 , 1.5)) / (cos + 2) // cos+2是为了调整到1-3,
  67919. let result = (dis1 + dis2*0.3) * ( -1 + cos*0.9 ); //尽量贴近最佳位置的角度, 或贴近相机原来的角度 。尽量靠近最佳观测点,并且优先选择靠近目标点的位置.(注意cos的乘数不能太接近1,否则容易只考虑角度)
  67920. //Potree.Log(pano.id, dis1, dis2, cos, result,{font:{toFixed:2,fontSize:10}})
  67921. return result
  67922. }
  67923. //注:热点最好加上法线信息,这样可以多加一个限制,尽量顺着热点像展示的方向。
  67924. },
  67925. (pano)=>{
  67926. let score = 0;
  67927. if(pano.depthTex && checkIntersect){
  67928. let intersect = !!viewer.ifPointBlockedByIntersect(target, pano.id, true); //viewer.inputHandler.ifBlockedByIntersect({point:target, margin:0.1, cameraPos:pano})
  67929. if(intersect){
  67930. score = 0;
  67931. }else {
  67932. score = base * 2;
  67933. }
  67934. }else {
  67935. score = base * 1.5; //没加载好的话,不管了 , 几乎当做无遮挡,否则容易到不了最近点
  67936. }
  67937. return score
  67938. }
  67939. );
  67940. var g = Common$1.sortByScore(panos, require, rank);
  67941. // console.log(g)
  67942. /* let result1 = g && g.slice(0, 10)
  67943. if(result1){
  67944. g = Common.sortByScore(result1, [], [(e)=>{//避免遮挡
  67945. let pano = e.item;
  67946. let score = 0, log = ''
  67947. if(atFloor && atFloor.panos.includes(pano)){//如果不在任何一楼呢?
  67948. score += 600, log+='atFloor'
  67949. }
  67950. return {score, log}
  67951. }]);
  67952. if(g){
  67953. g.forEach(e=>{e.item = e.item.item})
  67954. }
  67955. console.log(g)
  67956. } */
  67957. let pano = g && g.length > 0 && g[0].item;
  67958. if(pano && checkIntersect){
  67959. let intersect = !!viewer.ifPointBlockedByIntersect(target, pano.id, true);
  67960. if(intersect){
  67961. return {pano, msg : 'sheltered'}
  67962. }
  67963. }
  67964. //if(getAll)return g;
  67965. return pano
  67966. //注:深度图有的位置会不准确,以至于会算出错误的遮挡、选择错误的pano,解决办法只能是移动下热点到更好的位置
  67967. }
  67968. //---------------scroll zoom ------------------------------------------
  67969. /* zoomIn = function() { //放大
  67970. this.zoomBy(1 + this.zoomSpeed);
  67971. }
  67972. zoomOut = function() {//缩小
  67973. this.zoomBy(1 - this.zoomSpeed);
  67974. } */
  67975. zoomBy(e, pointer) {//以倍数
  67976. this.zoomTo(this.zoomLevel * e, pointer);
  67977. }
  67978. zoomTo(zoomLevel, pointer) {//缩放到某绝对zoomLevel
  67979. let zoom = Potree.settings.zoom;
  67980. if (zoom.enabled) {
  67981. zoomLevel = MathUtils.clamp(zoomLevel, zoom.min, zoom.max);
  67982. //console.log(zoomLevel)
  67983. if(zoomLevel == this.zoomLevel) return;
  67984. /* if (zoomLevel > this.zoomLevel) {
  67985. this.emit(ZoomEvents.ZoomIn);
  67986. zoomLevel === settings.zoom.max && this.emit(ZoomEvents.ZoomMax);
  67987. } else if (zoomLevel < this.zoomLevel) {
  67988. this.emit(ZoomEvents.ZoomOut);
  67989. zoomLevel === settings.zoom.min && this.emit(ZoomEvents.ZoomMin);
  67990. } */
  67991. this.zoomLevel = zoomLevel;
  67992. //定点缩放:使当前鼠标所在的位置缩放后不变
  67993. let view = viewer.scene.view;
  67994. let originDir = viewer.scene.view.direction;
  67995. let oldPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  67996. viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel));
  67997. let newPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  67998. view.direction = oldPointerDir; //获取一下鼠标所在位置的yaw 和 pitch
  67999. let oldPitch = view.pitch, oldYaw = view.yaw;
  68000. view.direction = newPointerDir;
  68001. let newPitch = view.pitch, newYaw = view.yaw;
  68002. view.direction = originDir; //还原
  68003. viewer.scene.view.pitch -= newPitch - oldPitch;
  68004. viewer.scene.view.yaw -= newYaw - oldYaw;
  68005. }
  68006. }
  68007. zoomFovTo( fov ) { //通过fov来算zoomLevel
  68008. let zoomLevel = Potree.config.view.fov /* this.baseFov */ / fov;
  68009. this.zoomTo( zoomLevel );
  68010. }
  68011. smoothZoomTo(aimLevel, dur=0) {
  68012. var currentLevel = this.zoomLevel;
  68013. if(currentLevel == aimLevel)return;
  68014. var fun = (progress)=>{
  68015. //progress > 1 && (progress = 1)
  68016. let level = currentLevel * (1 - progress) + aimLevel * progress;
  68017. this.zoomTo(level, !0);
  68018. };
  68019. transitions.start(fun, dur, null, null, 0 , easing['easeInOutQuad'] );
  68020. }
  68021. updateZoomPano() {
  68022. if (!this.panoRenderer.zoomPanoRenderingDisabled && Potree.settings.displayMode == 'showPanos') {
  68023. var currentPano = this.currentPano;
  68024. if (currentPano) {
  68025. let levelThreshold1 = Potree.settings.navTileClass == '1k' ? 1.3 : 1.7 , levelThreshold2 = 2;
  68026. var t = this.zoomLevel > levelThreshold1,
  68027. n = !(this.flying && this.nextPano && this.nextPano !== this.currentPano),
  68028. r = t && n;
  68029. this.tileDownloader.tilePrioritizer.setZoomingActive(r);
  68030. this.panoRenderer.setZoomingActive(r, currentPano, !0);
  68031. var o = (pano, ifZoom)=>{
  68032. this.panoRenderer.resetRenderStatus(pano.id, !1, !0, this.qualityManager.getMaxNavPanoSize());
  68033. this.panoRenderer.clearAllQueuedUploadsForPano(pano.id);
  68034. this.panoRenderer.renderPanoTiles(pano.id, null, !1, !1);
  68035. pano.setZoomed(ifZoom);
  68036. };
  68037. if (r && (!currentPano.zoomed || this.qualityManager.zoomLevelResolution && this.qualityManager.zoomLevelResolution != '4k')) {//needZoom
  68038. currentPano.zoomed || o(currentPano, !0);
  68039. if(Potree.settings.navTileClass == '1k' && Potree.settings.tileClass != '1k' && this.zoomLevel < levelThreshold2){
  68040. this.panoRenderer.enableHighQuality( function() {//开启2k
  68041. if(Potree.settings.tileClass != '4k') o(currentPano, !0);
  68042. }.bind(this));
  68043. }else {
  68044. this.panoRenderer.enableUltraHighQualityMode(function() {//开启4k getMaxZoomPanoSize
  68045. this.qualityManager.useUltraHighResolutionPanos && (Potree.settings.zoom.max = Potree.config.ultraHighQualityMaxZoom);
  68046. o(currentPano, !0);
  68047. }.bind(this));
  68048. }
  68049. } else {
  68050. !t && currentPano.zoomed && o(currentPano, !1);
  68051. }
  68052. if(r && Potree.settings.navTileClass == '1k' && Potree.settings.tileClass == '4k' ){ //目前只有手机端navTileClass == '1k' (分三个梯度)
  68053. var change = (zoomedFlag)=>{
  68054. this.qualityManager.updateMaximums();//更新maxZoomPanoSize
  68055. this.panoRenderer.setupZoomRenderTarget(); //更新renderTarget
  68056. //currentPano.setZoomed(t);//更新uniforms贴图
  68057. };
  68058. this.qualityManager.zoomLevelResolution = this.zoomLevel >= levelThreshold2 ? '4k' : this.zoomLevel > levelThreshold1 ? '2k' : '1k';
  68059. if(this.oldZoomLevel < levelThreshold2 && this.zoomLevel >= levelThreshold2){//1k/2k-4k
  68060. change();
  68061. o(currentPano, t);
  68062. }else if(this.oldZoomLevel <= levelThreshold1 && this.zoomLevel > levelThreshold1){//1k-2k
  68063. change();
  68064. }else if(this.oldZoomLevel > levelThreshold2 && this.zoomLevel <= levelThreshold2){//4k-2k/1k
  68065. change();
  68066. o(currentPano, t);
  68067. }else if(this.oldZoomLevel > levelThreshold1 && this.zoomLevel <= levelThreshold1){//2k-1k
  68068. change();
  68069. }
  68070. this.oldZoomLevel = this.zoomLevel;
  68071. }
  68072. }
  68073. }
  68074. }
  68075. //--------------------
  68076. addHighMapCube(){//创建8*8的tile cube 主要因手机版崩溃 要在电脑端测试得设置maxRenderTargetSize
  68077. if( Potree.settings.tileClass == '4k' && this.qualityManager.maxRenderTargetSize == 2048){
  68078. var geo = new PlaneGeometry(1, 1, 1, 1);
  68079. var cube = new Object3D;
  68080. cube.tiles = [];
  68081. for(var cubeIndex=0; cubeIndex<6; cubeIndex++){
  68082. var face = new Object3D;
  68083. for(var i=0;i<8;i++){
  68084. for(var j=0;j<8;j++){
  68085. var tile = new Mesh(geo, new MeshBasicMaterial({
  68086. //side:THREE.DoubleSide
  68087. transparent:true,
  68088. opacity : 0.4,
  68089. depthTest:false,
  68090. }));
  68091. tile.position.set(i-3.5, j-3.5, -4);
  68092. if(Potree.settings.isTest){
  68093. var colorHue = Math.random();
  68094. tile.material.color = (new Color()).setHSL(colorHue, 0.6, 0.7);
  68095. /* tile.scoreLabel = new TextSprite( {
  68096. backgroundColor: { r: 0, g: 0, b: 0, a: 0 },
  68097. textColor: { r: 0, g: 0, b: 0, a: 1 },
  68098. borderRadius: 15,
  68099. renderOrder: 50, fontsize : 13,
  68100. text: '' ,
  68101. dontFixOrient:true
  68102. })
  68103. tile.scoreLabel.sprite.material.side = 2;
  68104. tile.scoreLabel.rotation.x = Math.PI
  68105. tile.add(tile.scoreLabel) */
  68106. }
  68107. tile.visible = false;
  68108. tile.tileX = i;
  68109. tile.tileY = j;
  68110. tile.cubeFace = cubeIndex;
  68111. //tile.renderOrder = RenderOrder.highTileCube
  68112. cube.tiles.push(tile);
  68113. face.add(tile);
  68114. }
  68115. }
  68116. switch(cubeIndex){
  68117. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  68118. face.rotation.set(0,Math.PI/2,0);
  68119. break;
  68120. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  68121. face.rotation.set(0,-Math.PI/2,0);
  68122. break;
  68123. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  68124. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0,1,0),Math.PI);
  68125. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1,0,0),Math.PI/2);
  68126. face.quaternion.copy(rot1).multiply(rot2);
  68127. //face.rotation.set(Math.PI/2,0,0);
  68128. break;
  68129. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  68130. //face.rotation.set(-Math.PI/2,0,0);
  68131. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0,1,0),Math.PI);
  68132. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1,0,0),-Math.PI/2);
  68133. face.quaternion.copy(rot1).multiply(rot2);
  68134. break;
  68135. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  68136. face.rotation.set(0,Math.PI,0);
  68137. break;
  68138. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  68139. face.rotation.set(0,0,0);
  68140. }
  68141. face.scale.set(1,-1,1);
  68142. face.cubeFace = cubeIndex;
  68143. cube.add(face);
  68144. }
  68145. cube.name = 'highMapCube';
  68146. this.highMapCube = cube;
  68147. viewer.scene.scene.add(cube);
  68148. {
  68149. let s = 0.1;
  68150. cube.scale.set(s,s,s);
  68151. }//注:由于原本的mesh上加了深度贴图,可能距离镜头比这里的近。凡是在cube以内的部分都会挡住cube导致模糊。但是应该不常见吧(另外到天空的边缘也是很近)。姑且depthTest=false
  68152. this.highMapCube.visible = false;
  68153. Potree.Utils.setObjectLayers(this.highMapCube, 'sceneObjects'/* 'skybox' */); //因它的深度是错误的,故不在skybox层渲染,影响edlRT, 而在renderOverlay时渲染覆盖。
  68154. //console.warn('addHighMapCube')
  68155. viewer.addEventListener('update',()=>{
  68156. if (this.highMapCube.visibleTiles) {
  68157. this.updateTiles(); //逐步将visibleTiles加载完
  68158. }
  68159. });
  68160. viewer.addEventListener('camera_changed',(e)=>{
  68161. if(e.viewport == viewer.mainViewport){
  68162. //重新获取visibleTiles
  68163. Common$1.intervalTool.isWaiting(
  68164. 'update4kTiles',
  68165. () => {
  68166. let vectorForward = this.getDirection();
  68167. this.updateTiles(vectorForward);
  68168. },
  68169. 500
  68170. );
  68171. }
  68172. });
  68173. }
  68174. }
  68175. isHighMapLoaded( cubeFace, tileX, tileY){
  68176. var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
  68177. return !!tile.material.map
  68178. }
  68179. updateTiles(direction) {
  68180. if (!this.highMapCube || !this.highMapCube.visible) return
  68181. if (this.highMapCube.tiles.filter(e => e.image).length <= 10) return //加载的太少了
  68182. //performance.mark('updateTiles-start')
  68183. if (direction) {
  68184. let camera = viewer.mainViewport.camera;
  68185. let hfov = cameraLight.getHFOVForCamera(camera, true) / 2;
  68186. let vfov = MathUtils.degToRad(camera.fov) / 2;
  68187. /* let hcos = Math.cos(hfov / 2)
  68188. let vcos = Math.cos(vfov / 2) */
  68189. let list = this.highMapCube.tiles;
  68190. list.forEach(e => {
  68191. //屏幕外的不显示
  68192. let pos = e.getWorldPosition(new Vector3());
  68193. let dir = new Vector3().subVectors(pos, this.highMapCube.position).normalize();
  68194. let hcos_ = dir.clone().setZ(direction.z).normalize().dot(direction); //在direction的斜面上水平角度差
  68195. let hRad = Math.acos(hcos_);
  68196. let vRad = -200;
  68197. if (/* hRad > hfov + 0.08 */ hRad / hfov > 1.5 ) {
  68198. e.score = -100;
  68199. } else {
  68200. vRad = Math.abs(Math.acos(dir.z) - Math.acos(direction.z));
  68201. if (/* vRad > vfov + 0.08 */ vRad / vfov > 1.5 ) {
  68202. e.score = -100;
  68203. } else {
  68204. e.score = -(hRad / hfov + vRad / vfov);
  68205. }
  68206. }
  68207. e.scores = hRad.toFixed(3) + ', ' + vRad.toFixed(3);
  68208. if (e.score == -100) {
  68209. this.resetTile(e);
  68210. }
  68211. });
  68212. this.highMapCube.visibleTiles = list.filter(e => e.score > -100);
  68213. //list.forEach(e=>e.scoreLabel.setText(e.scores))
  68214. }
  68215. let needRecover = this.highMapCube.visibleTiles.filter(e => !e.material.map);
  68216. if (needRecover.length) {
  68217. let maxCount = Common$1.getBestCount( '4kmaxTileRecover', 0, 2, 1.5, 6, false, 2 );
  68218. let count = 0;
  68219. console.log(maxCount);
  68220. needRecover.forEach((e, i) => {
  68221. //只更新若干个,因为太耗时了, 其余的等下帧更新
  68222. if (count >= maxCount) return
  68223. let r = this.recoverTile(e);
  68224. if (r) count++;
  68225. });
  68226. }
  68227. }
  68228. getHighImage(image, cubeFace, tileX, tileY) {
  68229. let tile = this.highMapCube.children[cubeFace].children[tileX * 8 + tileY];
  68230. tile.image = image; //先记录下来
  68231. }
  68232. updateHighMap(image, cubeFace, tileX, tileY){
  68233. //console.warn('updateHighMap')
  68234. var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
  68235. if (image) tile.image = image; //先记录下来
  68236. if(tile.material.map)return
  68237. if (this.highMapCube.visibleTiles && !this.highMapCube.visibleTiles.includes(tile) /* this.highMapCube.texLoadedCount >= this.getMaxTileCount() */) {
  68238. return
  68239. }
  68240. //简易创建贴图
  68241. /* var tex = this.$app.core.get('SceneRenderer').initSizedTexture2D(512, THREE.ClampToEdgeWrapping)
  68242. //var loaded = this.$app.core.get('Player').model.isHighMapLoaded(tile.cubeFace, tile.tileX, tile.tileY)
  68243. this.$app.core.get('SceneRenderer').uploadTexture2D(image, tex, 0, 0, 512, 512) //只替换tex对应的img,不新建
  68244. */
  68245. var tex = new Texture();
  68246. tex.image = image;
  68247. tex.flipY = false;
  68248. tex.wrapS = tex.wrapT = ClampToEdgeWrapping;
  68249. tex.generateMipmaps = false;
  68250. tex.minFilter = LinearFilter;
  68251. tex.needsUpdate = true;
  68252. tile.material.map = tex;
  68253. tile.material.opacity = 1;
  68254. tile.material.transparent = false;
  68255. tile.visible = true;
  68256. tile.material.needsUpdate = true; //发现每次开始放大但还未放大到4k时也会把之前加载过的4k加载
  68257. }
  68258. recoverTile(tile) {
  68259. if (tile.material.map) return
  68260. if (tile.image) {
  68261. this.updateHighMap(tile.image, tile.cubeFace, tile.tileX, tile.tileY);
  68262. return true
  68263. } else {
  68264. //console.log('no image')
  68265. }
  68266. }
  68267. resetTile(tile, kill) {
  68268. if (kill) {
  68269. //完全消灭
  68270. tile.image = null;
  68271. }
  68272. let map = tile.material.map;
  68273. if (map) {
  68274. map.dispose(); //这句执行了以后,h.__webglTexture一直就是undefined
  68275. map.loaded = !1;
  68276. map.version = 0;
  68277. //保底再执行一下这个,类似app.sceneRenderer.deallocateCubeTexture(tile.material.map)
  68278. var h = viewer.renderer.properties.get(map);
  68279. //console.log('__webglTexture',!!h.__webglTexture)
  68280. viewer.renderer.getContext().deleteTexture(h.__webglTexture);
  68281. tile.material.map = null;
  68282. tile.material.needsUpdate = true;
  68283. tile.visible = false;
  68284. //this.highMapCube.texLoadedCount --
  68285. //console.log('resetTile'/* , tile.cubeFace, tile.tileX, tile.tileY */)
  68286. }
  68287. }
  68288. resetHighMap() {
  68289. if (!this.highMapCube) return
  68290. this.highMapCube.children.forEach(e =>
  68291. e.children.forEach(tile => {
  68292. this.resetTile(tile, true);
  68293. })
  68294. );
  68295. //this.highMapCube.texLoadedCount = 0
  68296. this.highMapCube.visibleTiles = null;
  68297. this.hideHighMap();
  68298. //console.log('resetHighMap')
  68299. }
  68300. setHighMap(pano){
  68301. if(!this.highMapCube) return
  68302. this.highMapCube.position.copy(pano.position);
  68303. //可以利用第0个pano查看,其 rotation4dkk是(_x: 0, _y: -1.5707963267948966, _z: 0 )而手动旋转至(_x:1.5707963, _y: -1.57079, _z: 0)时才正确,说明要在4dkk的旋转基础上,绕x轴转90度,(也就是转成navvis坐标系), 然后得到YupToZup的函数写法的
  68304. this.highMapCube.quaternion.copy( math.convertQuaternion.YupToZup( pano.quaternion4dkk ) );
  68305. //乘上数据集整体的旋转:
  68306. let modelRotQua = new Quaternion().setFromRotationMatrix(pano.pointcloud.rotateMatrix);
  68307. this.highMapCube.quaternion.premultiply(modelRotQua);
  68308. }
  68309. showHighMap(){
  68310. if(!this.highMapCube) return
  68311. //console.warn('showHighMap')
  68312. this.highMapCube.visible = true;
  68313. }
  68314. hideHighMap(){
  68315. if(!this.highMapCube) return
  68316. //console.warn('hideHighMap')
  68317. this.highMapCube.visible = false;
  68318. }
  68319. //缩小后继续显示cube呢还是不显示? 不显示的话,就要把cube上的复制到renderTarget上……会不会又崩溃,or没加载的显示???
  68320. addPanoData(data, datasetId ){//加载漫游点
  68321. //data[0].file_id = '00019'
  68322. if(data.data) data = data.data;
  68323. if(data.length == 0)console.error(datasetId + ' 没有漫游点');
  68324. //data = data.sort(function(a,b){return a.id-b.id})
  68325. data.forEach((info)=>{
  68326. //if(Potree.fileServer){
  68327. info.id = this.panos.length; //把info的id的一长串数字改简单点
  68328. //}
  68329. let pano = new Panorama( info, this );
  68330. pano.addEventListener('dispose',(e)=>{
  68331. if(this.closestPano == pano) this.closestPano = null;
  68332. });
  68333. this.panos.push(pano);
  68334. if(Potree.settings.editType == 'pano'){
  68335. Potree.settings.datasetsPanos[datasetId].panos.push(pano);
  68336. }
  68337. });
  68338. }
  68339. loadDone(){
  68340. Potree.Utils.setObjectLayers(this.node, 'sceneObjects');
  68341. //this.updateCube(/* viewer.bound */)
  68342. this.panos.forEach(e=>{
  68343. this.neighbourMap[e.id] = {};
  68344. e.label && Potree.Utils.setObjectLayers(e.label, 'bothMapAndScene');
  68345. e.label2 && Potree.Utils.setObjectLayers(e.label2, 'bothMapAndScene');
  68346. });
  68347. this.tileDownloader.setPanoData(this.panos, [] /* , Potree.settings.number */);
  68348. {
  68349. let minSize = new Vector3(1,1,1);
  68350. this.bound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize);
  68351. viewer.scene.pointclouds.forEach(pointcloud=>pointcloud.getPanosBound());
  68352. }
  68353. if(viewer.scene.pointclouds.some(e=>e.panos.length == 0)){
  68354. //console.warn('存在数据集没有pano');
  68355. viewer.hasNoPanoDataset = true;
  68356. }
  68357. }
  68358. getPano(value, typeName='id'){ //默认找的是id,也可以是sid、uuid
  68359. return this.panos.find(p=>p[typeName] == value)
  68360. }
  68361. };
  68362. //判断当前点是否加载了全景图
  68363. Images360.prototype.checkAndWaitForPanoLoad = function() {
  68364. var isLoadedPanos = {},
  68365. LoadedTimePanos = {},
  68366. loadedCallback = {}, //add
  68367. maxTime = 5e3;
  68368. var withinTime = function() {
  68369. for (var panoId in isLoadedPanos)
  68370. if (isLoadedPanos.hasOwnProperty(panoId) && isLoadedPanos[panoId]) {
  68371. var differTime = performance.now() - LoadedTimePanos[panoId];
  68372. if (differTime < maxTime)
  68373. return !0
  68374. }
  68375. return !1
  68376. };
  68377. return function(pano, basePanoSize, doneFun1, doneFun2, progressCallback, iswait, isclear, p ) {
  68378. loadedCallback[pano.id] = doneFun1;//add 因为有可能之前请求的没加doneFun1, 如果加载好就执行最新的doneFun1
  68379. if (withinTime()){//距离上次请求时间很近
  68380. return !0; //这里感觉应该是!1
  68381. }
  68382. var callback1 = (param1, param2)=>{
  68383. setTimeout(()=>{
  68384. isLoadedPanos[pano.id] = !1;
  68385. loadedCallback[pano.id] && loadedCallback[pano.id](param1, param2);
  68386. },1);
  68387. };
  68388. var callback2 = (param)=>{//没有看到有传doneFun2的
  68389. setTimeout(()=>{
  68390. isLoadedPanos[pano.id] = !1;
  68391. doneFun2 && doneFun2(param);
  68392. },1);
  68393. };
  68394. try {
  68395. null !== iswait && void 0 !== iswait || (iswait = !0);
  68396. isLoadedPanos[pano.id] = this.checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, p );
  68397. //true代表没加载好
  68398. isLoadedPanos[pano.id] && (LoadedTimePanos[pano.id] = performance.now());
  68399. return isLoadedPanos[pano.id];
  68400. } catch (msg) {
  68401. isLoadedPanos[pano.id] = !1;
  68402. LoadedTimePanos[pano.id] = performance.now() - maxTime;
  68403. throw msg;
  68404. }
  68405. }
  68406. }();//加载全景图的流程:请求下载当前点的最低分辨率图(不过有可能已经下载了),并且请求uploadTile渲染当前漫游点,若tile都upload完(先6个)会发送消息,LoadComplete 从而回调成功。
  68407. Images360.prototype.getNeighbours = function(){ //逐渐自动获取neighbours。 200个点差不多在半分钟内算完
  68408. let lastIndex; //标记上次查询到哪,防止重新sortByScore
  68409. return function( interacted){
  68410. if(!this.currentPano || viewer.mainViewport.view.isFlying() || viewer.lastFrameChanged || viewer.inputHandler.drag /* interacted */){ //拖拽时不更新,否则移动端卡
  68411. return lastIndex = 0;
  68412. }
  68413. let nearPanos = this.tileDownloader.tilePrioritizer.nearPanos;
  68414. if(!nearPanos)return;
  68415. //let startTime = Date.now()
  68416. let panos = [this.currentPano, ...nearPanos ];
  68417. this.depthSampler.updateNearPanos(panos);
  68418. let maxWaitDur = browser.isMobile() ? 40 : 60;
  68419. let changeCount = 0, maxChangeTex = browser.isMobile() ? 2 : 4, getCount = 0;
  68420. let changeTexCount = ()=>{
  68421. changeCount ++;
  68422. };
  68423. let median = Potree.timeCollect.depthSamChangeImg.median;
  68424. let ifOverTime = ()=>{
  68425. let is = changeCount >= maxChangeTex || changeCount * median + getCount * 0.01 > maxWaitDur;//不换贴图也要一丢丢计算时间
  68426. /* if(is){
  68427. console.log('OverTime, changeCount', changeCount)
  68428. } */
  68429. return is
  68430. };
  68431. this.depthSampler.addEventListener('changeImg', changeTexCount);
  68432. outer: for(let i=lastIndex,j=panos.length; i<j; i++){
  68433. let pano = panos[i];
  68434. let others = panos.slice(i+1, j);
  68435. lastIndex = i;
  68436. var g = Common$1.sortByScore(others, [ ], [
  68437. Images360.scoreFunctions.distanceSquared(pano.position)
  68438. ]);
  68439. for(let a=0, b=g.length; a<b; a++){
  68440. let item = g[a];
  68441. if(item.item == pano)continue
  68442. if(this.isNeighbour(pano,item.item,{dontCompute:true}) || this.neighbourMap[pano.id][item.item.id]!= void 0 && this.neighbourMap[item.item.id][pano.id]!= void 0)continue //为true或两个方向都算了的
  68443. //console.log('check isNeighbour', pano.id, item.item.id)
  68444. let byCloud = !pano.pointcloud.hasDepthTex;
  68445. let result = this.isNeighbour(pano, item.item, {onlyUseTex: !byCloud, computeDirFirst:true, computeTwoDir:true});//计算
  68446. if(result != void 0){//计算了
  68447. //console.log('提前计算neighbor', pano.id, item.item.id)
  68448. this.dispatchEvent({type:'getNeighbourAuto', panos:[pano,item.item]});
  68449. if(byCloud){ //只计算一次
  68450. //console.log('提前计算neighbor byCloud', result, pano.id, item.item.id)
  68451. break outer;
  68452. }
  68453. getCount ++;
  68454. if(ifOverTime()){
  68455. break outer
  68456. }
  68457. }
  68458. }
  68459. lastIndex = i+1; //这轮结束
  68460. }
  68461. /* if(changeCount){
  68462. console.log( 'changeCount', changeCount)
  68463. } */
  68464. this.depthSampler.removeEventListener('changeImg', changeTexCount);
  68465. /* let costTime = Date.now() - startTime
  68466. costTime > maxWaitDur && console.log( 'costTime:',costTime) */
  68467. }
  68468. }();
  68469. Images360.filters = {
  68470. inPanoDirection : function(pos, dir, i, log) { //pano在mouse的方向上
  68471. return function(pano) {
  68472. var r = pano.floorPosition.clone().sub(pos).normalize();
  68473. var o = pano.position.clone().sub(pos).normalize();
  68474. log && console.log('dire',pano.id, r.dot(dir), o.dot(dir) );
  68475. return r.dot(dir) > i || o.dot(dir) > i
  68476. }
  68477. },
  68478. inFloorDirection: function(pos, dir, min, log) { //pano在mouse的水平方向上
  68479. return function(pano) {
  68480. var vec = new Vector2().subVectors(pano.floorPosition, pos).normalize();
  68481. var dir_ = new Vector2().copy(dir).normalize();
  68482. log && console.log('dire', pano.id, vec.dot(dir_) );
  68483. return vec.dot(dir_) > min
  68484. /* var i = pano.floorPosition.clone().sub(pos).setZ(0).normalize();//改成在xz方向上,否则点击墙面不会移动
  68485. return i.dot(dir.clone().setZ(0)) > min */
  68486. }
  68487. },
  68488. isNotBehindNormal: function(e, t) {
  68489. var i = new Vector3;
  68490. return t = t.clone(),
  68491. function(n) {
  68492. var r = i.copy(n.position).sub(e).normalize();
  68493. return r.dot(t) > 0
  68494. }
  68495. },
  68496. isCloseEnoughTo: function(e, t) {
  68497. return function(i) {//因为marker可能比地面高,所以识别范围要比marker看起来更近一些。(因为投影到地板的位置比marker更近)
  68498. return e.distanceTo(i.floorPosition) < t //许钟文
  68499. }
  68500. },
  68501. not: function(e) {
  68502. return function(t) {
  68503. return t !== e
  68504. }
  68505. } ,
  68506. isEnabled:function() {
  68507. return function(t) {
  68508. return t.enabled
  68509. }
  68510. },
  68511. isVisible:function() {
  68512. return function(t) {
  68513. return t.visible
  68514. }
  68515. }
  68516. };
  68517. Images360.scoreFunctions = {
  68518. direction: function(curPos, dir, ifLog) {
  68519. return function(pano) {
  68520. var pos1 = /* pano.floorPosition */ pano.position; //旧:改为权重放在marker上,这样对有斜坡的更准确,如上楼, 但这样近距离的pano角度就会向下了,以致于走不到
  68521. var n = pos1.clone().sub(curPos).normalize();
  68522. //ifLog && console.log('direction', pano.id, n.dot(dir) * directionFactor )
  68523. return n.dot(dir) * directionFactor
  68524. }
  68525. },
  68526. distance: function(pos1, r=1, ifLog) {
  68527. if(pos1.position)pos1 = pos1.position;
  68528. return function(pano) {//许钟文 改
  68529. var pos2 = pano.position.clone();
  68530. //ifLog && console.log('distance', pano.id, pos1.distance(pos2) * -1 )
  68531. return pos1.distanceTo(pos2) * -1 * r;
  68532. }
  68533. },
  68534. distanceSquared: function(pos1, r=1 ) {
  68535. if(pos1.position)pos1 = pos1.position;
  68536. return function(pano) {//许钟文 改
  68537. var pos2 = pano.position.clone();
  68538. return pos1.distanceToSquared(pos2) * -1 * r;
  68539. }
  68540. },
  68541. angle: function(e, t) {
  68542. return function(i) {
  68543. var n = i.position.clone().sub(e).normalize();
  68544. return n.angleTo(t) * Potree.config.navigation.angleFactor
  68545. }
  68546. },
  68547. };
  68548. Images360.sortFunctions = {//排序函数,涉及到两个item相减
  68549. floorDisSquaredToPoint: function(e) {
  68550. return function(t, i) {
  68551. return t.floorPosition.distanceToSquared(e) - i.floorPosition.distanceToSquared(e)
  68552. }
  68553. },
  68554. disSquaredToPoint: function(e) {
  68555. return function(t, i) {
  68556. return t.position.distanceToSquared(e) - i.position.distanceToSquared(e)
  68557. }
  68558. },
  68559. };
  68560. Images360.prototype.updateCube = (function(){//增加细分的版本,且垂直方向上取中位数 侧边多条
  68561. const minDis = 0.2; //pano和墙距离不能小于相机的near
  68562. const height = 1; //准确计算的话要分别计算两个pano的地面、天花板之间的俯仰角,和pano之间的还不一样。这里统一假设一个比较小的高度,因高度越大 maxSinAlpha 越大
  68563. let minTanBeta = minDis / height; /* (pano0.position.z - pano0.floorPosition.z) */
  68564. let minBeta = Math.atan(minTanBeta);
  68565. const maxSinAlpha = Math.cos(minBeta); // 注:beta = Math/2 - alpha
  68566. const skyHeight = 50;
  68567. return function(pano0, pano1){
  68568. if(Potree.settings.displayMode != 'showPanos' || pano0 == pano1
  68569. || this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)
  68570. ) return
  68571. this.cubePanos = [pano0, pano1];
  68572. viewer.addTimeMark('updateCube','start');
  68573. //console.log('updateCube',pano0.id, pano1&&pano1.id)
  68574. let useBound = (bound, size)=>{
  68575. size = size || bound.getSize(new Vector3);
  68576. let center = bound.getCenter(new Vector3);
  68577. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  68578. this.cube.geometry = new BoxBufferGeometry(1,1,1,1);
  68579. this.cube.scale.copy(size);
  68580. this.cube.position.copy(center);
  68581. if(Potree.settings.testCube){
  68582. this.cubeTest.geometry = this.cube.geometry;
  68583. this.cubeTest.scale.copy(size);
  68584. this.cubeTest.position.copy(center);
  68585. }
  68586. return 'useBound'
  68587. };
  68588. let getPanoBound = (pano, dis)=>{//因漫游点可能在点云外部,如室外平地,所以需要union进漫游点
  68589. let panoBound = new Box3;
  68590. panoBound.expandByPoint(pano.position);
  68591. let margin = dis ? Math.max(dis * 0.1, 10) : 10;
  68592. panoBound.expandByVector(new Vector3(margin,margin,margin)); //give pano a margin 。 随着bound扩大,margin要相应扩大,否则当距离很远时看起来就像没有
  68593. return pano.pointcloud.bound.clone().union(panoBound)
  68594. };
  68595. this.cube.geometry.dispose();
  68596. if(pano1){//过渡
  68597. let dontAddSides;
  68598. let dis = pano0.position.distanceTo(pano1.position);
  68599. if(dis == 0)return
  68600. let sinAlpha = Math.abs(pano0.position.z - pano1.position.z) / dis; //俯仰角的sin,随角度增大而增大 0-1
  68601. let score = (1+sinAlpha*20) * dis; //score越大创建的mesh越不适合
  68602. let isNeighbour = this.isNeighbour(pano0, pano1);
  68603. //console.log(pano0.id, pano1.id, maxSinAlpha.toFixed(2), sinAlpha.toFixed(2), score.toFixed(2), isNeighbour)
  68604. if(sinAlpha>maxSinAlpha || !pano0.pointcloud.hasDepthTex || !pano1.pointcloud.hasDepthTex || (isNeighbour ? score > 100 : score > 50 ) ){
  68605. let bound = getPanoBound(pano0, dis).union(getPanoBound(pano1, dis));
  68606. let size = bound.getSize(new Vector3);
  68607. let max = Math.max(size.x, size.y, size.z);
  68608. size.set(max,max,max); //距离太远的数据集,过渡会畸变。所以扩大skybox,且为立方体
  68609. return useBound(bound, size)
  68610. }else if( isNeighbour ? score > 70 : score > 15 ){
  68611. dontAddSides = true; //pano间有阻挡时得到的side点可能使通道变窄,所以去掉。
  68612. }
  68613. //俯仰角增大时可能不在同一楼层,算出来的mesh不太好,所以更倾向直接使用cube,或去除side。
  68614. let half = browser.isMobile() ? 4 : 8; //自行输入 (点云计算的慢,还不准)
  68615. let count1 = 2*half;//偶数个 每个pano向 外dir 个数
  68616. //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
  68617. let getDir = (angle_, vec)=>{ //旋转获得水平向量
  68618. let rotMat = new Matrix4().makeRotationZ(angle_);
  68619. return vec.clone().applyMatrix4(rotMat)
  68620. };
  68621. let getFar = (dir, pano, origin, height)=>{//获取在这个方向上和墙体intersect的距离
  68622. //在垂直方向上分出多个方向,取一个最可能的接近真实的距离
  68623. let maxH = 40, minH = 2, minR = 0.5, maxR = 2;
  68624. height = height == void 0 ? (Math.min(skyHeight,pano.ceilZ) - pano.floorPosition.z) : height;
  68625. //let r = height (maxH - minH)* 0.14 // 高度越小,角度越小
  68626. //let r = minR + ( maxR - minR) * THREE.Math.clamp((height - minH) / (maxH - minH),0,1) //THREE.Math.smoothstep(currentDis, op.nearBound, op.farBound);
  68627. let r = math.linearClamp(height, minH,maxH, minR, maxR);
  68628. let getZ = (deg)=>{
  68629. deg *= r;
  68630. deg = MathUtils.clamp(deg, 1, 80);
  68631. return Math.tan(MathUtils.degToRad(deg))
  68632. };
  68633. let dirs_; //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 更多取接近0度的,否则围墙矮一点就会取到远处。
  68634. dirs_ = [15, 8, 3, -1, -5];
  68635. dirs_ = dirs_.map(deg=> dir.clone().setZ(getZ(deg)).normalize() );
  68636. let max = 50;
  68637. let count2 = dirs_.length;
  68638. let disArr = dirs_.map((dir_, i) =>{
  68639. let intersect = this.getIntersect(pano, dir_, origin);
  68640. let projectLen = intersect && intersect.distance ? dir_.dot(dir)*intersect.distance : max; //得到project在dir的长度
  68641. return projectLen //得水平距离
  68642. });
  68643. //console.log(pano ? pano.id : 'side','disArr', disArr.slice(0))
  68644. disArr.sort((a,b)=>{return b-a}); //从大到小
  68645. //console.log(pano ? pano.id : 'side','disArr', disArr)
  68646. let dis = disArr[Math.floor(count2/2-0.5)]; //对半、取前(中位数)
  68647. return dis
  68648. };
  68649. let sideCount = [0,0];
  68650. let addPos = (pano, vec )=>{//添加这个pano这一侧向外半圆的顶点
  68651. //添加pano位置对应的最高点最低点:
  68652. let minZ, maxZ;
  68653. minZ = pano.floorPosition.z;
  68654. maxZ = pano.getCeilHeight();
  68655. if(maxZ == Infinity) maxZ = skyHeight; //maxZ = Math.max(skyHeight, maxZ)
  68656. [maxZ, minZ ].forEach(z=>{
  68657. posArr.push(pano.position.clone().setZ(z));
  68658. });
  68659. //在画面上线条从左往右数
  68660. const angle = Math.PI/(count1-1);
  68661. const dirs = []; //平分这半边180度
  68662. for(let i=0;i<count1;i++){
  68663. dirs.push(getDir(Math.PI/2-i*angle, vec));//正的在左边
  68664. }
  68665. let dirs2 = dirs.map((dir)=>{
  68666. return {
  68667. dir,
  68668. dis: getFar(dir, pano)
  68669. }
  68670. });
  68671. //剔除那些突然间离相机很近的dir。有可能是拍摄的人、或者杆子、树
  68672. /* dirs2.forEach((e,i)=>{
  68673. console.log(i, e.dis)
  68674. let smallThanBefore = ()=>{
  68675. return dirs2[i-1].dis / e.dis > maxRatio
  68676. }
  68677. let smallThanAfter = ()=>{
  68678. return dirs2[i+1].dis / e.dis > maxRatio
  68679. }
  68680. if(i>0 && i<count1-1 && smallThanBefore() && smallThanAfter()){//比左右两边都小很多
  68681. e.disB = (dirs2[i-1].dis + dirs2[i+1].dis) / 2 //平均数
  68682. console.log('两者之间',i,e.disB)
  68683. }else if(i==count1-1 && smallThanBefore() ) {//比前者小很多
  68684. e.disB = dirs2[i-1].dis * 0.8
  68685. console.log('smallThanBefore', i, e.disB)
  68686. }else if(i==0 && smallThanAfter() ){//比后者小很多
  68687. e.disB = dirs2[i+1].dis * 0.8
  68688. console.log('smallThanAftere', i, e.disB)
  68689. }
  68690. }) */
  68691. const maxRatio1 = 3 , maxRatio2 = 8; //超过maxRatio1就要加入判断,而最终结果的设限其实是maxRatio2
  68692. const minWidth = 0.5;
  68693. let computeWidth = (start,end)=>{
  68694. start+=1; //不包含start和end
  68695. let count = end - start ;
  68696. let dis = 0;
  68697. for(let m=start;m<end;m++){//得平均数
  68698. dis += dirs2[m].dis;
  68699. }
  68700. dis /= count;
  68701. let angle = Math.PI / (count1-1) * count / 2;
  68702. let width = dis * Math.tan(angle); //得到block的半宽度
  68703. return width
  68704. };
  68705. let changeDis = (start,end )=>{ //不包含start
  68706. start+=1; //不包含start和end
  68707. for(let m=start;m<end;m++){
  68708. dirs2[m].disB = dirs2[end].dis * 0.8;
  68709. //console.log('changeDis', m, dirs2[m].disB)
  68710. }
  68711. };
  68712. let start = -1;
  68713. for(let i=0;i<count1;i++){//遍历时将左边dis比之小很多且宽度较小的改大
  68714. //console.log(i, dirs2[i].dis)
  68715. let j = i-1;
  68716. let ratios = 0;
  68717. while(j>start && dirs2[i].dis / dirs2[j].dis > maxRatio1){
  68718. ratios += dirs2[i].dis / dirs2[j].dis;
  68719. j--;
  68720. }
  68721. let count = i-j-1;
  68722. ratios /= count;
  68723. if(count > 0 && computeWidth(j,i)< minWidth * ratios / maxRatio2 ){ //怎么感觉好像改成了视觉宽度小于某个值即可,那直接用count好了?
  68724. changeDis(j,i);
  68725. start = i; //在此之前的修改过,之后不用再判断
  68726. }
  68727. /* if(count > 0 && (count == 1 || computeWidth(j,i)<minWidth)){//若只有一个不用判断宽度直接修改
  68728. changeDis(j,i)
  68729. start = i //在此之前的修改过,之后不用再判断
  68730. } */
  68731. }
  68732. dirs2.forEach((e, index)=>{
  68733. let dir = e.dir.clone().multiplyScalar(e.disB || e.dis);
  68734. [maxZ,minZ].forEach(z=>{
  68735. posArr.push(pano.position.clone().setZ(z).add(dir)); //获取到外墙点
  68736. });
  68737. });
  68738. };
  68739. let addSide = ()=>{//两个漫游点间两边各加一些侧线
  68740. //中点处的
  68741. let top0 = pano0.ceilZ == Infinity ? skyHeight : pano0.ceilZ;
  68742. let top1 = pano1.ceilZ == Infinity ? skyHeight : pano1.ceilZ;
  68743. let midMaxZ = (top0 + top1)/2;
  68744. let midMinZ = (pano0.floorPosition.z+pano1.floorPosition.z)/2;
  68745. let mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5);
  68746. if(!dontAddSides){
  68747. if( pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex){
  68748. let panos = [pano0,pano1];
  68749. let vecs = [vec.clone().negate(), vec];
  68750. let axis = [[-1,1],[1,-1]];
  68751. let dis2d = new Vector2().subVectors(pano0.position, pano1.position).length();//水平上的距离
  68752. let maxDis = 50, minDis = 0.5, minR = 0.2, maxR = 1.2;
  68753. //let r = maxR - ( maxR - minR) * THREE.Math.clamp((dis2d - minDis) / (maxDis - minDis),0,1) //dis2d越大,角度要越小 //THREE.Math.smoothstep(currentDis, op.nearBound, op.farBound);
  68754. let r = math.linearClamp(dis2d, minDis,maxDis, maxR, minR);
  68755. //console.log('dis2d',dis2d,'r',r)
  68756. let angles = ((browser.isMobile()/* || dis2d<4 */)? [60] : [50,70] /* [35,65] */).map(deg=>{ //正的在左边 尽量能够平分中间这段墙体。 (角度为从中心向外)
  68757. let angle = MathUtils.clamp(deg * r, 5, 80);
  68758. //console.log('angle',angle)
  68759. return MathUtils.degToRad(angle)
  68760. });
  68761. axis.forEach((axis_, index0)=>{
  68762. let disToSides = [];
  68763. let accordingPano = index0 == 0 ? pano0 : pano1; //根据离该点在vec方向上的距离顺序来存顶点
  68764. panos.forEach((pano,index)=>{
  68765. let dirs = angles.map(angle=>getDir(axis_[index]*angle, vecs[index]));//一侧的若干角度
  68766. dirs.forEach((dir_,i)=>{
  68767. let dis1 = getFar(dir_, pano);
  68768. let disToPano2d = dis1 * Math.cos(angles[i]);
  68769. if(disToPano2d<dis2d){//超过的话都到另一半pano的半圆了,不计入。(角度越小越容易超过)
  68770. let disToSide = dis1 * Math.sin(angles[i]);
  68771. if(pano != accordingPano){
  68772. disToPano2d = dis2d - disToPano2d; //反一下
  68773. }
  68774. dir_.multiplyScalar( dis1 );
  68775. disToSides.push({disToSide,disToPano2d, pano, dir_});
  68776. }else {
  68777. //console.log('超过',index0,index,i)
  68778. }
  68779. });
  68780. });
  68781. if(disToSides.length){
  68782. //disToSides.sort((a,b)=>{return b-a});//从大到小
  68783. //由距离accordingPano的近到远:
  68784. disToSides.sort((a,b)=>{return a.disToPano2d-b.disToPano2d});
  68785. //console.log('disToSides', index0, disToSides)
  68786. if(disToSides.length == 1 && disToSides[0].disToSide < 0.5){
  68787. disToSides = []; //如果太近直接去除
  68788. }
  68789. disToSides.forEach(e=>{//求z
  68790. let ratio = e.disToPano2d / dis2d;
  68791. let r = accordingPano == pano0 ? (1-ratio) : ratio;
  68792. let sideMaxZ_ = top0 * r + top1 * (1-r);
  68793. let sideMinZ_ = pano0.floorPosition.z * r + pano1.floorPosition.z * (1-r);
  68794. [sideMaxZ_,sideMinZ_].forEach(z=>{
  68795. posArr.push(e.pano.position.clone().setZ(z).add(e.dir_)); //是直接使用最长dis的那个intersect点好还是mid
  68796. });
  68797. });
  68798. }
  68799. sideCount[index0] = disToSides.length; //记录侧边个数
  68800. });
  68801. }else {
  68802. //这段针对点云时,仅测试才会执行到
  68803. sideCount = [1,1];
  68804. let sideDirs = [getDir(Math.PI/2, vec), getDir(-Math.PI/2, vec)];
  68805. sideDirs.forEach((dir_ ,index)=>{
  68806. let dis = getFar(dir_, null, mid, midMaxZ-midMinZ); //直接从中点求两侧的距离
  68807. dir_.multiplyScalar( /* Math.max( */dis/* , sideDis[index]) */ );
  68808. [midMaxZ,midMinZ].forEach(z=>{
  68809. posArr.push(mid.clone().setZ(z).add(dir_));
  68810. });
  68811. });
  68812. }
  68813. }
  68814. //中心:
  68815. [midMaxZ,midMinZ].forEach(z=>{
  68816. posArr.push(mid.clone().setZ(z));
  68817. });
  68818. };
  68819. //positions存放顺序:pano的每边的 zMax和zMin 、count1个dir的点 ;侧边的点 ;连接处顶底的中点
  68820. let addFaces = ()=>{
  68821. let getPI = function(index, posType, panoIndex){//获取顶点序号
  68822. return 2 + (count1*2 + 2 ) * panoIndex + index*2 + (posType == 'top' ? 0 : 1)
  68823. };
  68824. let getSidePI = function(index, posType, panoIndex){//获取侧边顶点序号
  68825. if(panoIndex == 1) index += sideCount[0];
  68826. return getPI(index, posType, 2)-2
  68827. };
  68828. let getPanoPI = function(posType, panoIndex){//获取pano处对应的点序号
  68829. return getPI(-1, posType, panoIndex)
  68830. };
  68831. let topCenter = posArr.length-2; //最后添加的两个中心点
  68832. let btmCenter = posArr.length-1;
  68833. for(let i=0;i<2;i++){
  68834. for(let index=1; index<count1; index++){
  68835. //pano外侧半圆围墙
  68836. faceArr.push([getPI(index,'top',i), getPI(index-1,'btm',i), getPI(index-1,'top',i)],//加入一块四方面
  68837. [getPI(index,'top',i), getPI(index,'btm',i), getPI(index-1,'btm',i)]);
  68838. faceArr.push([getPI(index,'top',i), getPI(index-1,'top',i), getPanoPI('top',i)]);//天花板扇形
  68839. faceArr.push([getPI(index,'btm',i), getPI(index-1,'btm',i), getPanoPI('btm',i)]);//地板扇形
  68840. }
  68841. let j = (i + 1) % 2; //另一个pano
  68842. //侧边
  68843. for(let u=0; u<=sideCount[i]; u++){
  68844. //侧边每个四方的左上右上左下右下四个点
  68845. let pLT = u == 0 ? getPI(0,'top',i) : getSidePI(u-1, 'top',i);
  68846. let pRT = u == sideCount[i] ? getPI(count1-1,'top',j) : getSidePI(u, 'top',i);
  68847. let pLB = u == 0 ? getPI(0,'btm',i) : getSidePI(u-1, 'btm',i);
  68848. let pRB = u == sideCount[i] ? getPI(count1-1,'btm',j) : getSidePI(u, 'btm',i);
  68849. faceArr.push([pLT,pLB,pRB],[pLT,pRB,pRT]);//外侧四方面
  68850. faceArr.push([pLT,topCenter,pRT] ,[pLB,btmCenter,pRB] );//顶部和底部到整体中心的扇形(由于点的顺序是根据和两个pano的距离,因此到中心的夹角并没按顺序排列,所以可能会重叠)
  68851. if(i==0){//只需要算一次
  68852. //顶部和底部中心与两个pano边构成的三角形
  68853. if(u == 0){
  68854. faceArr.push([pLT,getPI(count1-1,'top',i),topCenter],
  68855. [pLB,getPI(count1-1,'btm',i),btmCenter],
  68856. );
  68857. }
  68858. //不能用else 因为当length==0时u==0也==sideCount[i],此时就是要两个面
  68859. if(u == sideCount[i]){
  68860. faceArr.push([pRT,getPI(0,'top',j),topCenter],
  68861. [pRB,getPI(0,'btm',j),btmCenter],
  68862. );
  68863. }
  68864. }
  68865. }
  68866. }
  68867. };
  68868. let posArr = [];
  68869. let faceArr = [];
  68870. //两点连线的水平向量
  68871. let vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize();
  68872. /* let sideDis0 = */addPos(pano0, vec);
  68873. /* let sideDis1 = */addPos(pano1, vec.clone().negate());
  68874. addSide();
  68875. addFaces();
  68876. //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr)
  68877. let geo = MeshDraw.createGeometry(posArr, faceArr);
  68878. this.cube.geometry = geo;
  68879. this.cube.scale.set(1,1,1);
  68880. this.cube.position.set(0,0,0);
  68881. if(Potree.settings.testCube){
  68882. this.cubeTest.geometry = geo;
  68883. this.cubeTest.scale.set(1,1,1);
  68884. this.cubeTest.position.set(0,0,0);
  68885. }
  68886. }else {
  68887. useBound(getPanoBound(pano0));
  68888. }
  68889. viewer.addTimeMark('updateCube','end');
  68890. return true
  68891. /*
  68892. 关于卡顿:
  68893. 即使使用cube,若scale设置为只容纳两个pano,也会卡顿。但也是有的卡有的不卡。
  68894. 若按照原先的复杂geo,一般在平直的街道上行走流畅,经过拐弯或者复杂区域较卡。减小geo复杂度没有什么作用。
  68895. 注: 修改skybox,若不准的话,会遮住其他mesh,比如marker。尤其在没有深度贴图时。
  68896. 耗时: chrome: 20+ ,但是firefox:500+ 咋回事 ? iphonex safari: 40+
  68897. */
  68898. }
  68899. })();
  68900. /**
  68901. * @author alteredq / http://alteredqualia.com/
  68902. *
  68903. * Full-screen textured quad shader
  68904. */
  68905. let CopyShader = {
  68906. uniforms: {
  68907. "tDiffuse": { value: null },
  68908. "opacity": { value: 1.0 }
  68909. },
  68910. vertexShader: [
  68911. "varying vec2 vUv;",
  68912. "void main() {",
  68913. "vUv = uv;",
  68914. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  68915. "}"
  68916. ].join( "\n" ),
  68917. fragmentShader: [
  68918. "uniform float opacity;",
  68919. "uniform sampler2D tDiffuse;",
  68920. "varying vec2 vUv;",
  68921. "void main() {",
  68922. "vec4 texel = texture2D( tDiffuse, vUv );", //如果开启premultipliedAlpha用这个,否则用注释的
  68923. "gl_FragColor = opacity * texel;",
  68924. //"gl_FragColor = texture2D( tDiffuse, vUv );",
  68925. //"gl_FragColor.a *= opacity;",
  68926. "}"
  68927. ].join( "\n" )
  68928. };
  68929. /**
  68930. * @author alteredq / http://alteredqualia.com/
  68931. */
  68932. let Pass = function () {
  68933. // if set to true, the pass is processed by the composer
  68934. this.enabled = true;
  68935. // if set to true, the pass indicates to swap read and write buffer after rendering
  68936. this.needsSwap = true;
  68937. // if set to true, the pass clears its buffer before rendering
  68938. this.clear = false;
  68939. // if set to true, the result of the pass is rendered to screen
  68940. this.renderToScreen = false;
  68941. };
  68942. Object.assign( Pass.prototype, {
  68943. setSize: function ( width, height ) {},
  68944. render: function ( renderer, writeBuffer, readBuffer, delta, maskActive ) {
  68945. console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
  68946. }
  68947. } );
  68948. let ShaderPass = function ( shader, textureID ) {
  68949. Pass.call( this );
  68950. this.textureID = ( textureID !== undefined ) ? textureID : "tDiffuse";
  68951. if ( shader instanceof ShaderMaterial ) {
  68952. this.uniforms = shader.uniforms;
  68953. this.material = shader;
  68954. } else if ( shader ) {
  68955. this.uniforms = UniformsUtils.clone( shader.uniforms );
  68956. this.material = new ShaderMaterial( {
  68957. defines: Object.assign( {}, shader.defines ),
  68958. uniforms: this.uniforms,
  68959. vertexShader: shader.vertexShader,
  68960. fragmentShader: shader.fragmentShader,
  68961. transparent:true,//add
  68962. } );
  68963. }
  68964. this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  68965. this.scene = new Scene();
  68966. this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), null );
  68967. this.quad.frustumCulled = false; // Avoid getting clipped
  68968. this.scene.add( this.quad );
  68969. };
  68970. ShaderPass.prototype = Object.assign( Object.create( Pass.prototype ), {
  68971. constructor: ShaderPass,
  68972. render: function(scene,camera, viewports, renderer, writeBuffer, readBuffer, delta, maskActive ) {
  68973. let oldTarget = renderer.getRenderTarget();
  68974. /* if(this.readTarget){ //add
  68975. readBuffer = oldTarget
  68976. } */
  68977. if ( this.uniforms[ this.textureID ] ) {
  68978. this.uniforms[ this.textureID ].value = readBuffer.texture;
  68979. }
  68980. this.quad.material = this.material;
  68981. if ( this.renderToScreen ) {
  68982. renderer.render( this.scene, this.camera );
  68983. } else {
  68984. renderer.setRenderTarget(writeBuffer);
  68985. if(this.clear) renderer.clear();
  68986. renderer.render( this.scene, this.camera );
  68987. renderer.setRenderTarget(oldTarget);
  68988. }
  68989. }
  68990. } );
  68991. /* const mapHeight = -1000;//要比点云低。最低
  68992. const cameraHeight = 1000; //最高 */
  68993. const panosHeight = config$1.map.mapHeight + 100; //要比点云低 (marker)
  68994. const cursorHeight = 0;//比地图高就行
  68995. const routeLayerHeight = config$1.map.mapHeight + 105;
  68996. const texLoader$7 = new TextureLoader();
  68997. const planeGeo$2 = new PlaneBufferGeometry(1,1);
  68998. const markerSize = 1;
  68999. var initCameraFeildWidth = 50;
  69000. var panoMarkerMats;
  69001. class MapViewer extends ViewerBase{
  69002. constructor(dom){
  69003. super(dom, {
  69004. clearColor: Potree.config.mapBG,
  69005. name: 'mapViewer'
  69006. });
  69007. this.visible = true;
  69008. this.initScene();
  69009. this.needRender_ = false;
  69010. this.mapLayer = new MapLayer(this, this.viewports[0]);
  69011. this.scene.add(this.mapLayer.sceneGroup);
  69012. this.mapLayer.sceneGroup.position.setZ(Potree.config.map.mapHeight);
  69013. this.mapRatio = 0.5;
  69014. this.splitDir = 'leftRight';
  69015. //因context的preserveDrawingBuffer为false之后,canvas渲染多个viewport时会自动clear,所以若不渲染就会是空的。所以没有变化时就直接拷贝buffer好了。
  69016. this.copyPass = new ShaderPass( CopyShader );
  69017. this.copyBuffer = new WebGLRenderTarget( 100, 100 , {
  69018. minFilter: LinearFilter,
  69019. magFilter: LinearFilter,
  69020. format: RGBAFormat,
  69021. stencilBuffer: false,
  69022. });
  69023. viewer.addEventListener("camera_changed", (e)=>{
  69024. let needUpdateCursor;
  69025. if(e.viewport == viewer.mainViewport){
  69026. needUpdateCursor = true;
  69027. }else if(e.viewport == this.viewports[0]){//attachedToViewer
  69028. needUpdateCursor = true;
  69029. this.mapChanged = true;
  69030. this.updateWhenAtViewer();
  69031. e.changeInfo.projectionChanged && this.setViewLimit();
  69032. }
  69033. needUpdateCursor && this.updateCursor();
  69034. });
  69035. this.addEventListener("camera_changed", (e)=>{
  69036. e.changeInfo.projectionChanged && this.setViewLimit();
  69037. });
  69038. //viewer.addEventListener("global_mousemove", this.updateWhenAtViewer.bind(this)) //鼠标移动时reticule也动,所以直接就needRender
  69039. /* viewer.reticule.addEventListener('update',(e)=>{
  69040. if(this.attachedToViewer)this.needRender = true
  69041. }) */
  69042. viewer.scene.addEventListener("360_images_added", this.addPanos.bind(this));
  69043. viewer.addEventListener("loadPointCloudDone", this.initProjection.bind(this));
  69044. this.addEventListener('global_click',(e)=>{
  69045. if(!e.isTouch && e.button != MOUSE.LEFT)return
  69046. this.updateClosestPano(e.intersect);
  69047. });
  69048. this.addEventListener('add',(e)=>{//添加其他mesh
  69049. this.scene.add(e.object);
  69050. if(e.name == 'route'){
  69051. e.object.position.z = routeLayerHeight;
  69052. }
  69053. Potree.Utils.setObjectLayers(e.object, 'mapObjects' );
  69054. });
  69055. viewer.addEventListener('allLoaded',()=>{
  69056. this.setViewLimit('standard');
  69057. });
  69058. if(!Potree.settings.isOfficial){
  69059. let domRoot = viewer.renderer.domElement.parentElement;
  69060. let elAttach = $("<input type='button' value='map绑定'></input>");
  69061. elAttach.css({
  69062. position : "absolute",
  69063. right : '80%',
  69064. bottom: '20px',
  69065. zIndex: "10000",
  69066. fontSize:'1em', color:"black",
  69067. background:'rgba(255,255,255,0.8)',
  69068. });
  69069. let state = false;
  69070. elAttach.on("click", () => {
  69071. state = !state;
  69072. this.attachToMainViewer(state, 'measure');
  69073. elAttach.val(state ? 'map分离':'map绑定');
  69074. });
  69075. domRoot.appendChild(elAttach[0]);
  69076. }
  69077. }
  69078. get needRender(){
  69079. return this.needRender_
  69080. }
  69081. set needRender(n){
  69082. this.needRender_ = n;
  69083. n && (this.viewports[0].needRender = true); //使attachedToViewer时在renderDefault中可渲染
  69084. }
  69085. get mapChanged(){
  69086. return this.mapChanged_
  69087. }
  69088. set mapChanged(c){//镜头移动、地图内容改变都会为true
  69089. this.mapChanged_ = c;
  69090. c && (this.needRender = true);
  69091. }
  69092. waitLoadDone(callback){//确保加载完后执行
  69093. let timer; //等待一段时间看有没有新加载的tile,如果超过这个时间没有就不等了,算加载结束
  69094. let pauseCountDown = ()=>{//重新等待加载结束,中断倒计时
  69095. clearTimeout(timer);
  69096. //console.log('pauseCountDown')
  69097. };
  69098. let freshCountDown = ()=>{//刷新倒计时
  69099. //console.log('freshCountDown')
  69100. clearTimeout(timer);
  69101. timer = setTimeout(()=>{
  69102. this.mapLayer.removeEventListener('loadDone', freshCountDown);
  69103. this.mapLayer.removeEventListener('startLoad', pauseCountDown);
  69104. callback();
  69105. }, document.hidden ? 5000 : 500);
  69106. };
  69107. this.mapLayer.addEventListener('loadDone', freshCountDown);
  69108. this.mapLayer.addEventListener('startLoad', pauseCountDown);
  69109. if(this.mapLayer.loadingInProgress == 0){
  69110. freshCountDown();
  69111. }
  69112. }
  69113. addListener(images360){
  69114. images360.addEventListener('flyToPano',e=>{
  69115. let toPano = e.toPano;
  69116. if(toPano.dontMoveMap) return
  69117. /* transitions.start(lerp.vector(this.view.position, toPano.pano.position.clone().setZ(cameraHeight),
  69118. (pos, progress)=>{
  69119. }), toPano.duration, null, 0, easing[toPano.easeName] ); */
  69120. let boundSize;// = new THREE.Vector2(10,10)
  69121. this.moveTo(toPano.pano.position.clone().setZ(Potree.config.map.cameraHeight), boundSize, toPano.duration, null, toPano.easeName);
  69122. });
  69123. }
  69124. initProjection(){
  69125. this.started = true;
  69126. this.mapLayer.initProjection();
  69127. }
  69128. initScene(){
  69129. let w = initCameraFeildWidth;
  69130. let width = this.renderArea.clientWidth;
  69131. let height = this.renderArea.clientHeight;
  69132. //let aspect = width / height
  69133. 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);
  69134. this.camera.zoom = width / w; //zoom越大视野越小
  69135. //this.camera.position.set(0,0,10);
  69136. this.camera.up.set(0,0,1);
  69137. //this.camera.lookAt(new THREE.Vector3())
  69138. //this.camera.updateMatrixWorld()
  69139. this.view = new ExtendView();
  69140. this.view.position.set(0,0,Potree.config.map.cameraHeight);
  69141. this.view.lookAt(0,0,0);
  69142. let viewport = new Viewport( this.view, this.camera, {
  69143. left:0, bottom:0, width:1, height: 1, name:'mapViewport'
  69144. });
  69145. viewport.axis = ["x","y"];
  69146. viewport.axisSign = [1,1];
  69147. viewport.noPointcloud = true; //不要渲染点云
  69148. viewport.render = this.render.bind(this);//标志给mainView渲染
  69149. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  69150. viewport.addEventListener('resize',()=>{
  69151. this.copyBuffer.setSize(viewport.resolution2.x, viewport.resolution2.y);
  69152. });
  69153. this.viewports = [viewport];
  69154. this.controls = new FirstPersonControls(this, this.viewports[0]);
  69155. this.controls.setEnable(true);
  69156. this.scene = new Scene();
  69157. this.inputHandler = new InputHandler(this, this.scene);
  69158. this.inputHandler.name = 'mapInputHandler';
  69159. //this.inputHandler.addInputListener(this.controls);
  69160. this.inputHandler.registerInteractiveScene(this.scene);//interactiveScenes
  69161. this.viewports[0].interactiveScenes = this.inputHandler.interactiveScenes;//供viewer的inputHandler使用
  69162. var cursor = new Mesh(planeGeo$2, new MeshBasicMaterial({
  69163. transparent:true,
  69164. opacity:0.9,
  69165. depthTest : false, //防止透明冲突
  69166. map: texLoader$7.load(Potree.resourcePath+'/textures/pic_location128.png' )
  69167. }));
  69168. cursor.position.set(0,0,cursorHeight);
  69169. this.cursor = cursor;
  69170. this.scene.add(cursor);
  69171. Potree.Utils.setObjectLayers(this.scene, 'mapObjects' );
  69172. }
  69173. setViewLimit(state){//设置边界,当编辑空间模型等时要解禁
  69174. if(!state)state = this.limitBoundState;
  69175. if(!state)return
  69176. this.limitBoundState = state;
  69177. let setting = Potree.config.OrthoCameraLimit[state];
  69178. if(setting){
  69179. this.camera.zoomLimit = $.extend({},setting.zoom);
  69180. let lonlatCenter = viewer.transform.lonlatToLocal.inverse([0,0]);
  69181. let minY = viewer.transform.lonlatToLocal.forward([lonlatCenter[0], -90+setting.latPad])[1]; //屏幕边界的bound
  69182. let maxY = viewer.transform.lonlatToLocal.forward([lonlatCenter[0], 90-setting.latPad])[1];
  69183. /*this.view.limitBound = new THREE.Box3(
  69184. new THREE.Vector3(setting.xBound[0], minY, Potree.config.map.cameraHeight),
  69185. new THREE.Vector3(setting.xBound[1], maxY, 1 / 0)
  69186. ) */
  69187. let halfHeight = this.viewports[0].resolution.y / 2 / this.camera.zoom;//屏幕所占高度的一半
  69188. let halfWidth = this.viewports[0].resolution.x / 2 / this.camera.zoom;
  69189. this.view.limitBound = new Box3(
  69190. new Vector3(setting.xBound[0]+halfWidth, minY+halfHeight, Potree.config.map.cameraHeight),
  69191. new Vector3(setting.xBound[1]-halfWidth, maxY-halfHeight, 1 / 0)
  69192. );
  69193. }else {
  69194. this.view.limitBound = null;
  69195. this.camera.zoomLimit = null;
  69196. }
  69197. }
  69198. updateCursor(){
  69199. //console.log('pos', viewer.mainViewport.camera.position.toArray() )
  69200. var scale = math.getScaleForConstantSize( {//规定下最小最大像素
  69201. minSize : 80, maxSize : 200, nearBound : initCameraFeildWidth*0.1 , farBound : initCameraFeildWidth*2,
  69202. camera:this.camera , position: this.cursor.getWorldPosition(new Vector3()),
  69203. resolution: this.viewports[0].resolution//2
  69204. });
  69205. this.cursor.scale.set(scale, scale, scale);//当地图缩放时
  69206. this.cursor.position.copy(viewer.mainViewport.camera.position).setZ(cursorHeight);//当场景镜头旋转移动时
  69207. this.cursor.rotation.z = viewer.mainViewport.view.yaw;
  69208. this.needRender = true;
  69209. }
  69210. addPanos(e){
  69211. var panosGroup = new Object3D; panosGroup.name = 'markers';
  69212. panoMarkerMats = {
  69213. default: new MeshBasicMaterial({
  69214. transparent:true,
  69215. opacity: 0.5,
  69216. map: texLoader$7.load(Potree.resourcePath+'/textures/map_marker.png' ),
  69217. }),
  69218. selected: new MeshBasicMaterial({
  69219. transparent:true,
  69220. opacity: 1,
  69221. map: texLoader$7.load(Potree.resourcePath+'/textures/map_marker.png' ),
  69222. })
  69223. };
  69224. e.images.panos.forEach(pano=>{
  69225. pano.mapMarker = new Mesh(planeGeo$2, panoMarkerMats.default);
  69226. pano.mapMarker.position.copy(pano.position).setZ(0);
  69227. pano.mapMarker.scale.set(markerSize,markerSize,markerSize);
  69228. pano.mapMarker.name = 'mapMarker';
  69229. panosGroup.add(pano.mapMarker);
  69230. let mouseover = (e)=>{
  69231. if(!e.byMap){
  69232. pano.mapMarker.material = panoMarkerMats.selected;
  69233. if(!e.byMainView) pano.dispatchEvent({type: "hoverOn", byMap:true});
  69234. this.needRender = true;
  69235. }
  69236. };
  69237. let mouseleave = (e)=>{
  69238. if(!e.byMap){
  69239. pano.mapMarker.material = panoMarkerMats.default;
  69240. if(!e.byMainView) pano.dispatchEvent({type: "hoverOff", byMap:true});
  69241. this.needRender = true;
  69242. }
  69243. };
  69244. pano.mapMarker.addEventListener('mouseover', mouseover);
  69245. pano.mapMarker.addEventListener('mouseleave', mouseleave);
  69246. pano.addEventListener('hoverOn', mouseover);
  69247. pano.addEventListener('hoverOff', mouseleave);
  69248. let onclick = (e)=>{
  69249. viewer.images360.flyToPano(pano);
  69250. };
  69251. pano.mapMarker.addEventListener('click', onclick);
  69252. pano.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  69253. //console.log('panoMarker isVisible', pano.id, e.visible)
  69254. Potree.Utils.updateVisible(pano.mapMarker, 'panoVisible', e.visible );
  69255. this.needRender = true;
  69256. });
  69257. pano.addEventListener('rePos',(e)=>{
  69258. pano.mapMarker.position.copy(pano.position).setZ(0);
  69259. });
  69260. });
  69261. this.scene.add(panosGroup);
  69262. panosGroup.position.z = panosHeight;
  69263. this.panosGroup = panosGroup;
  69264. Potree.Utils.setObjectLayers(panosGroup, 'mapObjects' );
  69265. /* e.images.on('markersDisplayChange', (show)=>{
  69266. panosGroup.visible = show
  69267. this.needRender = true
  69268. }) */
  69269. //-------
  69270. //this.fitPanosToViewport()
  69271. this.initFitView();
  69272. }
  69273. updateClosestPano(intersect){
  69274. if(viewer.images360.flying)return;
  69275. intersect = intersect && intersect.orthoIntersect;
  69276. if(!intersect)return
  69277. intersect = intersect.clone().setZ(0);
  69278. const minDis = 20; //距离鼠标不能太远
  69279. var filterFuncs = [
  69280. Images360.filters.isEnabled(),
  69281. Images360.filters.isVisible(),//只走显示的点,否则会走到别的层
  69282. (pano)=>{
  69283. return pano.position.clone().setZ(0).distanceTo(intersect) < minDis
  69284. },
  69285. ];
  69286. var pano = Common$1.find(viewer.images360.panos, filterFuncs, [Images360.sortFunctions.floorDisSquaredToPoint(intersect)]);
  69287. if (pano && pano != viewer.images360.currentPano ) {
  69288. viewer.images360.flyToPano(pano);
  69289. }
  69290. }
  69291. fitPanosToViewport(){//使所有漫游点占满viewport
  69292. //var w = viewer.bound.boundSize.x;
  69293. var boundSize = viewer.images360.bound.size.clone().multiplyScalar(1.1);
  69294. boundSize.max(new Vector3(4,4,4));
  69295. let endPosition = viewer.images360.bound.center.clone();
  69296. this.moveTo(endPosition, boundSize, 0);
  69297. }
  69298. fitToPointcloud(pointcloud, duration=400){
  69299. var boundSize = pointcloud.bound.getSize(new Vector3);/* .multiplyScalar(1.1); */
  69300. boundSize.max(new Vector3(4,4,4));
  69301. let endPosition = pointcloud.bound.getCenter(new Vector3);
  69302. this.moveTo(endPosition, boundSize, duration); //给点duration去变化 否则地图放大后所占的还是很小
  69303. }
  69304. initFitView(){
  69305. let dis = 5 , px = 70; //地图上px像素长度代表的距离为dis //px是手动缩放到5m后发现是这个长度
  69306. let zoom = px / dis;
  69307. this.camera.zoom = zoom;
  69308. this.moveTo(viewer.images360.position/* viewer.images360.bound.center */);
  69309. this.camera.updateProjectionMatrix();
  69310. }
  69311. fitToDatasets(datasets){
  69312. let bound = new Box3;
  69313. datasets.forEach(e=>bound.union(e.bound));
  69314. let center = bound.getCenter(new Vector3);
  69315. let size = bound.getSize(new Vector3);
  69316. this.moveTo(center, size, 200 ); //给duration是为了顺应视口大小改变,缓冲
  69317. }
  69318. moveTo(endPosition, boundSize, duration=0, margin, easeName ){//前两个参数有xy即可
  69319. endPosition = new Vector3(endPosition.x,endPosition.y,Potree.config.map.cameraHeight);
  69320. this.view.moveOrthoCamera(this.viewports[0], {endPosition, boundSize, margin}, duration, easeName);
  69321. /* let endZoom, startZoom = this.camera.zoom
  69322. //修改相机为bound中心,这样能看到全部(宽度范围内)
  69323. this.view.setView({ position:endPosition, duration,
  69324. callback:()=>{//done
  69325. },
  69326. onUpdate:(progress)=>{
  69327. if(boundSize){
  69328. let aspect = boundSize.x / boundSize.y
  69329. let w, h;
  69330. if(this.camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  69331. h = boundSize.y
  69332. //w = h * this.camera.aspect
  69333. endZoom = this.viewports[0].resolution.y / h
  69334. }else{
  69335. w = boundSize.x;
  69336. //h = w / this.camera.aspect
  69337. endZoom = this.viewports[0].resolution.x / w
  69338. }
  69339. //onUpdate时更新endzoom是因为画布大小可能更改
  69340. this.camera.zoom = endZoom * progress + startZoom * (1 - progress)
  69341. this.camera.updateProjectionMatrix()
  69342. }
  69343. },
  69344. Easing:easeName
  69345. }) */
  69346. }
  69347. updateWhenAtViewer(e){//两个触发来源: 1 camera_changed时 2 mapLayer.needUpdate时。 render在viewer中执行
  69348. if(this.attachedToViewer){
  69349. if(this.started) this.mapLayer.update();
  69350. this.needRender = true;
  69351. }
  69352. }
  69353. update(delta, areaSize ){
  69354. if(!this.visible && !this.attachedToViewer )return
  69355. if(this.attachedToViewer){
  69356. if(this.mapLayer.needUpdate){
  69357. this.updateWhenAtViewer();
  69358. }
  69359. return
  69360. }
  69361. this.updateScreenSize();
  69362. this.controls.update(delta);
  69363. this.view.applyToCamera(this.camera);
  69364. let changed = this.cameraChanged();
  69365. if(this.started && (changed || this.mapLayer.needUpdate))this.mapLayer.update();
  69366. if(changed /*|| || this.needRender */){
  69367. /* this.dispatchEvent({
  69368. type: "camera_changed",
  69369. camera: this.camera,
  69370. viewport : this.viewports[0]
  69371. }) */
  69372. this.mapChanged = true;
  69373. this.needRender = true;
  69374. this.updateCursor();//更改大小
  69375. }
  69376. this.render();
  69377. }
  69378. attachToMainViewer(state, desc, mapRatio=0.5, options={}){//转移到viewer中。测量时展示or截图需要
  69379. if(!Potree.settings.isOfficial)this.renderArea.style.display = state ? 'none':'block';
  69380. if(state){
  69381. this.enabledOld = this.enabled;
  69382. this.enabled = true;
  69383. if(mapRatio != 'dontSet'){
  69384. this.changeSplitScreenDir(options.dir, mapRatio);
  69385. if(this.attachedToViewer){
  69386. //this.fitPanosToViewport()
  69387. viewer.updateScreenSize({forceUpdateSize:true});
  69388. return
  69389. }
  69390. viewer.viewports = [viewer.mainViewport, viewer.mapViewer.viewports[0] ];//因为mainViewer的相机变化会触发map的变化,所以先渲染mainViewer
  69391. }
  69392. if(desc == 'measure') this.inputHandler.registerInteractiveScene(viewer.measuringTool.scene);//虽然用的是viewer的inputHandler,但借用了this.inputHandler的interactiveScenes
  69393. else if(desc == 'split4Screens') {
  69394. this.inputHandler.registerInteractiveScene(viewer.scene.scene);
  69395. }
  69396. }else {
  69397. if(!this.attachedToViewer)return
  69398. viewer.mainViewport.left = 0;
  69399. viewer.mainViewport.bottom = 0;
  69400. viewer.mainViewport.width = 1;
  69401. viewer.mainViewport.height = 1;
  69402. this.viewports[0].width = 1;
  69403. this.viewports[0].bottom = 0;
  69404. this.viewports[0].height = 1;
  69405. this.viewports[0].left = 0;
  69406. this.inputHandler.unregisterInteractiveScene(viewer.measuringTool.scene);
  69407. this.inputHandler.unregisterInteractiveScene(viewer.scene.scene);
  69408. viewer.viewports = [viewer.mainViewport];
  69409. this.updateScreenSize({forceUpdateSize:true}); //更新相机projectionMatrix
  69410. }
  69411. //if(desc == 'measure')this.renderMeasure = state
  69412. this.attachedToViewer = state;
  69413. viewer.updateScreenSize({forceUpdateSize:true});
  69414. //mapRatio != 'dontSet' && !options.dontFit && this.moveTo(...)//要写在updateScreenSize后面,因为要根据视图大小来fit
  69415. if(options.moveToCurrentPos){
  69416. let boundSize = new Vector2(10,10);
  69417. let duration = 1000;
  69418. this.moveTo(viewer.images360.position.clone(), boundSize, duration);
  69419. }
  69420. this.needRender = true;
  69421. }
  69422. changeSplitScreenDir(dir, mapRatio){//左右 | 上下
  69423. //if(!dir || dir == this.dir)return
  69424. if(dir )this.splitDir = dir;
  69425. this.updateSplitSize(mapRatio);
  69426. /* if(this.attachedToViewer){ //如果已经分屏了,中途修改方向的话……
  69427. this.updateSplitSize()
  69428. } */
  69429. }
  69430. updateSplitSize(mapRatio){
  69431. if(mapRatio != void 0) this.mapRatio = mapRatio;
  69432. //console.log(this.mapRatio)
  69433. if(this.splitDir == 'leftRight'){//地图在左方
  69434. viewer.mainViewport.left = this.mapRatio;
  69435. viewer.mainViewport.width = 1-this.mapRatio;
  69436. this.viewports[0].width = this.mapRatio;
  69437. viewer.mainViewport.bottom = this.viewports[0].bottom = 0;
  69438. viewer.mainViewport.height = this.viewports[0].height = 1;
  69439. }else if(this.splitDir == 'upDown'){ //地图在下方
  69440. viewer.mainViewport.bottom = this.mapRatio;
  69441. viewer.mainViewport.height = 1-this.mapRatio;
  69442. this.viewports[0].height = this.mapRatio;
  69443. viewer.mainViewport.left = this.viewports[0].left = 0;
  69444. viewer.mainViewport.width = this.viewports[0].width = 1;
  69445. }
  69446. if(this.attachedToViewer){
  69447. viewer.updateScreenSize({forceUpdateSize:true});
  69448. }
  69449. }
  69450. render1(params={}){//viewer的preserveDrawingBuffer为false时的版本
  69451. let needCopy, waitCopy;
  69452. if(!this.visible && !this.attachedToViewer || !this.needRender && !params.force){
  69453. if(this.attachedToViewer ){
  69454. needCopy = true;
  69455. }else {
  69456. return
  69457. }
  69458. }
  69459. waitCopy = this.attachedToViewer && this.needRender && !params.force;//是否写入到copyBuffer。双屏时,若needRender就拷贝到copyBuffer中,双屏时就直接使用copyBuffer。 四屏时因渲染点云会每帧都渲染,所以不需要缓存。
  69460. let renderer = params.renderer || this.renderer;
  69461. if(waitCopy){
  69462. this.copyBuffer.setSize(params.viewport.resolution2.x, params.viewport.resolution2.y);
  69463. renderer.setRenderTarget(this.copyBuffer);
  69464. }else if(params.target){
  69465. renderer.setRenderTarget(params.target);
  69466. }
  69467. /* if(params.resize){
  69468. this.emitResizeMsg(new THREE.Vector2(params.width,params.height, viewport:params.viewport))
  69469. } */
  69470. params.clear ? params.clear() : renderer.clear();
  69471. if(!needCopy || waitCopy){//重绘
  69472. viewer.dispatchEvent({type: "render.begin", viewer: this, viewport:this.viewports[0], params });
  69473. Potree.Utils.setCameraLayers(this.camera, ['map','mapObjects' , 'bothMapAndScene' ]);
  69474. if(this.mapGradientBG){//渲染背景
  69475. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  69476. renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  69477. }
  69478. renderer.render(this.scene, this.camera);
  69479. renderer.render(viewer.scene.scene, this.camera);
  69480. //测量线等
  69481. //params.renderOverlay && params.renderOverlay( $.extend({}, params, { isMap:true }))
  69482. renderer.setRenderTarget(params.target||null);
  69483. }
  69484. if(needCopy || waitCopy){//使用缓存 ----当viewer的preserveDrawingBuffer为false的话,使用buffer
  69485. this.copyPass.render(null,null, null, renderer, params.target||null, this.copyBuffer);
  69486. }
  69487. this.needRender = false;
  69488. return true
  69489. }
  69490. //拆成两次渲染,一个地图一个其他物体,且地图渲染后保存在buffer中,只有当地图变化后才重渲染。
  69491. render(params={}){
  69492. if(!this.visible && !this.attachedToViewer || !this.needRender && !params.force){ //注意:mapViewer.needRender的权重高于它的viewport的needRender,也就是说,当attachedToViewer时,viewer即使needRender, mapViewer也不一定会渲染。
  69493. return
  69494. }
  69495. viewer.addTimeMark('mapRender','start');
  69496. let renderer = params.renderer || this.renderer;
  69497. if(this.mapChanged){ //渲染地图背景
  69498. renderer.setRenderTarget(this.copyBuffer);
  69499. params.clear ? params.clear() : renderer.clear();
  69500. if(this.mapGradientBG){//渲染背景
  69501. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  69502. renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  69503. }
  69504. Potree.Utils.setCameraLayers(this.camera, ['map']);
  69505. renderer.render(this.scene, this.camera);
  69506. params.renderBG && params.renderBG(this.viewports[0]);
  69507. this.mapChanged = false;
  69508. renderer.setRenderTarget(params.target||null);
  69509. }
  69510. params.clear ? params.clear() : renderer.clear();
  69511. this.copyPass.render(null,null, null,renderer, params.target||null, this.copyBuffer); //拷贝地图背景
  69512. renderer.clearDepth(); //防止地图遮挡其他物体
  69513. //绘制其他物体
  69514. Potree.Utils.setCameraLayers(this.camera, ['mapObjects' , 'bothMapAndScene' ]);
  69515. viewer.dispatchEvent({type: "render.begin", viewer: this, viewport:this.viewports[0], params });
  69516. renderer.render(this.scene, this.camera);
  69517. this.attachedToViewer || renderer.render(viewer.scene.scene, this.camera); //类同renderOverlay
  69518. renderer.setRenderTarget(null);
  69519. this.needRender = false;
  69520. viewer.addTimeMark('mapRender','end');
  69521. return true
  69522. }
  69523. }
  69524. /*
  69525. 渲染顺序:
  69526. 地图
  69527. 背景Overlay
  69528. 地图scene的物体,如cursor、 marker
  69529. 点云(如果有)
  69530. overlay,两层:第一层:viewer的scene中bothMapAndScene的如reticule. 第二层:如测量线(attachToMainViewer时才渲染)
  69531. */
  69532. //本地调试地图白屏是因为代码自动更新了 但没刷新
  69533. class NavigationCube extends Object3D {
  69534. constructor(viewer){
  69535. super();
  69536. this.viewer = viewer;
  69537. let createPlaneMaterial = (img) => {
  69538. let material = new MeshBasicMaterial( {
  69539. depthTest: true,
  69540. depthWrite: true,
  69541. side: DoubleSide
  69542. });
  69543. new TextureLoader().load(
  69544. exports.resourcePath + '/textures/navigation/' + img,
  69545. function(texture) {
  69546. texture.anisotropy = viewer.renderer.capabilities.getMaxAnisotropy();
  69547. material.map = texture;
  69548. material.needsUpdate = true;
  69549. });
  69550. return material;
  69551. };
  69552. let planeGeometry = new PlaneGeometry(1, 1);
  69553. this.front = new Mesh(planeGeometry, createPlaneMaterial('F.png'));
  69554. this.front.position.y = -0.5;
  69555. this.front.rotation.x = Math.PI / 2.0;
  69556. this.front.updateMatrixWorld();
  69557. this.front.name = "F";
  69558. this.add(this.front);
  69559. this.back = new Mesh(planeGeometry, createPlaneMaterial('B.png'));
  69560. this.back.position.y = 0.5;
  69561. this.back.rotation.x = Math.PI / 2.0;
  69562. this.back.updateMatrixWorld();
  69563. this.back.name = "B";
  69564. this.add(this.back);
  69565. this.left = new Mesh(planeGeometry, createPlaneMaterial('L.png'));
  69566. this.left.position.x = -0.5;
  69567. this.left.rotation.y = Math.PI / 2.0;
  69568. this.left.updateMatrixWorld();
  69569. this.left.name = "L";
  69570. this.add(this.left);
  69571. this.right = new Mesh(planeGeometry, createPlaneMaterial('R.png'));
  69572. this.right.position.x = 0.5;
  69573. this.right.rotation.y = Math.PI / 2.0;
  69574. this.right.updateMatrixWorld();
  69575. this.right.name = "R";
  69576. this.add(this.right);
  69577. this.bottom = new Mesh(planeGeometry, createPlaneMaterial('D.png'));
  69578. this.bottom.position.z = -0.5;
  69579. this.bottom.updateMatrixWorld();
  69580. this.bottom.name = "D";
  69581. this.add(this.bottom);
  69582. this.top = new Mesh(planeGeometry, createPlaneMaterial('U.png'));
  69583. this.top.position.z = 0.5;
  69584. this.top.updateMatrixWorld();
  69585. this.top.name = "U";
  69586. this.add(this.top);
  69587. this.width = 150; // in px
  69588. this.camera = new OrthographicCamera(-1, 1, 1, -1, -1, 1);
  69589. this.camera.position.copy(new Vector3(0, 0, 0));
  69590. this.camera.lookAt(new Vector3(0, 1, 0));
  69591. this.camera.updateMatrixWorld();
  69592. this.camera.rotation.order = "ZXY";
  69593. let onMouseDown = (event) => {
  69594. if (!this.visible) {
  69595. return;
  69596. }
  69597. this.pickedFace = null;
  69598. let mouse = new Vector2();
  69599. mouse.x = event.clientX - (window.innerWidth - this.width);
  69600. mouse.y = event.clientY;
  69601. if(mouse.x < 0 || mouse.y > this.width) return;
  69602. mouse.x = (mouse.x / this.width) * 2 - 1;
  69603. mouse.y = -(mouse.y / this.width) * 2 + 1;
  69604. let raycaster = new Raycaster();
  69605. raycaster.setFromCamera(mouse, this.camera);
  69606. raycaster.ray.origin.sub(this.camera.getWorldDirection(new Vector3()));
  69607. let intersects = raycaster.intersectObjects(this.children);
  69608. let minDistance = 1000;
  69609. for (let i = 0; i < intersects.length; i++) {
  69610. if(intersects[i].distance < minDistance) {
  69611. this.pickedFace = intersects[i].object.name;
  69612. minDistance = intersects[i].distance;
  69613. }
  69614. }
  69615. if(this.pickedFace) {
  69616. this.viewer.setView(this.pickedFace);
  69617. }
  69618. };
  69619. this.viewer.renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  69620. }
  69621. update(rotation) {
  69622. this.camera.rotation.copy(rotation);
  69623. this.visible && this.camera.updateMatrixWorld();
  69624. }
  69625. }
  69626. /**
  69627. *
  69628. * @author sigeom sa / http://sigeom.ch
  69629. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  69630. * @author Markus Schütz / http://potree.org
  69631. *
  69632. */
  69633. class GeoJSONExporter{
  69634. static measurementToFeatures (measurement) {
  69635. let coords = measurement.points.map(e => e.position.toArray());
  69636. let features = [];
  69637. if (coords.length === 1) {
  69638. let feature = {
  69639. type: 'Feature',
  69640. geometry: {
  69641. type: 'Point',
  69642. coordinates: coords[0]
  69643. },
  69644. properties: {
  69645. name: measurement.name
  69646. }
  69647. };
  69648. features.push(feature);
  69649. } else if (coords.length > 1 && !measurement.closed) {
  69650. let object = {
  69651. 'type': 'Feature',
  69652. 'geometry': {
  69653. 'type': 'LineString',
  69654. 'coordinates': coords
  69655. },
  69656. 'properties': {
  69657. name: measurement.name
  69658. }
  69659. };
  69660. features.push(object);
  69661. } else if (coords.length > 1 && measurement.closed) {
  69662. let object = {
  69663. 'type': 'Feature',
  69664. 'geometry': {
  69665. 'type': 'Polygon',
  69666. 'coordinates': [[...coords, coords[0]]]
  69667. },
  69668. 'properties': {
  69669. name: measurement.name
  69670. }
  69671. };
  69672. features.push(object);
  69673. }
  69674. if (measurement.showDistances) {
  69675. measurement.edgeLabels.forEach((label) => {
  69676. let labelPoint = {
  69677. type: 'Feature',
  69678. geometry: {
  69679. type: 'Point',
  69680. coordinates: label.position.toArray()
  69681. },
  69682. properties: {
  69683. distance: label.text
  69684. }
  69685. };
  69686. features.push(labelPoint);
  69687. });
  69688. }
  69689. if (measurement.showArea) {
  69690. let point = measurement.areaLabel.position;
  69691. let labelArea = {
  69692. type: 'Feature',
  69693. geometry: {
  69694. type: 'Point',
  69695. coordinates: point.toArray()
  69696. },
  69697. properties: {
  69698. area: measurement.areaLabel.text
  69699. }
  69700. };
  69701. features.push(labelArea);
  69702. }
  69703. return features;
  69704. }
  69705. static toString (measurements) {
  69706. if (!(measurements instanceof Array)) {
  69707. measurements = [measurements];
  69708. }
  69709. measurements = measurements.filter(m => m instanceof Measure);
  69710. let features = [];
  69711. for (let measure of measurements) {
  69712. let f = GeoJSONExporter.measurementToFeatures(measure);
  69713. features = features.concat(f);
  69714. }
  69715. let geojson = {
  69716. 'type': 'FeatureCollection',
  69717. 'features': features
  69718. };
  69719. return JSON.stringify(geojson, null, '\t');
  69720. }
  69721. }
  69722. /**
  69723. *
  69724. * @author sigeom sa / http://sigeom.ch
  69725. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  69726. * @author Markus Schuetz / http://potree.org
  69727. *
  69728. */
  69729. class DXFExporter {
  69730. static measurementPointSection (measurement) {
  69731. let position = measurement.points[0].position;
  69732. if (!position) {
  69733. return '';
  69734. }
  69735. let dxfSection = `0
  69736. CIRCLE
  69737. 8
  69738. layer_point
  69739. 10
  69740. ${position.x}
  69741. 20
  69742. ${position.y}
  69743. 30
  69744. ${position.z}
  69745. 40
  69746. 1.0
  69747. `;
  69748. return dxfSection;
  69749. }
  69750. static measurementPolylineSection (measurement) {
  69751. // bit code for polygons/polylines:
  69752. // https://www.autodesk.com/techpubs/autocad/acad2000/dxf/polyline_dxf_06.htm
  69753. let geomCode = 8;
  69754. if (measurement.closed) {
  69755. geomCode += 1;
  69756. }
  69757. let dxfSection = `0
  69758. POLYLINE
  69759. 8
  69760. layer_polyline
  69761. 62
  69762. 1
  69763. 66
  69764. 1
  69765. 10
  69766. 0.0
  69767. 20
  69768. 0.0
  69769. 30
  69770. 0.0
  69771. 70
  69772. ${geomCode}
  69773. `;
  69774. let xMax = 0.0;
  69775. let yMax = 0.0;
  69776. let zMax = 0.0;
  69777. for (let point of measurement.points) {
  69778. point = point.position;
  69779. xMax = Math.max(xMax, point.x);
  69780. yMax = Math.max(yMax, point.y);
  69781. zMax = Math.max(zMax, point.z);
  69782. dxfSection += `0
  69783. VERTEX
  69784. 8
  69785. 0
  69786. 10
  69787. ${point.x}
  69788. 20
  69789. ${point.y}
  69790. 30
  69791. ${point.z}
  69792. 70
  69793. 32
  69794. `;
  69795. }
  69796. dxfSection += `0
  69797. SEQEND
  69798. `;
  69799. return dxfSection;
  69800. }
  69801. static measurementSection (measurement) {
  69802. // if(measurement.points.length <= 1){
  69803. // return "";
  69804. // }
  69805. if (measurement.points.length === 0) {
  69806. return '';
  69807. } else if (measurement.points.length === 1) {
  69808. return DXFExporter.measurementPointSection(measurement);
  69809. } else if (measurement.points.length >= 2) {
  69810. return DXFExporter.measurementPolylineSection(measurement);
  69811. }
  69812. }
  69813. static toString(measurements){
  69814. if (!(measurements instanceof Array)) {
  69815. measurements = [measurements];
  69816. }
  69817. measurements = measurements.filter(m => m instanceof Measure);
  69818. let points = measurements.filter(m => (m instanceof Measure))
  69819. .map(m => m.points)
  69820. .reduce((a, v) => a.concat(v))
  69821. .map(p => p.position);
  69822. let min = new Vector3(Infinity, Infinity, Infinity);
  69823. let max = new Vector3(-Infinity, -Infinity, -Infinity);
  69824. for (let point of points) {
  69825. min.min(point);
  69826. max.max(point);
  69827. }
  69828. let dxfHeader = `999
  69829. DXF created from potree
  69830. 0
  69831. SECTION
  69832. 2
  69833. HEADER
  69834. 9
  69835. $ACADVER
  69836. 1
  69837. AC1006
  69838. 9
  69839. $INSBASE
  69840. 10
  69841. 0.0
  69842. 20
  69843. 0.0
  69844. 30
  69845. 0.0
  69846. 9
  69847. $EXTMIN
  69848. 10
  69849. ${min.x}
  69850. 20
  69851. ${min.y}
  69852. 30
  69853. ${min.z}
  69854. 9
  69855. $EXTMAX
  69856. 10
  69857. ${max.x}
  69858. 20
  69859. ${max.y}
  69860. 30
  69861. ${max.z}
  69862. 0
  69863. ENDSEC
  69864. `;
  69865. let dxfBody = `0
  69866. SECTION
  69867. 2
  69868. ENTITIES
  69869. `;
  69870. for (let measurement of measurements) {
  69871. dxfBody += DXFExporter.measurementSection(measurement);
  69872. }
  69873. dxfBody += `0
  69874. ENDSEC
  69875. `;
  69876. let dxf = dxfHeader + dxfBody + '0\nEOF';
  69877. return dxf;
  69878. }
  69879. }
  69880. class HandleSvg extends EventDispatcher{
  69881. constructor(position, color){
  69882. super();
  69883. this.position = position;
  69884. this.color = '#'+new Color(color).getHexString();
  69885. this.svg = this.create();
  69886. this.visible_ = true;
  69887. let update = ()=>{
  69888. this.update();
  69889. };
  69890. viewer.addEventListener("camera_changed", update);
  69891. this.addEventListener('dispose', ()=>{
  69892. viewer.removeEventListener("camera_changed", update);
  69893. });
  69894. }
  69895. create(){
  69896. const svgns = "http://www.w3.org/2000/svg";
  69897. const svg = document.createElementNS(svgns, "svg");
  69898. svg.setAttribute("width", "2em");
  69899. svg.setAttribute("height", "2em");
  69900. svg.setAttribute("position", "absolute");
  69901. svg.style.left = "50px";
  69902. svg.style.top = "50px";
  69903. svg.style.position = "absolute";
  69904. svg.style.zIndex = "10000";
  69905. svg.style.cursor = 'grab';
  69906. svg.style.transform = 'translate(-50%,-50%)';
  69907. const circle = document.createElementNS(svgns, 'circle');
  69908. circle.setAttributeNS(null, 'cx', "1em");
  69909. circle.setAttributeNS(null, 'cy', "1em");
  69910. circle.setAttributeNS(null, 'r', "0.5em");
  69911. circle.setAttributeNS(null, 'style', 'fill: '+this.color+'; stroke: black; stroke-width: 0.2em;' );
  69912. svg.appendChild(circle);
  69913. const element = viewer.renderer.domElement.parentElement;
  69914. element.appendChild(svg);
  69915. const startDrag = (evt) => {
  69916. /* if(evt.button === THREE.MOUSE.RIGHT){
  69917. return
  69918. } */
  69919. this.selectedElement = svg;
  69920. document.addEventListener("mousemove", drag);
  69921. };
  69922. const endDrag = (evt) => {
  69923. this.selectedElement = null;
  69924. document.removeEventListener("mousemove", drag);
  69925. };
  69926. const drag = (evt) => {
  69927. if (this.selectedElement) {
  69928. evt.preventDefault();
  69929. const rect = viewer.renderer.domElement.getBoundingClientRect();
  69930. const x = evt.clientX - rect.x;
  69931. const y = evt.clientY - rect.y;
  69932. const {width, height} = viewer.renderer.getSize(new Vector2());
  69933. const camera = viewer.scene.getActiveCamera();
  69934. const projected = this.position.clone().project(camera);
  69935. projected.x = ((x / width) - 0.5) / 0.5;
  69936. projected.y = (-(y - height) / height - 0.5) / 0.5;
  69937. const unprojected = projected.clone().unproject(camera);
  69938. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  69939. this.update();
  69940. this.dispatchEvent({type:'dragged', position: this.position});
  69941. }
  69942. };
  69943. svg.addEventListener('mousedown', startDrag);
  69944. svg.addEventListener('mouseup', endDrag);
  69945. svg.style.display = this.visible ? "" : "none";
  69946. this.addEventListener('dispose',()=>{
  69947. svg.removeEventListener('mousedown', startDrag);
  69948. svg.removeEventListener('mouseup', endDrag);
  69949. });
  69950. return svg
  69951. }
  69952. set visible(v){
  69953. this.visible_ = v;
  69954. if(v){
  69955. this.update();
  69956. }else {
  69957. this.svg.style.display = "none";
  69958. }
  69959. }
  69960. get visible(){
  69961. return this.visible_
  69962. }
  69963. update(){
  69964. if(!this.visible)return
  69965. let camera = viewer.scene.getActiveCamera();
  69966. var p = Potree.Utils.getPos2d( this.position, viewer.mainViewport, viewer.renderArea);
  69967. if(!p.trueSide){
  69968. return this.svg.style.display = 'none';
  69969. }
  69970. this.svg.style.left = p.posInViewport.x;
  69971. this.svg.style.top = p.posInViewport.y;
  69972. this.svg.style.display = '';
  69973. }
  69974. dispose(){
  69975. this.svg.remove();
  69976. this.dispatchEvent('dispose');
  69977. }
  69978. }
  69979. /*
  69980. 两种拖拽方式:
  69981. 1 只依附在点云上
  69982. 2 平行于镜头view移动 */
  69983. const geo$1 = new PlaneBufferGeometry(1,1);
  69984. class HandleSprite extends Sprite$2{
  69985. constructor(position,options={}){
  69986. options.sizeInfo = {width2d:60};
  69987. super(options);
  69988. this.position.copy(position);
  69989. this.dragStyle = options.dragStyle || 'default'; //'default'||'onPointCloud'
  69990. this.bindEvent();
  69991. }
  69992. bindEvent(){
  69993. let projectedStart, pointerStart;
  69994. const drag = (e)=>{
  69995. /* if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  69996. viewer.dispatchEvent({
  69997. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  69998. })
  69999. return
  70000. } */
  70001. const camera = viewer.scene.getActiveCamera();
  70002. if(projectedStart){
  70003. let move2d = new Vector2().subVectors(e.pointer, pointerStart);
  70004. let projectNow = projectedStart.clone();
  70005. projectNow.x += move2d.x;
  70006. projectNow.y += move2d.y;
  70007. let unprojected = projectNow.clone().unproject(camera);
  70008. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  70009. }else {
  70010. projectedStart = this.position.clone().project(camera);
  70011. pointerStart = e.pointer.clone();
  70012. }
  70013. this.update();
  70014. this.dispatchEvent({type:'dragged', position: this.position });
  70015. };
  70016. const drop = (e)=>{
  70017. projectedStart = null, pointerStart = null;
  70018. };
  70019. const mouseover = (e) => {
  70020. viewer.dispatchEvent({
  70021. type : "CursorChange", action : "add", name:"markerMove"
  70022. });
  70023. };
  70024. const mouseleave = (e) => {
  70025. viewer.dispatchEvent({
  70026. type : "CursorChange", action : "remove", name:"markerMove"
  70027. });
  70028. };
  70029. this.addEventListener('drag', drag);
  70030. this.addEventListener('drop', drop);
  70031. this.addEventListener('mouseover', mouseover);
  70032. this.addEventListener('mouseleave', mouseleave);
  70033. }
  70034. }
  70035. const sphere = new Mesh(new SphereBufferGeometry(0.08,0.08,3,2), new MeshBasicMaterial({color:'#f88'}));
  70036. class CurveCtrl extends Object3D {
  70037. constructor(points, lineMat, color, name, options={}){
  70038. super();
  70039. this.curve = new CatmullRomCurve3(points, false, "centripetal" /* , tension */);
  70040. this.name = name || 'curveNode';
  70041. this.handleMat = options.handleMat;
  70042. this.lineMat = lineMat;
  70043. this.createPath();
  70044. this.color = color;
  70045. this.handles = [];
  70046. this.wholeLength = 0;
  70047. this.viewports = options.viewports || [viewer.mainViewport]; //for HandleSprite
  70048. for(let i=0,j=this.points.length; i<j;i++){
  70049. this.handles.push(this.createHandle(this.points[i]));
  70050. }
  70051. this.visible_ = true;
  70052. if(Potree.settings.isTest){
  70053. this.spheres = new Object3D;
  70054. /* let i = Count+1;
  70055. while(i>0){
  70056. this.spheres.add(sphere.clone());
  70057. i--;
  70058. } */
  70059. this.add(this.spheres);
  70060. }
  70061. this.updatePath();
  70062. }
  70063. addPoint(position, index, ifUpdate){
  70064. let length = this.points.length;
  70065. if(index == void 0 ){
  70066. index = length;
  70067. }
  70068. let handle = this.createHandle(position);
  70069. this.handles = [...this.handles.slice(0,index), handle, ...this.handles.slice(index,length)];
  70070. this.points = [...this.points.slice(0,index), position, ...this.points.slice(index,length)];
  70071. ifUpdate && (this.updatePath(), this.updateHandle(index));
  70072. }
  70073. removePoint(index){
  70074. let handle = this.handles[index];
  70075. handle.dispose();
  70076. this.handles.splice(index,1);
  70077. this.points.splice(index,1);
  70078. this.updatePath();
  70079. }
  70080. createPath(){
  70081. const line = LineDraw.createFatLine( [ ],this.lineMat);
  70082. this.line = line;
  70083. this.add(line);
  70084. }
  70085. updatePath(){
  70086. this.curve.needsUpdate = true; //如果不更新,得到的点不均匀,开头点少。
  70087. let points, length = this.points.length;
  70088. this.wholeLength = this.points.reduce((total, currentValue, currentIndex, arr)=>{ //所有端点的距离总和
  70089. if(currentIndex == 0)return 0
  70090. return total + currentValue.distanceTo(arr[currentIndex-1]);
  70091. },0);
  70092. if(length > 1){
  70093. const count = MathUtils.clamp(Math.ceil(this.wholeLength * 5), 30, 500);
  70094. points = this.curve.getSpacedPoints( count );
  70095. if(this.needsPercent){ //获取每个节点在整条中的百分比,便于定位(但不精确)
  70096. this.pointsPercent = [0];
  70097. let sums = [0];
  70098. let sum = 0, last = points[0];
  70099. for(let i=1;i<length;i++){
  70100. let point = this.points[i];
  70101. sum += point.distanceTo(last); //参考getLengths函数,根据长度得到百分比
  70102. last = point;
  70103. sums.push(sum);
  70104. }
  70105. for(let i=1;i<length;i++){
  70106. this.pointsPercent.push(sum == 0 ? i/length : sums[i] / sum);
  70107. }
  70108. }
  70109. if(Potree.settings.isTest){
  70110. this.spheres.children.forEach(e=>e.visible = false);
  70111. points.forEach((e,i)=>{
  70112. let sphere1 = this.spheres.children[i];
  70113. if(!sphere1){
  70114. sphere1 = sphere.clone();
  70115. this.spheres.add(sphere1);
  70116. }
  70117. sphere1.position.copy(e);
  70118. sphere1.visible = true;
  70119. });
  70120. }
  70121. }else {
  70122. points = [];
  70123. }
  70124. LineDraw.updateLine(this.line, points);
  70125. this.dispatchEvent('updatePath');
  70126. }
  70127. createHandle(position){
  70128. if(this.handleMat){
  70129. var handle = new HandleSprite(position, {mat:this.handleMat, viewports:this.viewports});
  70130. this.add(handle);
  70131. }else {
  70132. var handle = new HandleSvg(position, this.color);
  70133. }
  70134. handle.visible = this.visible;
  70135. handle.addEventListener('dragged',(e)=>{
  70136. let index = this.handles.indexOf(handle);
  70137. this.points[index].copy(e.position);
  70138. this.updatePath();
  70139. this.dispatchEvent({type:'dragCurvePoint', index});
  70140. });
  70141. return handle
  70142. }
  70143. updateHandle(index){
  70144. if(!this.visible)return
  70145. this.handles[index].update();
  70146. }
  70147. updateHandles(){
  70148. this.handles.forEach((handle,index)=>{
  70149. this.updateHandle(index);
  70150. });
  70151. }
  70152. update(){
  70153. this.updateHandles();
  70154. this.updatePath();
  70155. }
  70156. set visible(v){
  70157. if(v != this.visible_ ){
  70158. this.visible_ = v;
  70159. this.visible = v;
  70160. if(this.handles){
  70161. this.handles.forEach(e=>e.visible = v );
  70162. if(v) this.updateHandles(); //因为不可见时没更新位置
  70163. }
  70164. }
  70165. }
  70166. get visible(){
  70167. return this.visible_
  70168. }
  70169. /* set visible(v){
  70170. this.handles.forEach(e=>e.svg.style.display = v ? "" : "none" )
  70171. if(v) this.updateHandles() //因为不可见时没更新位置
  70172. } */
  70173. get points(){
  70174. return this.curve.points;
  70175. }
  70176. set points(points){
  70177. this.curve.points = points;
  70178. }
  70179. getPointAt(t){
  70180. return this.curve.getPointAt(t)
  70181. }
  70182. getSpacedPoints(t){
  70183. return this.curve.getSpacedPoints(t)
  70184. }
  70185. dispose(){
  70186. this.parent && this.parent.remove(this);
  70187. this.handles.forEach(e=>e.dispose() );
  70188. this.line.geometry && this.line.geometry.dispose();
  70189. }
  70190. }
  70191. const colors$1 = {
  70192. position: 'red',
  70193. target : 'blue'
  70194. };
  70195. let lineMats$1;
  70196. const getLineMat = function(name){
  70197. if(!lineMats$1){
  70198. lineMats$1 = {
  70199. position: LineDraw.createFatLineMat({
  70200. color: colors$1.position,
  70201. lineWidth: 3
  70202. }),
  70203. target : LineDraw.createFatLineMat({
  70204. color: colors$1.target,
  70205. lineWidth: 3
  70206. }),
  70207. frustum: LineDraw.createFatLineMat({
  70208. color: colors$1.position,
  70209. lineWidth: 2
  70210. }),
  70211. aimAtTarget: new LineBasicMaterial({color:colors$1.target, depthTest:false})
  70212. };
  70213. }
  70214. return lineMats$1[name]
  70215. };
  70216. class CameraAnimation$1 extends EventDispatcher{
  70217. constructor(viewer){
  70218. super();
  70219. this.viewer = viewer;
  70220. this.selectedElement = null;
  70221. //this.controlPoints = [];
  70222. this.uuid = MathUtils.generateUUID();
  70223. this.node = new Object3D();
  70224. this.node.name = "camera animation";
  70225. this.viewer.scene.scene.add(this.node);
  70226. this.frustum = this.createFrustum();
  70227. this.node.add(this.frustum);
  70228. this.name = "Camera Animation";
  70229. // "centripetal", "chordal", "catmullrom"
  70230. this.curveType = "centripetal";
  70231. this.visible = true;
  70232. this.targets = [];
  70233. this.createPath();
  70234. this.duration = 5;
  70235. this.percent = 0;
  70236. this.currentIndex = 0;
  70237. this.durations = [];
  70238. this.quaternions = [];
  70239. if(!Potree.settings.isTest && Potree.settings.isOfficial ){
  70240. this.setVisible(false);
  70241. }
  70242. this.addEventListener('dispose', ()=>{
  70243. this.dispose();
  70244. });
  70245. this.targetLines = new Object3D;
  70246. this.node.add(this.targetLines);
  70247. }
  70248. static defaultFromView(viewer){
  70249. const animation = new CameraAnimation$1(viewer);
  70250. const camera = viewer.scene.getActiveCamera();
  70251. const target = viewer.scene.view.getPivot();
  70252. const cpCenter = new Vector3(
  70253. 0.3 * camera.position.x + 0.7 * target.x,
  70254. 0.3 * camera.position.y + 0.7 * target.y,
  70255. 0.3 * camera.position.z + 0.7 * target.z,
  70256. );
  70257. const targetCenter = new Vector3(
  70258. 0.05 * camera.position.x + 0.95 * target.x,
  70259. 0.05 * camera.position.y + 0.95 * target.y,
  70260. 0.05 * camera.position.z + 0.95 * target.z,
  70261. );
  70262. const r = 2;//camera.position.distanceTo(target) * 0.3;
  70263. //const dir = target.clone().sub(camera.position).normalize();
  70264. const angle = Utils.computeAzimuth(camera.position, target);
  70265. const n = 5;
  70266. for(let i = 0; i < n; i++){
  70267. let u = 1.5 * Math.PI * (i / n) + angle;
  70268. const dx = r * Math.cos(u);
  70269. const dy = r * Math.sin(u);
  70270. const cpPos = new Vector3(
  70271. cpCenter.x + dx,
  70272. cpCenter.y + dy,
  70273. cpCenter.z,
  70274. );
  70275. const targetPos = new Vector3(
  70276. targetCenter.x + dx * 0.1,
  70277. targetCenter.y + dy * 0.1,
  70278. targetCenter.z,
  70279. );
  70280. animation.createControlPoint(null,{position:cpPos, target:targetPos});
  70281. }
  70282. animation.changeCallback();
  70283. return animation;
  70284. }
  70285. createControlPoint(index, posInfo ){
  70286. const length = this.posCurve.points.length;
  70287. const position = new Vector3;
  70288. const target = new Vector3;
  70289. if(index == void 0 ){
  70290. index = length;
  70291. }
  70292. if(!posInfo){
  70293. if(length >= 2 && index === 0){
  70294. const dir = new Vector3().subVectors(this.posCurve.points[0], this.posCurve.points[1] );
  70295. position.copy(this.posCurve.points[0]).add(dir);
  70296. const tDir = new Vector3().subVectors(this.targets[0].position, this.targets[1].position );
  70297. target.copy(this.targets[0].position).add(dir);
  70298. }else if(length >= 2 && index === length){
  70299. const dir = new Vector3().subVectors(this.posCurve.points[length-1], this.posCurve.points[length-2] );
  70300. position.copy(this.posCurve.points[length-2]).add(dir);
  70301. const tDir = new Vector3().subVectors(this.targets[length-1].position, this.targets[length-2].position );
  70302. target.copy(this.targets[length-2].position).add(dir);
  70303. }else if(length >= 2){
  70304. position.copy(this.posCurve.points[index-1].clone().add(this.posCurve.points[index]).multiplyScalar(0.5));
  70305. target.copy(this.targets[index-1].position.clone().add(this.targets[index].position).multiplyScalar(0.5));
  70306. }
  70307. }else {
  70308. position.copy(posInfo.position);
  70309. target.copy(posInfo.target);
  70310. }
  70311. this.posCurve.addPoint(position, index/* , true */);
  70312. //this.targetCurve.addPoint(target, index/* , true */)
  70313. let targetSvg = new HandleSvg(target, colors$1.target);
  70314. targetSvg.visible = this.visible;
  70315. this.targets = [...this.targets.slice(0,index), targetSvg, ...this.targets.slice(index,length)];
  70316. if(this.useDurSlice){//不使用全局的duration,而是分段的
  70317. this.durations = [...this.durations.slice(0,index), posInfo.duration, ...this.durations.slice(index,length)];
  70318. }
  70319. this.dispatchEvent({
  70320. type: "controlpoint_added",
  70321. index
  70322. });
  70323. {
  70324. let targetLine = LineDraw.createLine([position,target] ,{mat: getLineMat('aimAtTarget')});
  70325. this.targetLines.children = [...this.targetLines.children.slice(0,index), targetLine, ...this.targetLines.children.slice(index,length)];
  70326. this.targets[index].addEventListener('dragged', (e)=>{
  70327. this.updatePathCallback();
  70328. this.dragPointCallback(e);
  70329. });
  70330. }
  70331. }
  70332. dragPointCallback(e){
  70333. let index = e.index;
  70334. if(e.index == void 0){
  70335. index = this.targets.indexOf(e.target);
  70336. }
  70337. LineDraw.moveLine(this.targetLines.children[index], [this.posCurve.points[index], this.targets[index].position] );
  70338. viewer.dispatchEvent('content_changed');
  70339. this.updateFrustum();
  70340. }
  70341. updatePathCallback(){
  70342. {
  70343. this.quaternions = [];
  70344. let length = this.posCurve.points.length;
  70345. for(let i=0; i<length; i++){
  70346. let quaternion = math.getQuaFromPosAim(this.posCurve.points[i], this.targets[i].position);
  70347. this.quaternions.push( quaternion);
  70348. }
  70349. }
  70350. this.reMapCurvePercent();
  70351. }
  70352. removeControlPoint(index){
  70353. this.posCurve.removePoint(index);
  70354. //this.targetCurve.removePoint(index)
  70355. this.targets[index].dispose();
  70356. this.targets.splice(index, 1);
  70357. this.dispatchEvent({
  70358. type: "controlpoint_removed",
  70359. index
  70360. });
  70361. this.targetLines.remove(this.targetLines.children[index]);
  70362. if(this.useDurSlice){
  70363. this.durations.splice(index, 1);
  70364. }
  70365. }
  70366. createPath(){
  70367. this.posCurve = new CurveCtrl([],getLineMat('position'), colors$1.position, 'posCurve');
  70368. //this.targetCurve = new CurveCtrl([], getLineMat('target'), colors.target, 'targetCurve', {noLine:true});
  70369. this.posCurve.needsPercent = true;
  70370. this.node.add(this.posCurve);
  70371. //this.node.add(this.targetCurve)
  70372. this.posCurve.addEventListener('dragCurvePoint', this.dragPointCallback.bind(this));
  70373. this.posCurve.addEventListener('updatePath', this.updatePathCallback.bind(this));
  70374. }
  70375. createFrustum(){
  70376. const f = 0.3;
  70377. const positions = [
  70378. new Vector3( 0, 0, 0),
  70379. new Vector3(-f, -f, +1),
  70380. new Vector3( 0, 0, 0),
  70381. new Vector3( f, -f, +1),
  70382. new Vector3( 0, 0, 0),
  70383. new Vector3( f, f, +1),
  70384. new Vector3( 0, 0, 0),
  70385. new Vector3(-f, f, +1),
  70386. new Vector3(-f, -f, +1),
  70387. new Vector3( f, -f, +1),
  70388. new Vector3( f, -f, +1),
  70389. new Vector3( f, f, +1),
  70390. new Vector3( f, f, +1),
  70391. new Vector3(-f, f, +1),
  70392. new Vector3(-f, f, +1),
  70393. new Vector3(-f, -f, +1),
  70394. ];
  70395. positions.forEach(e=>e.z *= -1); //因为得到的rotation是camera的,作用在物体上要反向,所以这里反向一下
  70396. //geometry.computeBoundingSphere();//?
  70397. const line = LineDraw.createFatLine( positions, {mat:getLineMat('frustum')});
  70398. //line.scale.set(20, 20, 20);
  70399. line.visible = false;
  70400. return line;
  70401. }
  70402. reMapCurvePercent(){ //因在不同点在相同位置旋转,由于间隔仅和位置距离相关,导致时间间隔为0,采取重新调整间隔的策略。
  70403. var length = this.posCurve.points.length;
  70404. if(length<2){
  70405. return this.newPointsPercents = []
  70406. }
  70407. var newPercents = [0];
  70408. if(this.useDurSlice){ //已经设定好了每一段的duration的话
  70409. let sums = [0];
  70410. let sum = 0, last;
  70411. for(let i=0;i<length-1;i++){ //去掉最后一个duration,因为已到终点
  70412. let duration = this.durations[i];
  70413. sum += duration;
  70414. last = duration;
  70415. sums.push(sum);
  70416. }
  70417. for(let i=1;i<length;i++){
  70418. newPercents.push(sum == 0 ? i/length : sums[i] / sum);
  70419. }
  70420. }else {
  70421. const maxSpaceDur = this.duration / length; //每两点之间修改间隔时间后,最大时间
  70422. const durPerRad = 0.8; //每弧度应该占用的时间
  70423. const minSpaceDur = Math.min(0.8, maxSpaceDur);//每两点之间修改间隔时间后,最小时间
  70424. const maxAngleSpaceDur = MathUtils.clamp(durPerRad * Math.PI, minSpaceDur, maxSpaceDur );// 最大可能差距是180度
  70425. var percents = this.posCurve.pointsPercent;
  70426. for(let i=1;i<length;i++){
  70427. let diff = (percents[i] - percents[i-1]) * this.duration; //间隔时间
  70428. let percent;
  70429. let curMin = minSpaceDur;
  70430. if(diff < maxAngleSpaceDur){ //若小于最大旋转时间
  70431. let rad = this.quaternions[i].angleTo(this.quaternions[i-1]);
  70432. curMin = MathUtils.clamp(rad * durPerRad, minSpaceDur, maxSpaceDur);
  70433. }
  70434. diff = Math.max(diff, curMin);
  70435. percent = newPercents[i-1] + (diff / this.duration); //得到新的percent
  70436. newPercents.push(percent);
  70437. }
  70438. let maxPercent = newPercents[length-1]; //最后一个,若扩充过时间,就会>1
  70439. if( !math.closeTo(maxPercent, 1)){
  70440. let scale = 1 / maxPercent; //需要压缩的比例 <1 这一步会让实际得到的间隔更小
  70441. newPercents = newPercents.map(e=> e*=scale );
  70442. }
  70443. }
  70444. this.newPointsPercents = newPercents;
  70445. //console.log(newPercents)
  70446. }
  70447. at(originPercent, delta, transitionRatio){
  70448. originPercent = MathUtils.clamp(originPercent, 0, 1);
  70449. //修改第一层:起始时间
  70450. let percent = originPercent;
  70451. /* const easePercent = 0.3; //缓动占比 //如果能在所有从静止到运动的中间加缓动就好了呀:lastPos * 0.9 + currentPos * 0.1 ?
  70452. if(originPercent < easePercent){
  70453. console.log('easeIn')
  70454. percent = easing.easeInSine(originPercent, 0, easePercent, easePercent) //currentTime, startY, wholeY, duration 选了一个衔接时接近斜率1的缓动函数
  70455. }else if(originPercent > 1-easePercent){
  70456. console.log('easeOut')
  70457. percent = easing.easeOutSine(originPercent-(1-easePercent), 1-easePercent, easePercent, easePercent)
  70458. } */
  70459. let quaternion;
  70460. if(percent < 1){
  70461. //修改第二层:使用每个点的重定位的 newPointsPercents
  70462. this.currentIndex = this.newPointsPercents.findIndex(e=> e>percent ) - 1;
  70463. //假设每个节点的百分比是精确的,那么:
  70464. let curIndexPercent = this.newPointsPercents[this.currentIndex];
  70465. let nextIndexPercent = this.newPointsPercents[this.currentIndex+1];
  70466. let progress = (percent - curIndexPercent) / (nextIndexPercent - curIndexPercent);//在这两个节点间的百分比
  70467. //投影到原本的 posCurve.pointsPercent上:
  70468. let curIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex];
  70469. let nextIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex+1];
  70470. percent = curIndexOriPercent + (nextIndexOriPercent - curIndexOriPercent) * progress;
  70471. let endQuaternion = this.quaternions[this.currentIndex+1];
  70472. let startQuaternion = this.quaternions[this.currentIndex];
  70473. quaternion = (new Quaternion()).copy(startQuaternion);
  70474. lerp.quaternion(quaternion, endQuaternion)(progress);
  70475. }else {
  70476. this.currentIndex = this.posCurve.points.length - 1;
  70477. quaternion = math.getQuaFromPosAim(this.posCurve.points[this.currentIndex], this.targets[this.currentIndex].position);
  70478. }
  70479. const position = this.posCurve.getPointAt(percent); // 需要this.posCurve.points.length>1 否则报错
  70480. //console.log(this.currentIndex, originPercent)
  70481. //缓动:
  70482. var aimQua, aimPos;
  70483. if(delta != void 0 ){
  70484. if(Potree.settings.tourTestCameraMove){
  70485. aimQua = this.frustum.quaternion.clone();
  70486. aimPos = this.frustum.position.clone();
  70487. }else {
  70488. var camera = viewer.scene.getActiveCamera();
  70489. aimQua = camera.quaternion.clone();
  70490. aimPos = camera.position.clone();
  70491. }
  70492. transitionRatio = transitionRatio || 1 / Potree.settings.cameraAniSmoothRatio;//渐变系数,越小缓动程度越高,越平滑
  70493. transitionRatio *= delta * 60; //假设标准帧率为60fps,当帧率低时(delta大时)要降低缓动
  70494. //console.log(transitionRatio, delta) //画面ui变化会使delta变大
  70495. transitionRatio = MathUtils.clamp(transitionRatio, 0, 1);
  70496. lerp.quaternion(aimQua, quaternion)(transitionRatio); //每次只改变一点点
  70497. lerp.vector(aimPos, position)(transitionRatio);
  70498. }else {
  70499. aimQua = quaternion; aimPos = position;
  70500. }
  70501. let rotation = new Euler().setFromQuaternion(aimQua );
  70502. const frame = {
  70503. position: aimPos,
  70504. rotation
  70505. };
  70506. return frame;
  70507. }
  70508. set(percent){
  70509. this.percent = percent;
  70510. }
  70511. setVisible(visible){
  70512. this.node.visible = visible;
  70513. this.posCurve.visible = visible;
  70514. this.targets.forEach(e=>e.visible = visible );
  70515. this.visible = visible;
  70516. }
  70517. setDuration(duration){
  70518. if(duration != this.duration){
  70519. this.duration = duration;
  70520. if(this.quaternions.length == this.posCurve.points.length)this.reMapCurvePercent();
  70521. }
  70522. }
  70523. getDuration(duration){
  70524. return this.duration;
  70525. }
  70526. play(startOptions={}){
  70527. if(this.onUpdate){
  70528. return console.error('已经开始播放')
  70529. }
  70530. let startPercent = 0, currentIndex = 0;
  70531. if(startOptions.percent != void 0 ){
  70532. startPercent = startOptions.percent;
  70533. }else if(startOptions.index){
  70534. currentIndex = index;
  70535. //startPercent = index/(this.posCurve.points.length-1)
  70536. startPercent = this.posCurve.pointsPercent[index];
  70537. }
  70538. //const tStart = performance.now();
  70539. const duration = this.duration;
  70540. this.originalyVisible = this.visible;
  70541. Potree.settings.tourTestCameraMove || this.setVisible(false);
  70542. let tStart, startTransitionRatio = 0.2;
  70543. let startDelay = 1/startTransitionRatio / 20 ;//因为缓动所以延迟开始,前面前都是at(0),使过渡到开始点位(但是依旧不能准确停在起始点,因为缓动是乘百分比有残留。所以直接平滑衔接到开始后的位置)
  70544. let hasPlayedTime = 0;
  70545. let finishDelay = Potree.settings.cameraAniSmoothRatio / 60 * 3;//结束后还需要多久时间才能大致达到缓动的最终目标
  70546. let hasStoppedTime = 0;
  70547. this.onUpdate = (e) => {
  70548. if(this.posCurve.points.length<2){
  70549. if(this.posCurve.points.length == 1){
  70550. viewer.scene.view.position.copy(this.posCurve.points[0]);
  70551. viewer.scene.view.rotation = new Euler().setFromQuaternion(this.quaternions[0]);
  70552. }
  70553. this.pause();
  70554. return
  70555. }
  70556. let percent, transitionRatio;
  70557. if(tStart){
  70558. let tNow = performance.now();
  70559. let elapsed = (tNow - tStart) / 1000;
  70560. percent = elapsed / duration + startPercent;
  70561. }else {//从当前位置过渡到开始位置
  70562. percent = 0;
  70563. hasPlayedTime += e.delta;
  70564. transitionRatio = startTransitionRatio;
  70565. //console.log('延迟开始')
  70566. if(hasPlayedTime > startDelay){
  70567. tStart = performance.now();
  70568. }
  70569. }
  70570. this.set(percent);
  70571. const frame = this.at(percent, e.delta, transitionRatio);
  70572. if(currentIndex != this.currentIndex){
  70573. currentIndex = this.currentIndex;
  70574. console.log('updateCurrentIndex', currentIndex);
  70575. this.dispatchEvent({type:'updateCurrentIndex', currentIndex });
  70576. }
  70577. if(!Potree.settings.tourTestCameraMove){
  70578. viewer.scene.view.position.copy(frame.position);
  70579. //viewer.scene.view.lookAt(frame.target);
  70580. viewer.scene.view.rotation = frame.rotation;
  70581. }
  70582. this.updateFrustum(frame);
  70583. if(percent >= 1){
  70584. if(hasStoppedTime > finishDelay){
  70585. this.pause();
  70586. }else {
  70587. hasStoppedTime += e.delta;
  70588. //console.log('延迟结束')
  70589. }
  70590. }
  70591. };
  70592. this.viewer.addEventListener("update", this.onUpdate);
  70593. }
  70594. pause(){
  70595. this.setVisible(this.originalyVisible);
  70596. this.viewer.removeEventListener("update", this.onUpdate);
  70597. this.dispatchEvent('playDone');
  70598. this.onUpdate = null;
  70599. }
  70600. updateFrustum(frame){
  70601. const frustum = this.frustum;
  70602. if(this.posCurve.points.length>1){
  70603. frustum.visible = true;
  70604. }else {
  70605. frustum.visible = false;
  70606. return
  70607. }
  70608. frame = frame || this.at(this.percent);
  70609. frustum.position.copy(frame.position);
  70610. //frustum.lookAt(...frame.target.toArray());
  70611. frustum.rotation.copy(frame.rotation);
  70612. }
  70613. changeCallback(){
  70614. this.posCurve.update();
  70615. //this.targetCurve.update()
  70616. this.targets.forEach(e=>e.update());
  70617. this.updateFrustum();
  70618. }
  70619. dispose(){//add
  70620. this.posCurve.dispose();
  70621. //this.targetCurve.dispatchEvent({type:'dispose'})
  70622. this.targets.forEach(e=>e.dispose());
  70623. this.durations = [];
  70624. this.node.parent.remove(this.node);
  70625. }
  70626. }
  70627. //scene.removeCameraAnimation
  70628. //修改:不使用targetCurve作为target曲线,因为播放时posCuve的节点和targetCurve并没有对应,且使用target的曲线会使角度变化大的情况过渡生硬。
  70629. // 改完旋转了。但是位置也有问题。速度完全和路程相关,当在同一位置设置多点时,这段的总时长为0. (是否要设置最小时长?不过也做不到 - -)
  70630. class MeasurePanel{
  70631. constructor(viewer, measurement, propertiesPanel){
  70632. this.viewer = viewer;
  70633. this.measurement = measurement;
  70634. this.propertiesPanel = propertiesPanel;
  70635. this._update = () => { this.update(); };
  70636. }
  70637. createCoordinatesTable(points){
  70638. let table = $(`
  70639. <table class="measurement_value_table">
  70640. <tr>
  70641. <th>x</th>
  70642. <th>y</th>
  70643. <th>z</th>
  70644. <th></th>
  70645. </tr>
  70646. </table>
  70647. `);
  70648. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  70649. for (let point of points) {
  70650. let x = Utils.addCommas(point.x.toFixed(3));
  70651. let y = Utils.addCommas(point.y.toFixed(3));
  70652. let z = Utils.addCommas(point.z.toFixed(3));
  70653. let row = $(`
  70654. <tr>
  70655. <td><span>${x}</span></td>
  70656. <td><span>${y}</span></td>
  70657. <td><span>${z}</span></td>
  70658. <td align="right" style="width: 25%">
  70659. <img name="copy" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  70660. </td>
  70661. </tr>
  70662. `);
  70663. this.elCopy = row.find("img[name=copy]");
  70664. this.elCopy.click( () => {
  70665. let msg = point.toArray().map(c => c.toFixed(3)).join(", ");
  70666. Utils.clipboardCopy(msg);
  70667. this.viewer.postMessage(
  70668. `Copied value to clipboard: <br>'${msg}'`,
  70669. {duration: 3000});
  70670. });
  70671. table.append(row);
  70672. }
  70673. return table;
  70674. };
  70675. createAttributesTable(){
  70676. let elTable = $('<table class="measurement_value_table"></table>');
  70677. let point = this.measurement.points[0];
  70678. /* for(let attributeName of Object.keys(point)){
  70679. if(attributeName === "position"){
  70680. }else if(attributeName === "rgba"){
  70681. let color = point.rgba;
  70682. let text = color.join(', ');
  70683. elTable.append($(`
  70684. <tr>
  70685. <td>rgb</td>
  70686. <td>${text}</td>
  70687. </tr>
  70688. `));
  70689. }else{
  70690. let value = point[attributeName];
  70691. let text = value.join(', ');
  70692. elTable.append($(`
  70693. <tr>
  70694. <td>${attributeName}</td>
  70695. <td>${text}</td>
  70696. </tr>
  70697. `));
  70698. }
  70699. } */
  70700. return elTable;
  70701. }
  70702. update(){
  70703. }
  70704. };
  70705. class DistancePanel extends MeasurePanel{
  70706. constructor(viewer, measurement, propertiesPanel){
  70707. super(viewer, measurement, propertiesPanel);
  70708. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  70709. this.elContent = $(`
  70710. <div class="measurement_content selectable">
  70711. <span class="coordinates_table_container"></span>
  70712. <br>
  70713. <table id="distances_table" class="measurement_value_table"></table>
  70714. <!-- ACTIONS -->
  70715. <div style="display: flex; margin-top: 12px">
  70716. <span>
  70717. <input type="button" name="make_profile" value="profile from measure" />
  70718. </span>
  70719. <span style="flex-grow: 1"></span>
  70720. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  70721. </div>
  70722. </div>
  70723. `);
  70724. this.elRemove = this.elContent.find("img[name=remove]");
  70725. this.elRemove.click( () => {
  70726. this.viewer.scene.removeMeasurement(measurement);
  70727. });
  70728. this.elMakeProfile = this.elContent.find("input[name=make_profile]");
  70729. this.elMakeProfile.click( () => {
  70730. //measurement.points;
  70731. const profile = new Profile();
  70732. profile.name = measurement.name;
  70733. profile.width = measurement.getTotalDistance() / 50;
  70734. for(const point of measurement.points){
  70735. profile.addMarker(point.position.clone());
  70736. }
  70737. this.viewer.scene.addProfile(profile);
  70738. });
  70739. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  70740. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  70741. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  70742. this.update();
  70743. }
  70744. update(){
  70745. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  70746. elCoordiantesContainer.empty();
  70747. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  70748. let positions = this.measurement.points.map(p => p.position);
  70749. let distances = [];
  70750. for (let i = 0; i < positions.length - 1; i++) {
  70751. let d = positions[i].distanceTo(positions[i + 1]);
  70752. distances.push(d.toFixed(3));
  70753. }
  70754. let totalDistance = this.measurement.getTotalDistance().toFixed(3);
  70755. let elDistanceTable = this.elContent.find(`#distances_table`);
  70756. elDistanceTable.empty();
  70757. for (let i = 0; i < distances.length; i++) {
  70758. let label = (i === 0) ? 'Distances: ' : '';
  70759. let distance = distances[i];
  70760. let elDistance = $(`
  70761. <tr>
  70762. <th>${label}</th>
  70763. <td style="width: 100%; padding-left: 10px">${distance}</td>
  70764. </tr>`);
  70765. elDistanceTable.append(elDistance);
  70766. }
  70767. let elTotal = $(`
  70768. <tr>
  70769. <th>Total: </td><td style="width: 100%; padding-left: 10px">${totalDistance}</th>
  70770. </tr>`);
  70771. elDistanceTable.append(elTotal);
  70772. }
  70773. };
  70774. class PointPanel extends MeasurePanel{
  70775. constructor(viewer, measurement, propertiesPanel){
  70776. super(viewer, measurement, propertiesPanel);
  70777. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  70778. this.elContent = $(`
  70779. <div class="measurement_content selectable">
  70780. <span class="coordinates_table_container"></span>
  70781. <br>
  70782. <span class="attributes_table_container"></span>
  70783. <!-- ACTIONS -->
  70784. <div style="display: flex; margin-top: 12px">
  70785. <span></span>
  70786. <span style="flex-grow: 1"></span>
  70787. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  70788. </div>
  70789. </div>
  70790. `);
  70791. this.elRemove = this.elContent.find("img[name=remove]");
  70792. this.elRemove.click( () => {
  70793. this.viewer.scene.removeMeasurement(measurement);
  70794. });
  70795. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  70796. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  70797. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  70798. this.update();
  70799. }
  70800. update(){
  70801. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  70802. elCoordiantesContainer.empty();
  70803. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  70804. let elAttributesContainer = this.elContent.find('.attributes_table_container');
  70805. elAttributesContainer.empty();
  70806. elAttributesContainer.append(this.createAttributesTable());
  70807. }
  70808. };
  70809. class AreaPanel extends MeasurePanel{
  70810. constructor(viewer, measurement, propertiesPanel){
  70811. super(viewer, measurement, propertiesPanel);
  70812. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  70813. this.elContent = $(`
  70814. <div class="measurement_content selectable">
  70815. <span class="coordinates_table_container"></span>
  70816. <br>
  70817. <span style="font-weight: bold">Area: </span>
  70818. <span id="measurement_area"></span>
  70819. <!-- ACTIONS -->
  70820. <div style="display: flex; margin-top: 12px">
  70821. <span></span>
  70822. <span style="flex-grow: 1"></span>
  70823. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  70824. </div>
  70825. </div>
  70826. `);
  70827. this.elRemove = this.elContent.find("img[name=remove]");
  70828. this.elRemove.click( () => {
  70829. this.viewer.scene.removeMeasurement(measurement);
  70830. });
  70831. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  70832. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  70833. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  70834. this.update();
  70835. }
  70836. update(){
  70837. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  70838. elCoordiantesContainer.empty();
  70839. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  70840. let elArea = this.elContent.find(`#measurement_area`);
  70841. elArea.html(this.measurement.area.value.toFixed(3));
  70842. }
  70843. };
  70844. class AnglePanel extends MeasurePanel{
  70845. constructor(viewer, measurement, propertiesPanel){
  70846. super(viewer, measurement, propertiesPanel);
  70847. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  70848. this.elContent = $(`
  70849. <div class="measurement_content selectable">
  70850. <span class="coordinates_table_container"></span>
  70851. <br>
  70852. <table class="measurement_value_table">
  70853. <tr>
  70854. <th>\u03b1</th>
  70855. <th>\u03b2</th>
  70856. <th>\u03b3</th>
  70857. </tr>
  70858. <tr>
  70859. <td align="center" id="angle_cell_alpha" style="width: 33%"></td>
  70860. <td align="center" id="angle_cell_betta" style="width: 33%"></td>
  70861. <td align="center" id="angle_cell_gamma" style="width: 33%"></td>
  70862. </tr>
  70863. </table>
  70864. <!-- ACTIONS -->
  70865. <div style="display: flex; margin-top: 12px">
  70866. <span></span>
  70867. <span style="flex-grow: 1"></span>
  70868. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  70869. </div>
  70870. </div>
  70871. `);
  70872. this.elRemove = this.elContent.find("img[name=remove]");
  70873. this.elRemove.click( () => {
  70874. this.viewer.scene.removeMeasurement(measurement);
  70875. });
  70876. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  70877. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  70878. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  70879. this.update();
  70880. }
  70881. update(){
  70882. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  70883. elCoordiantesContainer.empty();
  70884. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  70885. let angles = [];
  70886. for(let i = 0; i < this.measurement.points.length; i++){
  70887. angles.push(this.measurement.getAngle(i) * (180.0 / Math.PI));
  70888. }
  70889. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  70890. let elAlpha = this.elContent.find(`#angle_cell_alpha`);
  70891. let elBetta = this.elContent.find(`#angle_cell_betta`);
  70892. let elGamma = this.elContent.find(`#angle_cell_gamma`);
  70893. elAlpha.html(angles[0]);
  70894. elBetta.html(angles[1]);
  70895. elGamma.html(angles[2]);
  70896. }
  70897. };
  70898. class CirclePanel extends MeasurePanel{
  70899. constructor(viewer, measurement, propertiesPanel){
  70900. super(viewer, measurement, propertiesPanel);
  70901. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  70902. this.elContent = $(`
  70903. <div class="measurement_content selectable">
  70904. <span class="coordinates_table_container"></span>
  70905. <br>
  70906. <table id="infos_table" class="measurement_value_table"></table>
  70907. <!-- ACTIONS -->
  70908. <div style="display: flex; margin-top: 12px">
  70909. <span></span>
  70910. <span style="flex-grow: 1"></span>
  70911. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  70912. </div>
  70913. </div>
  70914. `);
  70915. this.elRemove = this.elContent.find("img[name=remove]");
  70916. this.elRemove.click( () => {
  70917. this.viewer.scene.removeMeasurement(measurement);
  70918. });
  70919. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  70920. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  70921. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  70922. this.update();
  70923. }
  70924. update(){
  70925. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  70926. elCoordiantesContainer.empty();
  70927. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  70928. const elInfos = this.elContent.find(`#infos_table`);
  70929. if(this.measurement.points.length !== 3){
  70930. elInfos.empty();
  70931. return;
  70932. }
  70933. const A = this.measurement.points[0].position;
  70934. const B = this.measurement.points[1].position;
  70935. const C = this.measurement.points[2].position;
  70936. const center = Potree.Utils.computeCircleCenter(A, B, C);
  70937. const radius = center.distanceTo(A);
  70938. const circumference = 2 * Math.PI * radius;
  70939. const format = (number) => {
  70940. return Potree.Utils.addCommas(number.toFixed(3));
  70941. };
  70942. const txtCenter = `${format(center.x)} ${format(center.y)} ${format(center.z)}`;
  70943. const txtRadius = format(radius);
  70944. const txtCircumference = format(circumference);
  70945. const thStyle = `style="text-align: left"`;
  70946. const tdStyle = `style="width: 100%; padding: 5px;"`;
  70947. elInfos.html(`
  70948. <tr>
  70949. <th ${thStyle}>Center: </th>
  70950. <td ${tdStyle}></td>
  70951. </tr>
  70952. <tr>
  70953. <td ${tdStyle} colspan="2">
  70954. ${txtCenter}
  70955. </td>
  70956. </tr>
  70957. <tr>
  70958. <th ${thStyle}>Radius: </th>
  70959. <td ${tdStyle}>${txtRadius}</td>
  70960. </tr>
  70961. <tr>
  70962. <th ${thStyle}>Circumference: </th>
  70963. <td ${tdStyle}>${txtCircumference}</td>
  70964. </tr>
  70965. `);
  70966. }
  70967. };
  70968. class HeightPanel extends MeasurePanel{
  70969. constructor(viewer, measurement, propertiesPanel){
  70970. super(viewer, measurement, propertiesPanel);
  70971. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  70972. this.elContent = $(`
  70973. <div class="measurement_content selectable">
  70974. <span class="coordinates_table_container"></span>
  70975. <br>
  70976. <span id="height_label">Height: </span><br>
  70977. <!-- ACTIONS -->
  70978. <div style="display: flex; margin-top: 12px">
  70979. <span></span>
  70980. <span style="flex-grow: 1"></span>
  70981. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  70982. </div>
  70983. </div>
  70984. `);
  70985. this.elRemove = this.elContent.find("img[name=remove]");
  70986. this.elRemove.click( () => {
  70987. this.viewer.scene.removeMeasurement(measurement);
  70988. });
  70989. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  70990. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  70991. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  70992. this.update();
  70993. }
  70994. update(){
  70995. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  70996. elCoordiantesContainer.empty();
  70997. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  70998. {
  70999. let points = this.measurement.points;
  71000. let sorted = points.slice().sort((a, b) => a.position.z - b.position.z);
  71001. let lowPoint = sorted[0].position.clone();
  71002. let highPoint = sorted[sorted.length - 1].position.clone();
  71003. let min = lowPoint.z;
  71004. let max = highPoint.z;
  71005. let height = max - min;
  71006. height = height.toFixed(3);
  71007. this.elHeightLabel = this.elContent.find(`#height_label`);
  71008. this.elHeightLabel.html(`<b>Height:</b> ${height}`);
  71009. }
  71010. }
  71011. };
  71012. class VolumePanel extends MeasurePanel{
  71013. constructor(viewer, measurement, propertiesPanel){
  71014. super(viewer, measurement, propertiesPanel);
  71015. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  71016. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  71017. let lblLengthText = new Map([
  71018. [BoxVolume, "length"],
  71019. [SphereVolume$1, "rx"],
  71020. ]).get(measurement.constructor);
  71021. let lblWidthText = new Map([
  71022. [BoxVolume, "width"],
  71023. [SphereVolume$1, "ry"],
  71024. ]).get(measurement.constructor);
  71025. let lblHeightText = new Map([
  71026. [BoxVolume, "height"],
  71027. [SphereVolume$1, "rz"],
  71028. ]).get(measurement.constructor);
  71029. this.elContent = $(`
  71030. <div class="measurement_content selectable">
  71031. <span class="coordinates_table_container"></span>
  71032. <table class="measurement_value_table">
  71033. <tr>
  71034. <th>\u03b1</th>
  71035. <th>\u03b2</th>
  71036. <th>\u03b3</th>
  71037. <th></th>
  71038. </tr>
  71039. <tr>
  71040. <td align="center" id="angle_cell_alpha" style="width: 33%"></td>
  71041. <td align="center" id="angle_cell_betta" style="width: 33%"></td>
  71042. <td align="center" id="angle_cell_gamma" style="width: 33%"></td>
  71043. <td align="right" style="width: 25%">
  71044. <img name="copyRotation" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  71045. </td>
  71046. </tr>
  71047. </table>
  71048. <table class="measurement_value_table">
  71049. <tr>
  71050. <th>${lblLengthText}</th>
  71051. <th>${lblWidthText}</th>
  71052. <th>${lblHeightText}</th>
  71053. <th></th>
  71054. </tr>
  71055. <tr>
  71056. <td align="center" id="cell_length" style="width: 33%"></td>
  71057. <td align="center" id="cell_width" style="width: 33%"></td>
  71058. <td align="center" id="cell_height" style="width: 33%"></td>
  71059. <td align="right" style="width: 25%">
  71060. <img name="copyScale" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  71061. </td>
  71062. </tr>
  71063. </table>
  71064. <br>
  71065. <span style="font-weight: bold">Volume: </span>
  71066. <span id="measurement_volume"></span>
  71067. <!--
  71068. <li>
  71069. <label style="whitespace: nowrap">
  71070. <input id="volume_show" type="checkbox"/>
  71071. <span>show volume</span>
  71072. </label>
  71073. </li>-->
  71074. <li>
  71075. <label style="whitespace: nowrap">
  71076. <input id="volume_clip" type="checkbox"/>
  71077. <span>make clip volume</span>
  71078. </label>
  71079. </li>
  71080. <li style="margin-top: 10px">
  71081. <input name="download_volume" type="button" value="prepare download" style="width: 100%" />
  71082. <div name="download_message"></div>
  71083. </li>
  71084. <!-- ACTIONS -->
  71085. <li style="display: grid; grid-template-columns: auto auto; grid-column-gap: 5px; margin-top: 10px">
  71086. <input id="volume_reset_orientation" type="button" value="reset orientation"/>
  71087. <input id="volume_make_uniform" type="button" value="make uniform"/>
  71088. </li>
  71089. <div style="display: flex; margin-top: 12px">
  71090. <span></span>
  71091. <span style="flex-grow: 1"></span>
  71092. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  71093. </div>
  71094. </div>
  71095. `);
  71096. { // download
  71097. this.elDownloadButton = this.elContent.find("input[name=download_volume]");
  71098. if(this.propertiesPanel.viewer.server){
  71099. this.elDownloadButton.click(() => this.download());
  71100. } else {
  71101. this.elDownloadButton.hide();
  71102. }
  71103. }
  71104. this.elCopyRotation = this.elContent.find("img[name=copyRotation]");
  71105. this.elCopyRotation.click( () => {
  71106. let rotation = this.measurement.rotation.toArray().slice(0, 3);
  71107. let msg = rotation.map(c => c.toFixed(3)).join(", ");
  71108. Utils.clipboardCopy(msg);
  71109. this.viewer.postMessage(
  71110. `Copied value to clipboard: <br>'${msg}'`,
  71111. {duration: 3000});
  71112. });
  71113. this.elCopyScale = this.elContent.find("img[name=copyScale]");
  71114. this.elCopyScale.click( () => {
  71115. let scale = this.measurement.scale.toArray();
  71116. let msg = scale.map(c => c.toFixed(3)).join(", ");
  71117. Utils.clipboardCopy(msg);
  71118. this.viewer.postMessage(
  71119. `Copied value to clipboard: <br>'${msg}'`,
  71120. {duration: 3000});
  71121. });
  71122. this.elRemove = this.elContent.find("img[name=remove]");
  71123. this.elRemove.click( () => {
  71124. this.viewer.scene.removeVolume(measurement);
  71125. });
  71126. this.elContent.find("#volume_reset_orientation").click(() => {
  71127. measurement.rotation.set(0, 0, 0);
  71128. });
  71129. this.elContent.find("#volume_make_uniform").click(() => {
  71130. let mean = (measurement.scale.x + measurement.scale.y + measurement.scale.z) / 3;
  71131. measurement.scale.set(mean, mean, mean);
  71132. });
  71133. this.elCheckClip = this.elContent.find('#volume_clip');
  71134. this.elCheckClip.click(event => {
  71135. this.measurement.clip = event.target.checked;
  71136. });
  71137. this.elCheckShow = this.elContent.find('#volume_show');
  71138. this.elCheckShow.click(event => {
  71139. this.measurement.visible = event.target.checked;
  71140. });
  71141. this.propertiesPanel.addVolatileListener(measurement, "position_changed", this._update);
  71142. this.propertiesPanel.addVolatileListener(measurement, "orientation_changed", this._update);
  71143. this.propertiesPanel.addVolatileListener(measurement, "scale_changed", this._update);
  71144. this.propertiesPanel.addVolatileListener(measurement, "clip_changed", this._update);
  71145. this.update();
  71146. }
  71147. async download(){
  71148. let clipBox = this.measurement;
  71149. let regions = [];
  71150. //for(let clipBox of boxes){
  71151. {
  71152. let toClip = clipBox.matrixWorld;
  71153. let px = new Vector3(+0.5, 0, 0).applyMatrix4(toClip);
  71154. let nx = new Vector3(-0.5, 0, 0).applyMatrix4(toClip);
  71155. let py = new Vector3(0, +0.5, 0).applyMatrix4(toClip);
  71156. let ny = new Vector3(0, -0.5, 0).applyMatrix4(toClip);
  71157. let pz = new Vector3(0, 0, +0.5).applyMatrix4(toClip);
  71158. let nz = new Vector3(0, 0, -0.5).applyMatrix4(toClip);
  71159. let pxN = new Vector3().subVectors(nx, px).normalize();
  71160. let nxN = pxN.clone().multiplyScalar(-1);
  71161. let pyN = new Vector3().subVectors(ny, py).normalize();
  71162. let nyN = pyN.clone().multiplyScalar(-1);
  71163. let pzN = new Vector3().subVectors(nz, pz).normalize();
  71164. let nzN = pzN.clone().multiplyScalar(-1);
  71165. let planes = [
  71166. new Plane().setFromNormalAndCoplanarPoint(pxN, px),
  71167. new Plane().setFromNormalAndCoplanarPoint(nxN, nx),
  71168. new Plane().setFromNormalAndCoplanarPoint(pyN, py),
  71169. new Plane().setFromNormalAndCoplanarPoint(nyN, ny),
  71170. new Plane().setFromNormalAndCoplanarPoint(pzN, pz),
  71171. new Plane().setFromNormalAndCoplanarPoint(nzN, nz),
  71172. ];
  71173. let planeQueryParts = [];
  71174. for(let plane of planes){
  71175. let part = [plane.normal.toArray(), plane.constant].join(",");
  71176. part = `[${part}]`;
  71177. planeQueryParts.push(part);
  71178. }
  71179. let region = "[" + planeQueryParts.join(",") + "]";
  71180. regions.push(region);
  71181. }
  71182. let regionsArg = regions.join(",");
  71183. let pointcloudArgs = [];
  71184. for(let pointcloud of this.viewer.scene.pointclouds){
  71185. if(!pointcloud.visible){
  71186. continue;
  71187. }
  71188. let offset = pointcloud.pcoGeometry.offset.clone();
  71189. let negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  71190. let matrixWorld = pointcloud.matrixWorld;
  71191. let transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  71192. let path = `${window.location.pathname}/../${pointcloud.pcoGeometry.url}`;
  71193. let arg = {
  71194. path: path,
  71195. transform: transform.elements,
  71196. };
  71197. let argString = JSON.stringify(arg);
  71198. pointcloudArgs.push(argString);
  71199. }
  71200. let pointcloudsArg = pointcloudArgs.join(",");
  71201. let elMessage = this.elContent.find("div[name=download_message]");
  71202. let error = (message) => {
  71203. elMessage.html(`<div style="color: #ff0000">ERROR: ${message}</div>`);
  71204. };
  71205. let info = (message) => {
  71206. elMessage.html(`${message}`);
  71207. };
  71208. let handle = null;
  71209. { // START FILTER
  71210. let url = `${viewer.server}/create_regions_filter?pointclouds=[${pointcloudsArg}]&regions=[${regionsArg}]`;
  71211. //console.log(url);
  71212. info("estimating results ...");
  71213. let response = await fetch(url);
  71214. let jsResponse = await response.json();
  71215. //console.log(jsResponse);
  71216. if(!jsResponse.handle){
  71217. error(jsResponse.message);
  71218. return;
  71219. }else {
  71220. handle = jsResponse.handle;
  71221. }
  71222. }
  71223. { // WAIT, CHECK PROGRESS, HANDLE FINISH
  71224. let url = `${viewer.server}/check_regions_filter?handle=${handle}`;
  71225. let sleep = (function(duration){
  71226. return new Promise( (res, rej) => {
  71227. setTimeout(() => {
  71228. res();
  71229. }, duration);
  71230. });
  71231. });
  71232. let handleFiltering = (jsResponse) => {
  71233. let {progress, estimate} = jsResponse;
  71234. let progressFract = progress["processed points"] / estimate.points;
  71235. let progressPercents = parseInt(progressFract * 100);
  71236. info(`progress: ${progressPercents}%`);
  71237. };
  71238. let handleFinish = (jsResponse) => {
  71239. let message = "downloads ready: <br>";
  71240. message += "<ul>";
  71241. for(let i = 0; i < jsResponse.pointclouds.length; i++){
  71242. let url = `${viewer.server}/download_regions_filter_result?handle=${handle}&index=${i}`;
  71243. message += `<li><a href="${url}">result_${i}.las</a> </li>\n`;
  71244. }
  71245. let reportURL = `${viewer.server}/download_regions_filter_report?handle=${handle}`;
  71246. message += `<li> <a href="${reportURL}">report.json</a> </li>\n`;
  71247. message += "</ul>";
  71248. info(message);
  71249. };
  71250. let handleUnexpected = (jsResponse) => {
  71251. let message = `Unexpected Response. <br>status: ${jsResponse.status} <br>message: ${jsResponse.message}`;
  71252. info(message);
  71253. };
  71254. let handleError = (jsResponse) => {
  71255. let message = `ERROR: ${jsResponse.message}`;
  71256. error(message);
  71257. throw new Error(message);
  71258. };
  71259. let start = Date.now();
  71260. while(true){
  71261. let response = await fetch(url);
  71262. let jsResponse = await response.json();
  71263. if(jsResponse.status === "ERROR"){
  71264. handleError(jsResponse);
  71265. }else if(jsResponse.status === "FILTERING"){
  71266. handleFiltering(jsResponse);
  71267. }else if(jsResponse.status === "FINISHED"){
  71268. handleFinish(jsResponse);
  71269. break;
  71270. }else {
  71271. handleUnexpected(jsResponse);
  71272. }
  71273. let durationS = (Date.now() - start) / 1000;
  71274. let sleepAmountMS = durationS < 10 ? 100 : 1000;
  71275. await sleep(sleepAmountMS);
  71276. }
  71277. }
  71278. }
  71279. update(){
  71280. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  71281. elCoordiantesContainer.empty();
  71282. elCoordiantesContainer.append(this.createCoordinatesTable([this.measurement.position]));
  71283. {
  71284. let angles = this.measurement.rotation.toVector3();
  71285. angles = angles.toArray();
  71286. //angles = [angles.z, angles.x, angles.y];
  71287. angles = angles.map(v => 180 * v / Math.PI);
  71288. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  71289. let elAlpha = this.elContent.find(`#angle_cell_alpha`);
  71290. let elBetta = this.elContent.find(`#angle_cell_betta`);
  71291. let elGamma = this.elContent.find(`#angle_cell_gamma`);
  71292. elAlpha.html(angles[0]);
  71293. elBetta.html(angles[1]);
  71294. elGamma.html(angles[2]);
  71295. }
  71296. {
  71297. let dimensions = this.measurement.scale.toArray();
  71298. dimensions = dimensions.map(v => Utils.addCommas(v.toFixed(2)));
  71299. let elLength = this.elContent.find(`#cell_length`);
  71300. let elWidth = this.elContent.find(`#cell_width`);
  71301. let elHeight = this.elContent.find(`#cell_height`);
  71302. elLength.html(dimensions[0]);
  71303. elWidth.html(dimensions[1]);
  71304. elHeight.html(dimensions[2]);
  71305. }
  71306. {
  71307. let elVolume = this.elContent.find(`#measurement_volume`);
  71308. let volume = this.measurement.getVolume();
  71309. elVolume.html(Utils.addCommas(volume.toFixed(2)));
  71310. }
  71311. this.elCheckClip.prop("checked", this.measurement.clip);
  71312. this.elCheckShow.prop("checked", this.measurement.visible);
  71313. }
  71314. };
  71315. class ProfilePanel extends MeasurePanel{
  71316. constructor(viewer, measurement, propertiesPanel){
  71317. super(viewer, measurement, propertiesPanel);
  71318. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  71319. this.elContent = $(`
  71320. <div class="measurement_content selectable">
  71321. <span class="coordinates_table_container"></span>
  71322. <br>
  71323. <span style="display:flex">
  71324. <span style="display:flex; align-items: center; padding-right: 10px">Width: </span>
  71325. <input id="sldProfileWidth" name="sldProfileWidth" value="5.06" style="flex-grow: 1; width:100%">
  71326. </span>
  71327. <br>
  71328. <li style="margin-top: 10px">
  71329. <input name="download_profile" type="button" value="prepare download" style="width: 100%" />
  71330. <div name="download_message"></div>
  71331. </li>
  71332. <br>
  71333. <input type="button" id="show_2d_profile" value="show 2d profile" style="width: 100%"/>
  71334. <!-- ACTIONS -->
  71335. <div style="display: flex; margin-top: 12px">
  71336. <span></span>
  71337. <span style="flex-grow: 1"></span>
  71338. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  71339. </div>
  71340. </div>
  71341. `);
  71342. this.elRemove = this.elContent.find("img[name=remove]");
  71343. this.elRemove.click( () => {
  71344. this.viewer.scene.removeProfile(measurement);
  71345. });
  71346. { // download
  71347. this.elDownloadButton = this.elContent.find(`input[name=download_profile]`);
  71348. if(this.propertiesPanel.viewer.server){
  71349. this.elDownloadButton.click(() => this.download());
  71350. } else {
  71351. this.elDownloadButton.hide();
  71352. }
  71353. }
  71354. { // width spinner
  71355. let elWidthSlider = this.elContent.find(`#sldProfileWidth`);
  71356. elWidthSlider.spinner({
  71357. min: 0, max: 10 * 1000 * 1000, step: 0.01,
  71358. numberFormat: 'n',
  71359. start: () => {},
  71360. spin: (event, ui) => {
  71361. let value = elWidthSlider.spinner('value');
  71362. measurement.setWidth(value);
  71363. },
  71364. change: (event, ui) => {
  71365. let value = elWidthSlider.spinner('value');
  71366. measurement.setWidth(value);
  71367. },
  71368. stop: (event, ui) => {
  71369. let value = elWidthSlider.spinner('value');
  71370. measurement.setWidth(value);
  71371. },
  71372. incremental: (count) => {
  71373. let value = elWidthSlider.spinner('value');
  71374. let step = elWidthSlider.spinner('option', 'step');
  71375. let delta = value * 0.05;
  71376. let increments = Math.max(1, parseInt(delta / step));
  71377. return increments;
  71378. }
  71379. });
  71380. elWidthSlider.spinner('value', measurement.getWidth());
  71381. elWidthSlider.spinner('widget').css('width', '100%');
  71382. let widthListener = (event) => {
  71383. let value = elWidthSlider.spinner('value');
  71384. if (value !== measurement.getWidth()) {
  71385. elWidthSlider.spinner('value', measurement.getWidth());
  71386. }
  71387. };
  71388. this.propertiesPanel.addVolatileListener(measurement, "width_changed", widthListener);
  71389. }
  71390. let elShow2DProfile = this.elContent.find(`#show_2d_profile`);
  71391. elShow2DProfile.click(() => {
  71392. this.propertiesPanel.viewer.profileWindow.show();
  71393. this.propertiesPanel.viewer.profileWindowController.setProfile(measurement);
  71394. });
  71395. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  71396. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  71397. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  71398. this.update();
  71399. }
  71400. update(){
  71401. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  71402. elCoordiantesContainer.empty();
  71403. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  71404. }
  71405. async download(){
  71406. let profile = this.measurement;
  71407. let regions = [];
  71408. {
  71409. let segments = profile.getSegments();
  71410. let width = profile.width;
  71411. for(let segment of segments){
  71412. let start = segment.start.clone().multiply(new Vector3(1, 1, 0));
  71413. let end = segment.end.clone().multiply(new Vector3(1, 1, 0));
  71414. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  71415. let startEndDir = new Vector3().subVectors(end, start).normalize();
  71416. let endStartDir = new Vector3().subVectors(start, end).normalize();
  71417. let upDir = new Vector3(0, 0, 1);
  71418. let rightDir = new Vector3().crossVectors(startEndDir, upDir);
  71419. let leftDir = new Vector3().crossVectors(endStartDir, upDir);
  71420. console.log(leftDir);
  71421. let right = rightDir.clone().multiplyScalar(width * 0.5).add(center);
  71422. let left = leftDir.clone().multiplyScalar(width * 0.5).add(center);
  71423. let planes = [
  71424. new Plane().setFromNormalAndCoplanarPoint(startEndDir, start),
  71425. new Plane().setFromNormalAndCoplanarPoint(endStartDir, end),
  71426. new Plane().setFromNormalAndCoplanarPoint(leftDir, right),
  71427. new Plane().setFromNormalAndCoplanarPoint(rightDir, left),
  71428. ];
  71429. let planeQueryParts = [];
  71430. for(let plane of planes){
  71431. let part = [plane.normal.toArray(), plane.constant].join(",");
  71432. part = `[${part}]`;
  71433. planeQueryParts.push(part);
  71434. }
  71435. let region = "[" + planeQueryParts.join(",") + "]";
  71436. regions.push(region);
  71437. }
  71438. }
  71439. let regionsArg = regions.join(",");
  71440. let pointcloudArgs = [];
  71441. for(let pointcloud of this.viewer.scene.pointclouds){
  71442. if(!pointcloud.visible){
  71443. continue;
  71444. }
  71445. let offset = pointcloud.pcoGeometry.offset.clone();
  71446. let negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  71447. let matrixWorld = pointcloud.matrixWorld;
  71448. let transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  71449. let path = `${window.location.pathname}/../${pointcloud.pcoGeometry.url}`;
  71450. let arg = {
  71451. path: path,
  71452. transform: transform.elements,
  71453. };
  71454. let argString = JSON.stringify(arg);
  71455. pointcloudArgs.push(argString);
  71456. }
  71457. let pointcloudsArg = pointcloudArgs.join(",");
  71458. let elMessage = this.elContent.find("div[name=download_message]");
  71459. let error = (message) => {
  71460. elMessage.html(`<div style="color: #ff0000">ERROR: ${message}</div>`);
  71461. };
  71462. let info = (message) => {
  71463. elMessage.html(`${message}`);
  71464. };
  71465. let handle = null;
  71466. { // START FILTER
  71467. let url = `${viewer.server}/create_regions_filter?pointclouds=[${pointcloudsArg}]&regions=[${regionsArg}]`;
  71468. //console.log(url);
  71469. info("estimating results ...");
  71470. let response = await fetch(url);
  71471. let jsResponse = await response.json();
  71472. //console.log(jsResponse);
  71473. if(!jsResponse.handle){
  71474. error(jsResponse.message);
  71475. return;
  71476. }else {
  71477. handle = jsResponse.handle;
  71478. }
  71479. }
  71480. { // WAIT, CHECK PROGRESS, HANDLE FINISH
  71481. let url = `${viewer.server}/check_regions_filter?handle=${handle}`;
  71482. let sleep = (function(duration){
  71483. return new Promise( (res, rej) => {
  71484. setTimeout(() => {
  71485. res();
  71486. }, duration);
  71487. });
  71488. });
  71489. let handleFiltering = (jsResponse) => {
  71490. let {progress, estimate} = jsResponse;
  71491. let progressFract = progress["processed points"] / estimate.points;
  71492. let progressPercents = parseInt(progressFract * 100);
  71493. info(`progress: ${progressPercents}%`);
  71494. };
  71495. let handleFinish = (jsResponse) => {
  71496. let message = "downloads ready: <br>";
  71497. message += "<ul>";
  71498. for(let i = 0; i < jsResponse.pointclouds.length; i++){
  71499. let url = `${viewer.server}/download_regions_filter_result?handle=${handle}&index=${i}`;
  71500. message += `<li><a href="${url}">result_${i}.las</a> </li>\n`;
  71501. }
  71502. let reportURL = `${viewer.server}/download_regions_filter_report?handle=${handle}`;
  71503. message += `<li> <a href="${reportURL}">report.json</a> </li>\n`;
  71504. message += "</ul>";
  71505. info(message);
  71506. };
  71507. let handleUnexpected = (jsResponse) => {
  71508. let message = `Unexpected Response. <br>status: ${jsResponse.status} <br>message: ${jsResponse.message}`;
  71509. info(message);
  71510. };
  71511. let handleError = (jsResponse) => {
  71512. let message = `ERROR: ${jsResponse.message}`;
  71513. error(message);
  71514. throw new Error(message);
  71515. };
  71516. let start = Date.now();
  71517. while(true){
  71518. let response = await fetch(url);
  71519. let jsResponse = await response.json();
  71520. if(jsResponse.status === "ERROR"){
  71521. handleError(jsResponse);
  71522. }else if(jsResponse.status === "FILTERING"){
  71523. handleFiltering(jsResponse);
  71524. }else if(jsResponse.status === "FINISHED"){
  71525. handleFinish(jsResponse);
  71526. break;
  71527. }else {
  71528. handleUnexpected(jsResponse);
  71529. }
  71530. let durationS = (Date.now() - start) / 1000;
  71531. let sleepAmountMS = durationS < 10 ? 100 : 1000;
  71532. await sleep(sleepAmountMS);
  71533. }
  71534. }
  71535. }
  71536. };
  71537. class CameraPanel{
  71538. constructor(viewer, propertiesPanel){
  71539. this.viewer = viewer;
  71540. this.propertiesPanel = propertiesPanel;
  71541. this._update = () => { this.update(); };
  71542. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  71543. this.elContent = $(`
  71544. <div class="propertypanel_content">
  71545. <table>
  71546. <tr>
  71547. <th colspan="3">position</th>
  71548. <th></th>
  71549. </tr>
  71550. <tr>
  71551. <td align="center" id="camera_position_x" style="width: 25%"></td>
  71552. <td align="center" id="camera_position_y" style="width: 25%"></td>
  71553. <td align="center" id="camera_position_z" style="width: 25%"></td>
  71554. <td align="right" id="copy_camera_position" style="width: 25%">
  71555. <img name="copyPosition" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  71556. </td>
  71557. </tr>
  71558. <tr>
  71559. <th colspan="3">target</th>
  71560. <th></th>
  71561. </tr>
  71562. <tr>
  71563. <td align="center" id="camera_target_x" style="width: 25%"></td>
  71564. <td align="center" id="camera_target_y" style="width: 25%"></td>
  71565. <td align="center" id="camera_target_z" style="width: 25%"></td>
  71566. <td align="right" id="copy_camera_target" style="width: 25%">
  71567. <img name="copyTarget" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  71568. </td>
  71569. </tr>
  71570. </table>
  71571. </div>
  71572. `);
  71573. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  71574. this.elCopyPosition.click( () => {
  71575. let pos = this.viewer.scene.getActiveCamera().position.toArray();
  71576. let msg = pos.map(c => c.toFixed(3)).join(", ");
  71577. Utils.clipboardCopy(msg);
  71578. this.viewer.postMessage(
  71579. `Copied value to clipboard: <br>'${msg}'`,
  71580. {duration: 3000});
  71581. });
  71582. this.elCopyTarget = this.elContent.find("img[name=copyTarget]");
  71583. this.elCopyTarget.click( () => {
  71584. let pos = this.viewer.scene.view.getPivot().toArray();
  71585. let msg = pos.map(c => c.toFixed(3)).join(", ");
  71586. Utils.clipboardCopy(msg);
  71587. this.viewer.postMessage(
  71588. `Copied value to clipboard: <br>'${msg}'`,
  71589. {duration: 3000});
  71590. });
  71591. this.propertiesPanel.addVolatileListener(viewer, "camera_changed", this._update);
  71592. this.update();
  71593. }
  71594. update(){
  71595. //console.log("updating camera panel");
  71596. let camera = this.viewer.scene.getActiveCamera();
  71597. let view = this.viewer.scene.view;
  71598. let pos = camera.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  71599. this.elContent.find("#camera_position_x").html(pos[0]);
  71600. this.elContent.find("#camera_position_y").html(pos[1]);
  71601. this.elContent.find("#camera_position_z").html(pos[2]);
  71602. let target = view.getPivot().toArray().map(c => Utils.addCommas(c.toFixed(3)));
  71603. this.elContent.find("#camera_target_x").html(target[0]);
  71604. this.elContent.find("#camera_target_y").html(target[1]);
  71605. this.elContent.find("#camera_target_z").html(target[2]);
  71606. }
  71607. };
  71608. class AnnotationPanel{
  71609. constructor(viewer, propertiesPanel, annotation){
  71610. this.viewer = viewer;
  71611. this.propertiesPanel = propertiesPanel;
  71612. this.annotation = annotation;
  71613. this._update = () => { this.update(); };
  71614. let copyIconPath = `${Potree.resourcePath}/icons/copy.svg`;
  71615. this.elContent = $(`
  71616. <div class="propertypanel_content">
  71617. <table>
  71618. <tr>
  71619. <th colspan="3">position</th>
  71620. <th></th>
  71621. </tr>
  71622. <tr>
  71623. <td align="center" id="annotation_position_x" style="width: 25%"></td>
  71624. <td align="center" id="annotation_position_y" style="width: 25%"></td>
  71625. <td align="center" id="annotation_position_z" style="width: 25%"></td>
  71626. <td align="right" id="copy_annotation_position" style="width: 25%">
  71627. <img name="copyPosition" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  71628. </td>
  71629. </tr>
  71630. </table>
  71631. <div>
  71632. <div class="heading">Title</div>
  71633. <div id="annotation_title" contenteditable="true">
  71634. Annotation Title
  71635. </div>
  71636. <div class="heading">Description</div>
  71637. <div id="annotation_description" contenteditable="true">
  71638. A longer description of this annotation.
  71639. Can be multiple lines long. TODO: the user should be able
  71640. to modify title and description.
  71641. </div>
  71642. </div>
  71643. </div>
  71644. `);
  71645. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  71646. this.elCopyPosition.click( () => {
  71647. let pos = this.annotation.position.toArray();
  71648. let msg = pos.map(c => c.toFixed(3)).join(", ");
  71649. Utils.clipboardCopy(msg);
  71650. this.viewer.postMessage(
  71651. `Copied value to clipboard: <br>'${msg}'`,
  71652. {duration: 3000});
  71653. });
  71654. this.elTitle = this.elContent.find("#annotation_title").html(annotation.title);
  71655. this.elDescription = this.elContent.find("#annotation_description").html(annotation.description);
  71656. this.elTitle[0].addEventListener("input", () => {
  71657. const title = this.elTitle.html();
  71658. annotation.title = title;
  71659. }, false);
  71660. this.elDescription[0].addEventListener("input", () => {
  71661. const description = this.elDescription.html();
  71662. annotation.description = description;
  71663. }, false);
  71664. this.update();
  71665. }
  71666. update(){
  71667. const {annotation, elContent, elTitle, elDescription} = this;
  71668. let pos = annotation.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  71669. elContent.find("#annotation_position_x").html(pos[0]);
  71670. elContent.find("#annotation_position_y").html(pos[1]);
  71671. elContent.find("#annotation_position_z").html(pos[2]);
  71672. elTitle.html(annotation.title);
  71673. elDescription.html(annotation.description);
  71674. }
  71675. };
  71676. class CameraAnimationPanel{
  71677. constructor(viewer, propertiesPanel, animation){
  71678. this.viewer = viewer;
  71679. this.propertiesPanel = propertiesPanel;
  71680. this.animation = animation;
  71681. this.elContent = $(`
  71682. <div class="propertypanel_content">
  71683. <span id="animation_keyframes"></span>
  71684. <span>
  71685. <span style="display:flex">
  71686. <span style="display:flex; align-items: center; padding-right: 10px">Duration: </span>
  71687. <input name="spnDuration" value="5.0" style="flex-grow: 1; width:100%">
  71688. </span>
  71689. <span>Time: </span><span id="lblTime"></span> <div id="sldTime"></div>
  71690. <input name="play" type="button" value="play"/>
  71691. </span>
  71692. </div>
  71693. `);
  71694. const elPlay = this.elContent.find("input[name=play]");
  71695. elPlay.click( () => {
  71696. animation.play();
  71697. });
  71698. const elSlider = this.elContent.find('#sldTime');
  71699. elSlider.slider({
  71700. value: 0,
  71701. min: 0,
  71702. max: 1,
  71703. step: 0.001,
  71704. slide: (event, ui) => {
  71705. animation.set(ui.value);
  71706. animation.updateFrustum();
  71707. }
  71708. });
  71709. let elDuration = this.elContent.find(`input[name=spnDuration]`);
  71710. elDuration.spinner({
  71711. min: 0, max: 300, step: 0.01,
  71712. numberFormat: 'n',
  71713. start: () => {},
  71714. spin: (event, ui) => {
  71715. let value = elDuration.spinner('value');
  71716. animation.setDuration(value);
  71717. },
  71718. change: (event, ui) => {
  71719. let value = elDuration.spinner('value');
  71720. animation.setDuration(value);
  71721. },
  71722. stop: (event, ui) => {
  71723. let value = elDuration.spinner('value');
  71724. animation.setDuration(value);
  71725. },
  71726. incremental: (count) => {
  71727. let value = elDuration.spinner('value');
  71728. let step = elDuration.spinner('option', 'step');
  71729. let delta = value * 0.05;
  71730. let increments = Math.max(1, parseInt(delta / step));
  71731. return increments;
  71732. }
  71733. });
  71734. elDuration.spinner('value', animation.getDuration());
  71735. elDuration.spinner('widget').css('width', '100%');
  71736. const elKeyframes = this.elContent.find("#animation_keyframes");
  71737. const updateKeyframes = () => {
  71738. elKeyframes.empty();
  71739. //let index = 0;
  71740. // <span style="flex-grow: 0;">
  71741. // <img name="add" src="${Potree.resourcePath}/icons/add.svg" style="width: 1.5em; height: 1.5em"/>
  71742. // </span>
  71743. const addNewKeyframeItem = (index) => {
  71744. let elNewKeyframe = $(`
  71745. <div style="display: flex; margin: 0.2em 0em">
  71746. <span style="flex-grow: 1"></span>
  71747. <input type="button" name="add" value="insert control point" />
  71748. <span style="flex-grow: 1"></span>
  71749. </div>
  71750. `);
  71751. const elAdd = elNewKeyframe.find("input[name=add]");
  71752. elAdd.click( () => {
  71753. animation.createControlPoint(index);
  71754. animation.changeCallback();
  71755. });
  71756. elKeyframes.append(elNewKeyframe);
  71757. };
  71758. const addKeyframeItem = (index) => {
  71759. let elKeyframe = $(`
  71760. <div style="display: flex; margin: 0.2em 0em">
  71761. <span style="flex-grow: 0;">
  71762. <img name="assign" src="${Potree.resourcePath}/icons/assign.svg" style="width: 1.5em; height: 1.5em"/>
  71763. </span>
  71764. <span style="flex-grow: 0;">
  71765. <img name="move" src="${Potree.resourcePath}/icons/circled_dot.svg" style="width: 1.5em; height: 1.5em"/>
  71766. </span>
  71767. <span style="flex-grow: 0; width: 1.5em; height: 1.5em"></span>
  71768. <span style="flex-grow: 0; font-size: 1.5em">keyframe</span>
  71769. <span style="flex-grow: 1"></span>
  71770. <span style="flex-grow: 0;">
  71771. <img name="delete" src="${Potree.resourcePath}/icons/remove.svg" style="width: 1.5em; height: 1.5em"/>
  71772. </span>
  71773. </div>
  71774. `);
  71775. const elAssign = elKeyframe.find("img[name=assign]");
  71776. const elMove = elKeyframe.find("img[name=move]");
  71777. const elDelete = elKeyframe.find("img[name=delete]");
  71778. elAssign.click( () => {
  71779. animation.posCurve.points[index].copy(viewer.scene.view.position);
  71780. animation.targetCurve.points[index].copy(viewer.scene.view.getPivot());
  71781. animation.changeCallback();
  71782. });
  71783. elMove.click( () => {
  71784. viewer.scene.view.position.copy(animation.posCurve.points[index]);
  71785. viewer.scene.view.lookAt(animation.targetCurve.points[index]);
  71786. });
  71787. elDelete.click( () => {
  71788. animation.removeControlPoint(index);
  71789. animation.changeCallback();
  71790. });
  71791. elKeyframes.append(elKeyframe);
  71792. };
  71793. let index = 0;
  71794. addNewKeyframeItem(index);
  71795. animation.posCurve.points.forEach(e=>{
  71796. addKeyframeItem(index);
  71797. index++;
  71798. addNewKeyframeItem(index);
  71799. });
  71800. };
  71801. updateKeyframes();
  71802. animation.addEventListener("controlpoint_added", updateKeyframes);
  71803. animation.addEventListener("controlpoint_removed", updateKeyframes);
  71804. // this._update = () => { this.update(); };
  71805. // this.update();
  71806. }
  71807. update(){
  71808. }
  71809. };
  71810. class PropertiesPanel{
  71811. constructor(container, viewer){
  71812. this.container = container;
  71813. this.viewer = viewer;
  71814. this.object = null;
  71815. this.cleanupTasks = [];
  71816. this.scene = null;
  71817. }
  71818. setScene(scene){
  71819. this.scene = scene;
  71820. }
  71821. set(object){
  71822. if(this.object === object){
  71823. return;
  71824. }
  71825. this.object = object;
  71826. for(let task of this.cleanupTasks){
  71827. task();
  71828. }
  71829. this.cleanupTasks = [];
  71830. this.container.empty();
  71831. if(object instanceof PointCloudTree){
  71832. this.setPointCloud(object);
  71833. }else if(object instanceof Measure || object instanceof Profile || object instanceof Volume){
  71834. this.setMeasurement(object);
  71835. }else if(object instanceof Camera){
  71836. this.setCamera(object);
  71837. }else if(object instanceof Annotation){
  71838. this.setAnnotation(object);
  71839. }else if(object instanceof CameraAnimation$1){//改
  71840. this.setCameraAnimation(object);
  71841. }
  71842. }
  71843. //
  71844. // Used for events that should be removed when the property object changes.
  71845. // This is for listening to materials, scene, point clouds, etc.
  71846. // not required for DOM listeners, since they are automatically cleared by removing the DOM subtree.
  71847. //
  71848. addVolatileListener(target, type, callback){
  71849. target.addEventListener(type, callback);
  71850. this.cleanupTasks.push(() => {
  71851. target.removeEventListener(type, callback);
  71852. });
  71853. }
  71854. setPointCloud(pointcloud){
  71855. let material = pointcloud.material;
  71856. let panel = $(`
  71857. <div class="scene_content selectable">
  71858. <ul class="pv-menu-list">
  71859. <li>
  71860. <span data-i18n="appearance.point_size"></span>:&nbsp;<span id="lblPointSize"></span> <div id="sldPointSize"></div>
  71861. </li>
  71862. <li>
  71863. <span data-i18n="appearance.min_point_size"></span>:&nbsp;<span id="lblMinPointSize"></span> <div id="sldMinPointSize"></div>
  71864. </li>
  71865. <!-- SIZE TYPE -->
  71866. <li>
  71867. <label for="optPointSizing" class="pv-select-label" data-i18n="appearance.point_size_type">Point Sizing </label>
  71868. <select id="optPointSizing" name="optPointSizing">
  71869. <option>FIXED</option>
  71870. <option>ATTENUATED</option>
  71871. <option>ADAPTIVE</option>
  71872. </select>
  71873. </li>
  71874. <!-- SHAPE -->
  71875. <li>
  71876. <label for="optShape" class="pv-select-label" data-i18n="appearance.point_shape"></label><br>
  71877. <select id="optShape" name="optShape">
  71878. <option>SQUARE</option>
  71879. <option>CIRCLE</option>
  71880. <option>PARABOLOID</option>
  71881. </select>
  71882. </li>
  71883. <li id="materials_backface_container">
  71884. <label><input id="set_backface_culling" type="checkbox" /><span data-i18n="appearance.backface_culling"></span></label>
  71885. </li>
  71886. <!-- OPACITY -->
  71887. <li><span data-i18n="appearance.point_opacity"></span>:<span id="lblOpacity"></span><div id="sldOpacity"></div></li>
  71888. <div class="divider">
  71889. <span>Attribute</span>
  71890. </div>
  71891. <li>
  71892. <select id="optMaterial" name="optMaterial"></select>
  71893. </li>
  71894. <div id="materials.composite_weight_container">
  71895. <div class="divider">
  71896. <span>Attribute Weights</span>
  71897. </div>
  71898. <li>RGB: <span id="lblWeightRGB"></span> <div id="sldWeightRGB"></div> </li>
  71899. <li>Intensity: <span id="lblWeightIntensity"></span> <div id="sldWeightIntensity"></div> </li>
  71900. <li>Elevation: <span id="lblWeightElevation"></span> <div id="sldWeightElevation"></div> </li>
  71901. <li>Classification: <span id="lblWeightClassification"></span> <div id="sldWeightClassification"></div> </li>
  71902. <li>Return Number: <span id="lblWeightReturnNumber"></span> <div id="sldWeightReturnNumber"></div> </li>
  71903. <li>Source ID: <span id="lblWeightSourceID"></span> <div id="sldWeightSourceID"></div> </li>
  71904. </div>
  71905. <div id="materials.rgb_container">
  71906. <div class="divider">
  71907. <span>RGB</span>
  71908. </div>
  71909. <li>Gamma: <span id="lblRGBGamma"></span> <div id="sldRGBGamma"></div> </li>
  71910. <li>Brightness: <span id="lblRGBBrightness"></span> <div id="sldRGBBrightness"></div> </li>
  71911. <li>Contrast: <span id="lblRGBContrast"></span> <div id="sldRGBContrast"></div> </li>
  71912. </div>
  71913. <div id="materials.extra_container">
  71914. <div class="divider">
  71915. <span>Extra Attribute</span>
  71916. </div>
  71917. <li><span data-i18n="appearance.extra_range"></span>: <span id="lblExtraRange"></span> <div id="sldExtraRange"></div></li>
  71918. <li>Gamma: <span id="lblExtraGamma"></span> <div id="sldExtraGamma"></div></li>
  71919. <li>Brightness: <span id="lblExtraBrightness"></span> <div id="sldExtraBrightness"></div></li>
  71920. <li>Contrast: <span id="lblExtraContrast"></span> <div id="sldExtraContrast"></div></li>
  71921. </div>
  71922. <div id="materials.matcap_container">
  71923. <div class="divider">
  71924. <span>MATCAP</span>
  71925. </div>
  71926. <li>
  71927. <div id="matcap_scheme_selection" style="display: flex; flex-wrap: wrap;"> </div>
  71928. </li>
  71929. </div>
  71930. <div id="materials.color_container">
  71931. <div class="divider">
  71932. <span>Color</span>
  71933. </div>
  71934. <input id="materials.color.picker" />
  71935. </div>
  71936. <div id="materials.elevation_container">
  71937. <div class="divider">
  71938. <span>Elevation</span>
  71939. </div>
  71940. <li><span data-i18n="appearance.elevation_range"></span>: <span id="lblHeightRange"></span> <div id="sldHeightRange"></div> </li>
  71941. <li>
  71942. <selectgroup id="gradient_repeat_option">
  71943. <option id="gradient_repeat_clamp" value="CLAMP">Clamp</option>
  71944. <option id="gradient_repeat_repeat" value="REPEAT">Repeat</option>
  71945. <option id="gradient_repeat_mirrored_repeat" value="MIRRORED_REPEAT">Mirrored Repeat</option>
  71946. </selectgroup>
  71947. </li>
  71948. <li>
  71949. <span>Gradient Scheme:</span>
  71950. <div id="elevation_gradient_scheme_selection" style="display: flex; padding: 1em 0em">
  71951. </div>
  71952. </li>
  71953. </div>
  71954. <div id="materials.transition_container">
  71955. <div class="divider">
  71956. <span>Transition</span>
  71957. </div>
  71958. <li>transition: <span id="lblTransition"></span> <div id="sldTransition"></div> </li>
  71959. </div>
  71960. <div id="materials.intensity_container">
  71961. <div class="divider">
  71962. <span>Intensity</span>
  71963. </div>
  71964. <li>Range: <span id="lblIntensityRange"></span> <div id="sldIntensityRange"></div> </li>
  71965. <li>Gamma: <span id="lblIntensityGamma"></span> <div id="sldIntensityGamma"></div> </li>
  71966. <li>Brightness: <span id="lblIntensityBrightness"></span> <div id="sldIntensityBrightness"></div> </li>
  71967. <li>Contrast: <span id="lblIntensityContrast"></span> <div id="sldIntensityContrast"></div> </li>
  71968. </div>
  71969. <div id="materials.gpstime_container">
  71970. <div class="divider">
  71971. <span>GPS Time</span>
  71972. </div>
  71973. </div>
  71974. <div id="materials.index_container">
  71975. <div class="divider">
  71976. <span>Indices</span>
  71977. </div>
  71978. </div>
  71979. </ul>
  71980. </div>
  71981. `);
  71982. panel.i18n();
  71983. this.container.append(panel);
  71984. { // POINT SIZE
  71985. let sldPointSize = panel.find(`#sldPointSize`);
  71986. let lblPointSize = panel.find(`#lblPointSize`);
  71987. sldPointSize.slider({
  71988. value: material.size,
  71989. min: 0,
  71990. max: 3,
  71991. step: 0.01,
  71992. slide: function (event, ui) { material.size = ui.value; }
  71993. });
  71994. let update = (e) => {
  71995. lblPointSize.html(material.size.toFixed(2));
  71996. sldPointSize.slider({value: material.size});
  71997. };
  71998. this.addVolatileListener(material, "point_size_changed", update);
  71999. update();
  72000. }
  72001. { // MINIMUM POINT SIZE
  72002. let sldMinPointSize = panel.find(`#sldMinPointSize`);
  72003. let lblMinPointSize = panel.find(`#lblMinPointSize`);
  72004. sldMinPointSize.slider({
  72005. value: material.size,
  72006. min: 0,
  72007. max: 3,
  72008. step: 0.01,
  72009. slide: function (event, ui) { material.minSize = ui.value; }
  72010. });
  72011. let update = (e) => {
  72012. lblMinPointSize.html(material.minSize.toFixed(2));
  72013. sldMinPointSize.slider({value: material.minSize});
  72014. };
  72015. this.addVolatileListener(material, "point_size_changed", update);
  72016. update();
  72017. }
  72018. { // POINT SIZING
  72019. let strSizeType = Object.keys(PointSizeType)[material.pointSizeType];
  72020. let opt = panel.find(`#optPointSizing`);
  72021. opt.selectmenu();
  72022. opt.val(strSizeType).selectmenu('refresh');
  72023. opt.selectmenu({
  72024. change: (event, ui) => {
  72025. material.pointSizeType = PointSizeType[ui.item.value];
  72026. }
  72027. });
  72028. }
  72029. { // SHAPE
  72030. let opt = panel.find(`#optShape`);
  72031. opt.selectmenu({
  72032. change: (event, ui) => {
  72033. let value = ui.item.value;
  72034. material.shape = PointShape$1[value];
  72035. }
  72036. });
  72037. let update = () => {
  72038. let typename = Object.keys(PointShape$1)[material.shape];
  72039. opt.selectmenu().val(typename).selectmenu('refresh');
  72040. };
  72041. this.addVolatileListener(material, "point_shape_changed", update);
  72042. update();
  72043. }
  72044. { // BACKFACE CULLING
  72045. let opt = panel.find(`#set_backface_culling`);
  72046. opt.click(() => {
  72047. material.backfaceCulling = opt.prop("checked");
  72048. });
  72049. let update = () => {
  72050. let value = material.backfaceCulling;
  72051. opt.prop("checked", value);
  72052. };
  72053. this.addVolatileListener(material, "backface_changed", update);
  72054. update();
  72055. let blockBackface = $('#materials_backface_container');
  72056. blockBackface.css('display', 'none');
  72057. const pointAttributes = pointcloud.pcoGeometry.pointAttributes;
  72058. const hasNormals = pointAttributes.hasNormals ? pointAttributes.hasNormals() : false;
  72059. if(hasNormals) {
  72060. blockBackface.css('display', 'block');
  72061. }
  72062. /*
  72063. opt.checkboxradio({
  72064. clicked: (event, ui) => {
  72065. // let value = ui.item.value;
  72066. let value = ui.item.checked;
  72067. console.log(value);
  72068. material.backfaceCulling = value; // $('#set_freeze').prop("checked");
  72069. }
  72070. });
  72071. */
  72072. }
  72073. { // OPACITY
  72074. let sldOpacity = panel.find(`#sldOpacity`);
  72075. let lblOpacity = panel.find(`#lblOpacity`);
  72076. sldOpacity.slider({
  72077. value: material.opacity,
  72078. min: 0,
  72079. max: 1,
  72080. step: 0.001,
  72081. slide: function (event, ui) {
  72082. material.opacity = ui.value;
  72083. }
  72084. });
  72085. let update = (e) => {
  72086. lblOpacity.html(material.opacity.toFixed(2));
  72087. sldOpacity.slider({value: material.opacity});
  72088. };
  72089. this.addVolatileListener(material, "opacity_changed", update);
  72090. update();
  72091. }
  72092. {
  72093. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  72094. let options = [];
  72095. options.push(...attributes.map(a => a.name));
  72096. const intensityIndex = options.indexOf("intensity");
  72097. if(intensityIndex >= 0){
  72098. options.splice(intensityIndex + 1, 0, "intensity gradient");
  72099. }
  72100. options.push(
  72101. "elevation",
  72102. "color",
  72103. 'matcap',
  72104. 'indices',
  72105. 'level of detail',
  72106. 'composite'
  72107. );
  72108. const blacklist = [
  72109. "POSITION_CARTESIAN",
  72110. "position",
  72111. ];
  72112. options = options.filter(o => !blacklist.includes(o));
  72113. let attributeSelection = panel.find('#optMaterial');
  72114. for(let option of options){
  72115. let elOption = $(`<option>${option}</option>`);
  72116. attributeSelection.append(elOption);
  72117. }
  72118. let updateMaterialPanel = (event, ui) => {
  72119. let selectedValue = attributeSelection.selectmenu().val();
  72120. material.activeAttributeName = selectedValue;
  72121. let attribute = pointcloud.getAttribute(selectedValue);
  72122. if(selectedValue === "intensity gradient"){
  72123. attribute = pointcloud.getAttribute("intensity");
  72124. }
  72125. const isIntensity = attribute ? ["intensity", "intensity gradient"].includes(attribute.name) : false;
  72126. if(isIntensity){
  72127. if(pointcloud.material.intensityRange[0] === Infinity){
  72128. pointcloud.material.intensityRange = attribute.range;
  72129. }
  72130. const [min, max] = attribute.range;
  72131. panel.find('#sldIntensityRange').slider({
  72132. range: true,
  72133. min: min, max: max, step: 0.01,
  72134. values: [min, max],
  72135. slide: (event, ui) => {
  72136. let min = ui.values[0];
  72137. let max = ui.values[1];
  72138. material.intensityRange = [min, max];
  72139. }
  72140. });
  72141. } else if(attribute){
  72142. const [min, max] = attribute.range;
  72143. let selectedRange = material.getRange(attribute.name);
  72144. if(!selectedRange){
  72145. selectedRange = [...attribute.range];
  72146. }
  72147. let minMaxAreNumbers = typeof min === "number" && typeof max === "number";
  72148. if(minMaxAreNumbers){
  72149. panel.find('#sldExtraRange').slider({
  72150. range: true,
  72151. min: min,
  72152. max: max,
  72153. step: 0.01,
  72154. values: selectedRange,
  72155. slide: (event, ui) => {
  72156. let [a, b] = ui.values;
  72157. material.setRange(attribute.name, [a, b]);
  72158. }
  72159. });
  72160. }
  72161. }
  72162. let blockWeights = $('#materials\\.composite_weight_container');
  72163. let blockElevation = $('#materials\\.elevation_container');
  72164. let blockRGB = $('#materials\\.rgb_container');
  72165. let blockExtra = $('#materials\\.extra_container');
  72166. let blockColor = $('#materials\\.color_container');
  72167. let blockIntensity = $('#materials\\.intensity_container');
  72168. let blockIndex = $('#materials\\.index_container');
  72169. let blockTransition = $('#materials\\.transition_container');
  72170. let blockGps = $('#materials\\.gpstime_container');
  72171. let blockMatcap = $('#materials\\.matcap_container');
  72172. blockIndex.css('display', 'none');
  72173. blockIntensity.css('display', 'none');
  72174. blockElevation.css('display', 'none');
  72175. blockRGB.css('display', 'none');
  72176. blockExtra.css('display', 'none');
  72177. blockColor.css('display', 'none');
  72178. blockWeights.css('display', 'none');
  72179. blockTransition.css('display', 'none');
  72180. blockMatcap.css('display', 'none');
  72181. blockGps.css('display', 'none');
  72182. if (selectedValue === 'composite') {
  72183. blockWeights.css('display', 'block');
  72184. blockElevation.css('display', 'block');
  72185. blockRGB.css('display', 'block');
  72186. blockIntensity.css('display', 'block');
  72187. } else if (selectedValue === 'elevation') {
  72188. blockElevation.css('display', 'block');
  72189. } else if (selectedValue === 'RGB and Elevation') {
  72190. blockRGB.css('display', 'block');
  72191. blockElevation.css('display', 'block');
  72192. } else if (selectedValue === 'rgba') {
  72193. blockRGB.css('display', 'block');
  72194. } else if (selectedValue === 'color') {
  72195. blockColor.css('display', 'block');
  72196. } else if (selectedValue === 'intensity') {
  72197. blockIntensity.css('display', 'block');
  72198. } else if (selectedValue === 'intensity gradient') {
  72199. blockIntensity.css('display', 'block');
  72200. } else if (selectedValue === "indices" ){
  72201. blockIndex.css('display', 'block');
  72202. } else if (selectedValue === "matcap" ){
  72203. blockMatcap.css('display', 'block');
  72204. } else if (selectedValue === "classification" ){
  72205. // add classification color selctor?
  72206. } else if (selectedValue === "gps-time" ){
  72207. blockGps.css('display', 'block');
  72208. } else if(selectedValue === "number of returns"){
  72209. } else if(selectedValue === "return number"){
  72210. } else if(["source id", "point source id"].includes(selectedValue)){
  72211. } else {
  72212. blockExtra.css('display', 'block');
  72213. }
  72214. };
  72215. attributeSelection.selectmenu({change: updateMaterialPanel});
  72216. let update = () => {
  72217. attributeSelection.val(material.activeAttributeName).selectmenu('refresh');
  72218. };
  72219. this.addVolatileListener(material, "point_color_type_changed", update);
  72220. this.addVolatileListener(material, "active_attribute_changed", update);
  72221. update();
  72222. updateMaterialPanel();
  72223. }
  72224. {
  72225. const schemes = Object.keys(Potree.Gradients).map(name => ({name: name, values: Gradients[name]}));
  72226. let elSchemeContainer = panel.find("#elevation_gradient_scheme_selection");
  72227. for(let scheme of schemes){
  72228. let elScheme = $(`
  72229. <span style="flex-grow: 1;">
  72230. </span>
  72231. `);
  72232. const svg = Potree.Utils.createSvgGradient(scheme.values);
  72233. svg.setAttributeNS(null, "class", `button-icon`);
  72234. elScheme.append($(svg));
  72235. elScheme.click( () => {
  72236. material.gradient = Gradients[scheme.name];
  72237. });
  72238. elSchemeContainer.append(elScheme);
  72239. }
  72240. }
  72241. {
  72242. let matcaps = [
  72243. {name: "Normals", icon: `${Potree.resourcePath}/icons/matcap/check_normal+y.jpg`},
  72244. {name: "Basic 1", icon: `${Potree.resourcePath}/icons/matcap/basic_1.jpg`},
  72245. {name: "Basic 2", icon: `${Potree.resourcePath}/icons/matcap/basic_2.jpg`},
  72246. {name: "Basic Dark", icon: `${Potree.resourcePath}/icons/matcap/basic_dark.jpg`},
  72247. {name: "Basic Side", icon: `${Potree.resourcePath}/icons/matcap/basic_side.jpg`},
  72248. {name: "Ceramic Dark", icon: `${Potree.resourcePath}/icons/matcap/ceramic_dark.jpg`},
  72249. {name: "Ceramic Lightbulb", icon: `${Potree.resourcePath}/icons/matcap/ceramic_lightbulb.jpg`},
  72250. {name: "Clay Brown", icon: `${Potree.resourcePath}/icons/matcap/clay_brown.jpg`},
  72251. {name: "Clay Muddy", icon: `${Potree.resourcePath}/icons/matcap/clay_muddy.jpg`},
  72252. {name: "Clay Studio", icon: `${Potree.resourcePath}/icons/matcap/clay_studio.jpg`},
  72253. {name: "Resin", icon: `${Potree.resourcePath}/icons/matcap/resin.jpg`},
  72254. {name: "Skin", icon: `${Potree.resourcePath}/icons/matcap/skin.jpg`},
  72255. {name: "Jade", icon: `${Potree.resourcePath}/icons/matcap/jade.jpg`},
  72256. {name: "Metal_ Anisotropic", icon: `${Potree.resourcePath}/icons/matcap/metal_anisotropic.jpg`},
  72257. {name: "Metal Carpaint", icon: `${Potree.resourcePath}/icons/matcap/metal_carpaint.jpg`},
  72258. {name: "Metal Lead", icon: `${Potree.resourcePath}/icons/matcap/metal_lead.jpg`},
  72259. {name: "Metal Shiny", icon: `${Potree.resourcePath}/icons/matcap/metal_shiny.jpg`},
  72260. {name: "Pearl", icon: `${Potree.resourcePath}/icons/matcap/pearl.jpg`},
  72261. {name: "Toon", icon: `${Potree.resourcePath}/icons/matcap/toon.jpg`},
  72262. {name: "Check Rim Light", icon: `${Potree.resourcePath}/icons/matcap/check_rim_light.jpg`},
  72263. {name: "Check Rim Dark", icon: `${Potree.resourcePath}/icons/matcap/check_rim_dark.jpg`},
  72264. {name: "Contours 1", icon: `${Potree.resourcePath}/icons/matcap/contours_1.jpg`},
  72265. {name: "Contours 2", icon: `${Potree.resourcePath}/icons/matcap/contours_2.jpg`},
  72266. {name: "Contours 3", icon: `${Potree.resourcePath}/icons/matcap/contours_3.jpg`},
  72267. {name: "Reflection Check Horizontal", icon: `${Potree.resourcePath}/icons/matcap/reflection_check_horizontal.jpg`},
  72268. {name: "Reflection Check Vertical", icon: `${Potree.resourcePath}/icons/matcap/reflection_check_vertical.jpg`},
  72269. ];
  72270. let elMatcapContainer = panel.find("#matcap_scheme_selection");
  72271. for(let matcap of matcaps){
  72272. let elMatcap = $(`
  72273. <img src="${matcap.icon}" class="button-icon" style="width: 25%;" />
  72274. `);
  72275. elMatcap.click( () => {
  72276. material.matcap = matcap.icon.substring(matcap.icon.lastIndexOf('/'));
  72277. });
  72278. elMatcapContainer.append(elMatcap);
  72279. }
  72280. }
  72281. {
  72282. panel.find('#sldRGBGamma').slider({
  72283. value: material.rgbGamma,
  72284. min: 0, max: 4, step: 0.01,
  72285. slide: (event, ui) => {material.rgbGamma = ui.value;}
  72286. });
  72287. panel.find('#sldRGBContrast').slider({
  72288. value: material.rgbContrast,
  72289. min: -1, max: 1, step: 0.01,
  72290. slide: (event, ui) => {material.rgbContrast = ui.value;}
  72291. });
  72292. panel.find('#sldRGBBrightness').slider({
  72293. value: material.rgbBrightness,
  72294. min: -1, max: 1, step: 0.01,
  72295. slide: (event, ui) => {material.rgbBrightness = ui.value;}
  72296. });
  72297. panel.find('#sldExtraGamma').slider({
  72298. value: material.extraGamma,
  72299. min: 0, max: 4, step: 0.01,
  72300. slide: (event, ui) => {material.extraGamma = ui.value;}
  72301. });
  72302. panel.find('#sldExtraBrightness').slider({
  72303. value: material.extraBrightness,
  72304. min: -1, max: 1, step: 0.01,
  72305. slide: (event, ui) => {material.extraBrightness = ui.value;}
  72306. });
  72307. panel.find('#sldExtraContrast').slider({
  72308. value: material.extraContrast,
  72309. min: -1, max: 1, step: 0.01,
  72310. slide: (event, ui) => {material.extraContrast = ui.value;}
  72311. });
  72312. panel.find('#sldHeightRange').slider({
  72313. range: true,
  72314. min: 0, max: 1000, step: 0.01,
  72315. values: [0, 1000],
  72316. slide: (event, ui) => {
  72317. material.heightMin = ui.values[0];
  72318. material.heightMax = ui.values[1];
  72319. }
  72320. });
  72321. panel.find('#sldIntensityGamma').slider({
  72322. value: material.intensityGamma,
  72323. min: 0, max: 4, step: 0.01,
  72324. slide: (event, ui) => {material.intensityGamma = ui.value;}
  72325. });
  72326. panel.find('#sldIntensityContrast').slider({
  72327. value: material.intensityContrast,
  72328. min: -1, max: 1, step: 0.01,
  72329. slide: (event, ui) => {material.intensityContrast = ui.value;}
  72330. });
  72331. panel.find('#sldIntensityBrightness').slider({
  72332. value: material.intensityBrightness,
  72333. min: -1, max: 1, step: 0.01,
  72334. slide: (event, ui) => {material.intensityBrightness = ui.value;}
  72335. });
  72336. panel.find('#sldWeightRGB').slider({
  72337. value: material.weightRGB,
  72338. min: 0, max: 1, step: 0.01,
  72339. slide: (event, ui) => {material.weightRGB = ui.value;}
  72340. });
  72341. panel.find('#sldWeightIntensity').slider({
  72342. value: material.weightIntensity,
  72343. min: 0, max: 1, step: 0.01,
  72344. slide: (event, ui) => {material.weightIntensity = ui.value;}
  72345. });
  72346. panel.find('#sldWeightElevation').slider({
  72347. value: material.weightElevation,
  72348. min: 0, max: 1, step: 0.01,
  72349. slide: (event, ui) => {material.weightElevation = ui.value;}
  72350. });
  72351. panel.find('#sldWeightClassification').slider({
  72352. value: material.weightClassification,
  72353. min: 0, max: 1, step: 0.01,
  72354. slide: (event, ui) => {material.weightClassification = ui.value;}
  72355. });
  72356. panel.find('#sldWeightReturnNumber').slider({
  72357. value: material.weightReturnNumber,
  72358. min: 0, max: 1, step: 0.01,
  72359. slide: (event, ui) => {material.weightReturnNumber = ui.value;}
  72360. });
  72361. panel.find('#sldWeightSourceID').slider({
  72362. value: material.weightSourceID,
  72363. min: 0, max: 1, step: 0.01,
  72364. slide: (event, ui) => {material.weightSourceID = ui.value;}
  72365. });
  72366. panel.find(`#materials\\.color\\.picker`).spectrum({
  72367. flat: true,
  72368. showInput: true,
  72369. preferredFormat: 'rgb',
  72370. cancelText: '',
  72371. chooseText: 'Apply',
  72372. color: `#${material.color.getHexString()}`,
  72373. move: color => {
  72374. let cRGB = color.toRgb();
  72375. let tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  72376. material.color = tc;
  72377. },
  72378. change: color => {
  72379. let cRGB = color.toRgb();
  72380. let tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  72381. material.color = tc;
  72382. }
  72383. });
  72384. this.addVolatileListener(material, "color_changed", () => {
  72385. panel.find(`#materials\\.color\\.picker`)
  72386. .spectrum('set', `#${material.color.getHexString()}`);
  72387. });
  72388. let updateHeightRange = function () {
  72389. let aPosition = pointcloud.getAttribute("position");
  72390. let bMin, bMax;
  72391. if(aPosition){
  72392. // for new format 2.0 and loader that contain precomputed min/max of attributes
  72393. let min = aPosition.range[0][2];
  72394. let max = aPosition.range[1][2];
  72395. let width = max - min;
  72396. bMin = min - 0.2 * width;
  72397. bMax = max + 0.2 * width;
  72398. }else {
  72399. // for format up until exlusive 2.0
  72400. let box = [pointcloud.pcoGeometry.tightBoundingBox, pointcloud.getBoundingBoxWorld()]
  72401. .find(v => v !== undefined);
  72402. pointcloud.updateMatrixWorld(true);
  72403. box = Utils.computeTransformedBoundingBox(box, pointcloud.matrixWorld);
  72404. let bWidth = box.max.z - box.min.z;
  72405. bMin = box.min.z - 0.2 * bWidth;
  72406. bMax = box.max.z + 0.2 * bWidth;
  72407. }
  72408. let range = material.elevationRange;
  72409. panel.find('#lblHeightRange').html(`${range[0].toFixed(2)} to ${range[1].toFixed(2)}`);
  72410. panel.find('#sldHeightRange').slider({min: bMin, max: bMax, values: range});
  72411. };
  72412. let updateExtraRange = function () {
  72413. let attributeName = material.activeAttributeName;
  72414. let attribute = pointcloud.getAttribute(attributeName);
  72415. if(attribute == null){
  72416. return;
  72417. }
  72418. let range = material.getRange(attributeName);
  72419. if(range == null){
  72420. range = attribute.range;
  72421. }
  72422. // currently only supporting scalar ranges.
  72423. // rgba, normals, positions, etc have vector ranges, however
  72424. let isValidRange = (typeof range[0] === "number") && (typeof range[1] === "number");
  72425. if(!isValidRange){
  72426. return;
  72427. }
  72428. if(range){
  72429. let msg = `${range[0].toFixed(2)} to ${range[1].toFixed(2)}`;
  72430. panel.find('#lblExtraRange').html(msg);
  72431. }else {
  72432. panel.find("could not deduce range");
  72433. }
  72434. };
  72435. let updateIntensityRange = function () {
  72436. let range = material.intensityRange;
  72437. panel.find('#lblIntensityRange').html(`${parseInt(range[0])} to ${parseInt(range[1])}`);
  72438. };
  72439. {
  72440. updateHeightRange();
  72441. panel.find(`#sldHeightRange`).slider('option', 'min');
  72442. panel.find(`#sldHeightRange`).slider('option', 'max');
  72443. }
  72444. {
  72445. let elGradientRepeat = panel.find("#gradient_repeat_option");
  72446. elGradientRepeat.selectgroup({title: "Gradient"});
  72447. elGradientRepeat.find("input").click( (e) => {
  72448. this.viewer.setElevationGradientRepeat(ElevationGradientRepeat[e.target.value]);
  72449. });
  72450. let current = Object.keys(ElevationGradientRepeat)
  72451. .filter(key => ElevationGradientRepeat[key] === this.viewer.elevationGradientRepeat);
  72452. elGradientRepeat.find(`input[value=${current}]`).trigger("click");
  72453. }
  72454. let onIntensityChange = () => {
  72455. let gamma = material.intensityGamma;
  72456. let contrast = material.intensityContrast;
  72457. let brightness = material.intensityBrightness;
  72458. updateIntensityRange();
  72459. panel.find('#lblIntensityGamma').html(gamma.toFixed(2));
  72460. panel.find('#lblIntensityContrast').html(contrast.toFixed(2));
  72461. panel.find('#lblIntensityBrightness').html(brightness.toFixed(2));
  72462. panel.find('#sldIntensityGamma').slider({value: gamma});
  72463. panel.find('#sldIntensityContrast').slider({value: contrast});
  72464. panel.find('#sldIntensityBrightness').slider({value: brightness});
  72465. };
  72466. let onRGBChange = () => {
  72467. let gamma = material.rgbGamma;
  72468. let contrast = material.rgbContrast;
  72469. let brightness = material.rgbBrightness;
  72470. panel.find('#lblRGBGamma').html(gamma.toFixed(2));
  72471. panel.find('#lblRGBContrast').html(contrast.toFixed(2));
  72472. panel.find('#lblRGBBrightness').html(brightness.toFixed(2));
  72473. panel.find('#sldRGBGamma').slider({value: gamma});
  72474. panel.find('#sldRGBContrast').slider({value: contrast});
  72475. panel.find('#sldRGBBrightness').slider({value: brightness});
  72476. };
  72477. this.addVolatileListener(material, "material_property_changed", updateExtraRange);
  72478. this.addVolatileListener(material, "material_property_changed", updateHeightRange);
  72479. this.addVolatileListener(material, "material_property_changed", onIntensityChange);
  72480. this.addVolatileListener(material, "material_property_changed", onRGBChange);
  72481. updateExtraRange();
  72482. updateHeightRange();
  72483. onIntensityChange();
  72484. onRGBChange();
  72485. }
  72486. }
  72487. setMeasurement(object){
  72488. let TYPE = {
  72489. DISTANCE: {panel: DistancePanel},
  72490. AREA: {panel: AreaPanel},
  72491. POINT: {panel: PointPanel},
  72492. ANGLE: {panel: AnglePanel},
  72493. HEIGHT: {panel: HeightPanel},
  72494. PROFILE: {panel: ProfilePanel},
  72495. VOLUME: {panel: VolumePanel},
  72496. CIRCLE: {panel: CirclePanel},
  72497. OTHER: {panel: PointPanel},
  72498. };
  72499. let getType = (measurement) => {
  72500. if (measurement instanceof Measure) {
  72501. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  72502. return TYPE.DISTANCE;
  72503. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  72504. return TYPE.AREA;
  72505. } else if (measurement.maxMarkers === 1) {
  72506. return TYPE.POINT;
  72507. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  72508. return TYPE.ANGLE;
  72509. } else if (measurement.showHeight) {
  72510. return TYPE.HEIGHT;
  72511. } else if (measurement.showCircle) {
  72512. return TYPE.CIRCLE;
  72513. } else {
  72514. return TYPE.OTHER;
  72515. }
  72516. } else if (measurement instanceof Profile) {
  72517. return TYPE.PROFILE;
  72518. } else if (measurement instanceof Volume) {
  72519. return TYPE.VOLUME;
  72520. }
  72521. };
  72522. //this.container.html("measurement");
  72523. let type = getType(object);
  72524. let Panel = type.panel;
  72525. let panel = new Panel(this.viewer, object, this);
  72526. this.container.append(panel.elContent);
  72527. }
  72528. setCamera(camera){
  72529. let panel = new CameraPanel(this.viewer, this);
  72530. this.container.append(panel.elContent);
  72531. }
  72532. setAnnotation(annotation){
  72533. let panel = new AnnotationPanel(this.viewer, this, annotation);
  72534. this.container.append(panel.elContent);
  72535. }
  72536. setCameraAnimation(animation){
  72537. let panel = new CameraAnimationPanel(this.viewer, this, animation);
  72538. this.container.append(panel.elContent);
  72539. }
  72540. }
  72541. function addCommas(nStr){
  72542. nStr += '';
  72543. let x = nStr.split('.');
  72544. let x1 = x[0];
  72545. let x2 = x.length > 1 ? '.' + x[1] : '';
  72546. let rgx = /(\d+)(\d{3})/;
  72547. while (rgx.test(x1)) {
  72548. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  72549. }
  72550. return x1 + x2;
  72551. };
  72552. function format(value){
  72553. return addCommas(value.toFixed(3));
  72554. };
  72555. class HierarchicalSlider{
  72556. constructor(params = {}){
  72557. this.element = document.createElement("div");
  72558. this.labels = [];
  72559. this.sliders = [];
  72560. this.range = params.range != null ? params.range : [0, 1];
  72561. this.slide = params.slide != null ? params.slide : null;
  72562. this.step = params.step != null ? params.step : 0.0001;
  72563. let levels = params.levels != null ? params.levels : 1;
  72564. for(let level = 0; level < levels; level++){
  72565. this.addLevel();
  72566. }
  72567. }
  72568. setRange(range){
  72569. this.range = [...range];
  72570. { // root slider
  72571. let slider = this.sliders[0];
  72572. $(slider).slider({
  72573. min: range[0],
  72574. max: range[1],
  72575. });
  72576. }
  72577. for(let i = 1; i < this.sliders.length; i++){
  72578. let parentSlider = this.sliders[i - 1];
  72579. let slider = this.sliders[i];
  72580. let parentValues = $(parentSlider).slider("option", "values");
  72581. let childRange = [...parentValues];
  72582. $(slider).slider({
  72583. min: childRange[0],
  72584. max: childRange[1],
  72585. });
  72586. }
  72587. this.updateLabels();
  72588. }
  72589. setValues(values){
  72590. for(let slider of this.sliders){
  72591. $(slider).slider({
  72592. values: [...values],
  72593. });
  72594. }
  72595. this.updateLabels();
  72596. }
  72597. addLevel(){
  72598. const elLevel = document.createElement("li");
  72599. const elRange = document.createTextNode("Range: ");
  72600. const label = document.createElement("span");
  72601. const slider = document.createElement("div");
  72602. let level = this.sliders.length;
  72603. let [min, max] = [0, 0];
  72604. if(this.sliders.length === 0){
  72605. [min, max] = this.range;
  72606. }else {
  72607. let parentSlider = this.sliders[this.sliders.length - 1];
  72608. [min, max] = $(parentSlider).slider("option", "values");
  72609. }
  72610. $(slider).slider({
  72611. range: true,
  72612. min: min,
  72613. max: max,
  72614. step: this.step,
  72615. values: [min, max],
  72616. slide: (event, ui) => {
  72617. // set all descendants to same range
  72618. let levels = this.sliders.length;
  72619. for(let i = level + 1; i < levels; i++){
  72620. let descendant = this.sliders[i];
  72621. $(descendant).slider({
  72622. range: true,
  72623. min: ui.values[0],
  72624. max: ui.values[1],
  72625. values: [...ui.values],
  72626. });
  72627. }
  72628. if(this.slide){
  72629. let values = [...ui.values];
  72630. this.slide({
  72631. target: this,
  72632. range: this.range,
  72633. values: values,
  72634. });
  72635. }
  72636. this.updateLabels();
  72637. },
  72638. });
  72639. elLevel.append(elRange, label, slider);
  72640. this.sliders.push(slider);
  72641. this.labels.push(label);
  72642. this.element.append(elLevel);
  72643. this.updateLabels();
  72644. }
  72645. removeLevel(){
  72646. }
  72647. updateSliders(){
  72648. }
  72649. updateLabels(){
  72650. let levels = this.sliders.length;
  72651. for(let i = 0; i < levels; i++){
  72652. let slider = this.sliders[i];
  72653. let label = this.labels[i];
  72654. let [min, max] = $(slider).slider("option", "values");
  72655. let strMin = format(min);
  72656. let strMax = format(max);
  72657. let strLabel = `${strMin} to ${strMax}`;
  72658. label.innerHTML = strLabel;
  72659. }
  72660. }
  72661. }
  72662. class OrientedImageControls extends EventDispatcher$1{
  72663. constructor(viewer){
  72664. super();
  72665. this.viewer = viewer;
  72666. this.renderer = viewer.renderer;
  72667. this.originalCam = viewer.scene.getActiveCamera();
  72668. this.shearCam = viewer.scene.getActiveCamera().clone();
  72669. this.shearCam.rotation.set(this.originalCam.rotation.toArray());
  72670. this.shearCam.updateProjectionMatrix();
  72671. this.shearCam.updateProjectionMatrix = () => {
  72672. return this.shearCam.projectionMatrix;
  72673. };
  72674. this.image = null;
  72675. this.fadeFactor = 20;
  72676. this.fovDelta = 0;
  72677. this.fovMin = 0.1;
  72678. this.fovMax = 120;
  72679. this.shear = [0, 0];
  72680. // const style = ``;
  72681. this.elUp = $(`<input type="button" value="🡅" style="position: absolute; top: 10px; left: calc(50%); z-index: 1000" />`);
  72682. this.elRight = $(`<input type="button" value="🡆" style="position: absolute; top: calc(50%); right: 10px; z-index: 1000" />`);
  72683. this.elDown = $(`<input type="button" value="🡇" style="position: absolute; bottom: 10px; left: calc(50%); z-index: 1000" />`);
  72684. this.elLeft = $(`<input type="button" value="🡄" style="position: absolute; top: calc(50%); left: 10px; z-index: 1000" />`);
  72685. this.elExit = $(`<input type="button" value="Back to 3D view" style="position: absolute; bottom: 10px; right: 10px; z-index: 1000" />`);
  72686. this.elExit.click( () => {
  72687. this.release();
  72688. });
  72689. this.elUp.click(() => {
  72690. const fovY = viewer.getFOV();
  72691. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  72692. this.shear[1] += 0.1 * top;
  72693. });
  72694. this.elRight.click(() => {
  72695. const fovY = viewer.getFOV();
  72696. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  72697. this.shear[0] += 0.1 * top;
  72698. });
  72699. this.elDown.click(() => {
  72700. const fovY = viewer.getFOV();
  72701. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  72702. this.shear[1] -= 0.1 * top;
  72703. });
  72704. this.elLeft.click(() => {
  72705. const fovY = viewer.getFOV();
  72706. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  72707. this.shear[0] -= 0.1 * top;
  72708. });
  72709. this.scene = null;
  72710. this.sceneControls = new Scene();
  72711. let scroll = (e) => {
  72712. this.fovDelta += -e.delta * 1.0;
  72713. };
  72714. this.addEventListener('mousewheel', scroll);
  72715. //this.addEventListener("mousemove", onMove);
  72716. }
  72717. hasSomethingCaptured(){
  72718. return this.image !== null;
  72719. }
  72720. capture(image){
  72721. if(this.hasSomethingCaptured()){
  72722. return;
  72723. }
  72724. this.image = image;
  72725. this.originalFOV = this.viewer.getFOV();
  72726. this.originalControls = this.viewer.getControls();
  72727. this.viewer.setControls(this);
  72728. this.viewer.scene.overrideCamera = this.shearCam;
  72729. const elCanvas = this.viewer.renderer.domElement;
  72730. const elRoot = $(elCanvas.parentElement);
  72731. this.shear = [0, 0];
  72732. elRoot.append(this.elUp);
  72733. elRoot.append(this.elRight);
  72734. elRoot.append(this.elDown);
  72735. elRoot.append(this.elLeft);
  72736. elRoot.append(this.elExit);
  72737. }
  72738. release(){
  72739. this.image = null;
  72740. this.viewer.scene.overrideCamera = null;
  72741. this.elUp.detach();
  72742. this.elRight.detach();
  72743. this.elDown.detach();
  72744. this.elLeft.detach();
  72745. this.elExit.detach();
  72746. this.viewer.setFOV(this.originalFOV);
  72747. this.viewer.setControls(this.originalControls);
  72748. }
  72749. setScene (scene) {
  72750. this.scene = scene;
  72751. }
  72752. update (delta) {
  72753. // const view = this.scene.view;
  72754. // let prevTotal = this.shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  72755. //const progression = Math.min(1, this.fadeFactor * delta);
  72756. //const attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  72757. const progression = 1;
  72758. const attenuation = 0;
  72759. const oldFov = this.viewer.getFOV();
  72760. let fovProgression = progression * this.fovDelta;
  72761. let newFov = oldFov * ((1 + fovProgression / 10));
  72762. newFov = Math.max(this.fovMin, newFov);
  72763. newFov = Math.min(this.fovMax, newFov);
  72764. let diff = newFov / oldFov;
  72765. const mouse = this.viewer.inputHandler.mouse;
  72766. const canvasSize = this.viewer.renderer.getSize(new Vector2());
  72767. const uv = [
  72768. (mouse.x / canvasSize.x),
  72769. ((canvasSize.y - mouse.y) / canvasSize.y)
  72770. ];
  72771. const fovY = newFov;
  72772. const aspect = canvasSize.x / canvasSize.y;
  72773. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  72774. const height = 2 * top;
  72775. const width = aspect * height;
  72776. const shearRangeX = [
  72777. this.shear[0] - 0.5 * width,
  72778. this.shear[0] + 0.5 * width,
  72779. ];
  72780. const shearRangeY = [
  72781. this.shear[1] - 0.5 * height,
  72782. this.shear[1] + 0.5 * height,
  72783. ];
  72784. const shx = (1 - uv[0]) * shearRangeX[0] + uv[0] * shearRangeX[1];
  72785. const shy = (1 - uv[1]) * shearRangeY[0] + uv[1] * shearRangeY[1];
  72786. const shu = (1 - diff);
  72787. const newShear = [
  72788. (1 - shu) * this.shear[0] + shu * shx,
  72789. (1 - shu) * this.shear[1] + shu * shy,
  72790. ];
  72791. this.shear = newShear;
  72792. this.viewer.setFOV(newFov);
  72793. const {originalCam, shearCam} = this;
  72794. originalCam.fov = newFov;
  72795. originalCam.updateMatrixWorld();
  72796. originalCam.updateProjectionMatrix();
  72797. shearCam.copy(originalCam);
  72798. shearCam.rotation.set(...originalCam.rotation.toArray());
  72799. shearCam.updateMatrixWorld();
  72800. shearCam.projectionMatrix.copy(originalCam.projectionMatrix);
  72801. const [sx, sy] = this.shear;
  72802. const mShear = new Matrix4().set(
  72803. 1, 0, sx, 0,
  72804. 0, 1, sy, 0,
  72805. 0, 0, 1, 0,
  72806. 0, 0, 0, 1,
  72807. );
  72808. const proj = shearCam.projectionMatrix;
  72809. proj.multiply(mShear);
  72810. shearCam.projectionMatrixInverse.copy(proj).invert();
  72811. let total = shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  72812. this.fovDelta *= attenuation;
  72813. }
  72814. };
  72815. // https://support.pix4d.com/hc/en-us/articles/205675256-How-are-yaw-pitch-roll-defined
  72816. // https://support.pix4d.com/hc/en-us/articles/202558969-How-are-omega-phi-kappa-defined
  72817. function createMaterial(){
  72818. let vertexShader = `
  72819. uniform float uNear;
  72820. varying vec2 vUV;
  72821. varying vec4 vDebug;
  72822. void main(){
  72823. vDebug = vec4(0.0, 1.0, 0.0, 1.0);
  72824. vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
  72825. // make sure that this mesh is at least in front of the near plane
  72826. modelViewPosition.xyz += normalize(modelViewPosition.xyz) * uNear;
  72827. gl_Position = projectionMatrix * modelViewPosition;
  72828. vUV = uv;
  72829. }
  72830. `;
  72831. let fragmentShader = `
  72832. uniform sampler2D tColor;
  72833. uniform float uOpacity;
  72834. varying vec2 vUV;
  72835. varying vec4 vDebug;
  72836. void main(){
  72837. vec4 color = texture2D(tColor, vUV);
  72838. gl_FragColor = color;
  72839. gl_FragColor.a = uOpacity;
  72840. }
  72841. `;
  72842. const material = new ShaderMaterial( {
  72843. uniforms: {
  72844. // time: { value: 1.0 },
  72845. // resolution: { value: new THREE.Vector2() }
  72846. tColor: {value: new Texture() },
  72847. uNear: {value: 0.0},
  72848. uOpacity: {value: 1.0},
  72849. },
  72850. vertexShader: vertexShader,
  72851. fragmentShader: fragmentShader,
  72852. side: DoubleSide,
  72853. } );
  72854. material.side = DoubleSide;
  72855. return material;
  72856. }
  72857. const planeGeometry = new PlaneGeometry(1, 1);
  72858. const lineGeometry = new Geometry();
  72859. lineGeometry.vertices.push(
  72860. new Vector3(-0.5, -0.5, 0),
  72861. new Vector3( 0.5, -0.5, 0),
  72862. new Vector3( 0.5, 0.5, 0),
  72863. new Vector3(-0.5, 0.5, 0),
  72864. new Vector3(-0.5, -0.5, 0),
  72865. );
  72866. class OrientedImage{
  72867. constructor(id){
  72868. this.id = id;
  72869. this.fov = 1.0;
  72870. this.position = new Vector3();
  72871. this.rotation = new Vector3();
  72872. this.width = 0;
  72873. this.height = 0;
  72874. this.fov = 1.0;
  72875. const material = createMaterial();
  72876. const lineMaterial = new LineBasicMaterial( { color: 0x00ff00 } );
  72877. this.mesh = new Mesh(planeGeometry, material);
  72878. this.line = new Line(lineGeometry, lineMaterial);
  72879. this.texture = null;
  72880. this.mesh.orientedImage = this;
  72881. }
  72882. set(position, rotation, dimension, fov){
  72883. let radians = rotation.map(MathUtils.degToRad);
  72884. this.position.set(...position);
  72885. this.mesh.position.set(...position);
  72886. this.rotation.set(...radians);
  72887. this.mesh.rotation.set(...radians);
  72888. [this.width, this.height] = dimension;
  72889. this.mesh.scale.set(this.width / this.height, 1, 1);
  72890. this.fov = fov;
  72891. this.updateTransform();
  72892. }
  72893. updateTransform(){
  72894. let {mesh, line, fov} = this;
  72895. mesh.updateMatrixWorld();
  72896. const dir = mesh.getWorldDirection();
  72897. const alpha = MathUtils.degToRad(fov / 2);
  72898. const d = -0.5 / Math.tan(alpha);
  72899. const move = dir.clone().multiplyScalar(d);
  72900. mesh.position.add(move);
  72901. line.position.copy(mesh.position);
  72902. line.scale.copy(mesh.scale);
  72903. line.rotation.copy(mesh.rotation);
  72904. }
  72905. };
  72906. class OrientedImages extends EventDispatcher$1{
  72907. constructor(){
  72908. super();
  72909. this.node = null;
  72910. this.cameraParams = null;
  72911. this.imageParams = null;
  72912. this.images = null;
  72913. this._visible = true;
  72914. }
  72915. set visible(visible){
  72916. if(this._visible === visible){
  72917. return;
  72918. }
  72919. for(const image of this.images){
  72920. image.mesh.visible = visible;
  72921. image.line.visible = visible;
  72922. }
  72923. this._visible = visible;
  72924. this.dispatchEvent({
  72925. type: "visibility_changed",
  72926. images: this,
  72927. });
  72928. }
  72929. get visible(){
  72930. return this._visible;
  72931. }
  72932. };
  72933. class OrientedImageLoader{
  72934. static async loadCameraParams(path){
  72935. const res = await fetch(path);
  72936. const text = await res.text();
  72937. const parser = new DOMParser();
  72938. const doc = parser.parseFromString(text, "application/xml");
  72939. const width = parseInt(doc.getElementsByTagName("width")[0].textContent);
  72940. const height = parseInt(doc.getElementsByTagName("height")[0].textContent);
  72941. const f = parseFloat(doc.getElementsByTagName("f")[0].textContent);
  72942. let a = (height / 2) / f;
  72943. let fov = 2 * MathUtils.radToDeg(Math.atan(a));
  72944. const params = {
  72945. path: path,
  72946. width: width,
  72947. height: height,
  72948. f: f,
  72949. fov: fov,
  72950. };
  72951. return params;
  72952. }
  72953. static async loadImageParams(path){
  72954. const response = await fetch(path);
  72955. if(!response.ok){
  72956. console.error(`failed to load ${path}`);
  72957. return;
  72958. }
  72959. const content = await response.text();
  72960. const lines = content.split(/\r?\n/);
  72961. const imageParams = [];
  72962. for(let i = 1; i < lines.length; i++){
  72963. const line = lines[i];
  72964. if(line.startsWith("#")){
  72965. continue;
  72966. }
  72967. const tokens = line.split(/\s+/);
  72968. if(tokens.length < 6){
  72969. continue;
  72970. }
  72971. const params = {
  72972. id: tokens[0],
  72973. x: Number.parseFloat(tokens[1]),
  72974. y: Number.parseFloat(tokens[2]),
  72975. z: Number.parseFloat(tokens[3]),
  72976. omega: Number.parseFloat(tokens[4]),
  72977. phi: Number.parseFloat(tokens[5]),
  72978. kappa: Number.parseFloat(tokens[6]),
  72979. };
  72980. // const whitelist = ["47518.jpg"];
  72981. // if(whitelist.includes(params.id)){
  72982. // imageParams.push(params);
  72983. // }
  72984. imageParams.push(params);
  72985. }
  72986. // debug
  72987. //return [imageParams[50]];
  72988. return imageParams;
  72989. }
  72990. static async load(cameraParamsPath, imageParamsPath, viewer){
  72991. const tStart = performance.now();
  72992. const [cameraParams, imageParams] = await Promise.all([
  72993. OrientedImageLoader.loadCameraParams(cameraParamsPath),
  72994. OrientedImageLoader.loadImageParams(imageParamsPath),
  72995. ]);
  72996. const orientedImageControls = new OrientedImageControls(viewer);
  72997. const raycaster = new Raycaster();
  72998. const tEnd = performance.now();
  72999. console.log(tEnd - tStart);
  73000. // const sp = new THREE.PlaneGeometry(1, 1);
  73001. // const lg = new THREE.Geometry();
  73002. // lg.vertices.push(
  73003. // new THREE.Vector3(-0.5, -0.5, 0),
  73004. // new THREE.Vector3( 0.5, -0.5, 0),
  73005. // new THREE.Vector3( 0.5, 0.5, 0),
  73006. // new THREE.Vector3(-0.5, 0.5, 0),
  73007. // new THREE.Vector3(-0.5, -0.5, 0),
  73008. // );
  73009. const {width, height} = cameraParams;
  73010. const orientedImages = [];
  73011. const sceneNode = new Object3D();
  73012. sceneNode.name = "oriented_images";
  73013. for(const params of imageParams){
  73014. // const material = createMaterial();
  73015. // const lm = new THREE.LineBasicMaterial( { color: 0x00ff00 } );
  73016. // const mesh = new THREE.Mesh(sp, material);
  73017. const {x, y, z, omega, phi, kappa} = params;
  73018. // const [rx, ry, rz] = [omega, phi, kappa]
  73019. // .map(THREE.Math.degToRad);
  73020. // mesh.position.set(x, y, z);
  73021. // mesh.scale.set(width / height, 1, 1);
  73022. // mesh.rotation.set(rx, ry, rz);
  73023. // {
  73024. // mesh.updateMatrixWorld();
  73025. // const dir = mesh.getWorldDirection();
  73026. // const alpha = THREE.Math.degToRad(cameraParams.fov / 2);
  73027. // const d = -0.5 / Math.tan(alpha);
  73028. // const move = dir.clone().multiplyScalar(d);
  73029. // mesh.position.add(move);
  73030. // }
  73031. // sceneNode.add(mesh);
  73032. // const line = new THREE.Line(lg, lm);
  73033. // line.position.copy(mesh.position);
  73034. // line.scale.copy(mesh.scale);
  73035. // line.rotation.copy(mesh.rotation);
  73036. // sceneNode.add(line);
  73037. let orientedImage = new OrientedImage(params.id);
  73038. // orientedImage.setPosition(x, y, z);
  73039. // orientedImage.setRotation(omega, phi, kappa);
  73040. // orientedImage.setDimension(width, height);
  73041. let position = [x, y, z];
  73042. let rotation = [omega, phi, kappa];
  73043. let dimension = [width, height];
  73044. orientedImage.set(position, rotation, dimension, cameraParams.fov);
  73045. sceneNode.add(orientedImage.mesh);
  73046. sceneNode.add(orientedImage.line);
  73047. orientedImages.push(orientedImage);
  73048. }
  73049. let hoveredElement = null;
  73050. let clipVolume = null;
  73051. const onMouseMove = (evt) => {
  73052. const tStart = performance.now();
  73053. if(hoveredElement){
  73054. hoveredElement.line.material.color.setRGB(0, 1, 0);
  73055. }
  73056. evt.preventDefault();
  73057. //var array = getMousePosition( container, evt.clientX, evt.clientY );
  73058. const rect = viewer.renderer.domElement.getBoundingClientRect();
  73059. const [x, y] = [evt.clientX, evt.clientY];
  73060. const array = [
  73061. ( x - rect.left ) / rect.width,
  73062. ( y - rect.top ) / rect.height
  73063. ];
  73064. const onClickPosition = new Vector2(...array);
  73065. //const intersects = getIntersects(onClickPosition, scene.children);
  73066. const camera = viewer.scene.getActiveCamera();
  73067. const mouse = new Vector3(
  73068. + ( onClickPosition.x * 2 ) - 1,
  73069. - ( onClickPosition.y * 2 ) + 1 );
  73070. const objects = orientedImages.map(i => i.mesh);
  73071. raycaster.setFromCamera( mouse, camera );
  73072. const intersects = raycaster.intersectObjects( objects );
  73073. let selectionChanged = false;
  73074. if ( intersects.length > 0){
  73075. //console.log(intersects);
  73076. const intersection = intersects[0];
  73077. const orientedImage = intersection.object.orientedImage;
  73078. orientedImage.line.material.color.setRGB(1, 0, 0);
  73079. selectionChanged = hoveredElement !== orientedImage;
  73080. hoveredElement = orientedImage;
  73081. }else {
  73082. hoveredElement = null;
  73083. }
  73084. let shouldRemoveClipVolume = clipVolume !== null && hoveredElement === null;
  73085. let shouldAddClipVolume = clipVolume === null && hoveredElement !== null;
  73086. if(clipVolume !== null && (hoveredElement === null || selectionChanged)){
  73087. // remove existing
  73088. viewer.scene.removePolygonClipVolume(clipVolume);
  73089. clipVolume = null;
  73090. }
  73091. if(shouldAddClipVolume || selectionChanged){
  73092. const img = hoveredElement;
  73093. const fov = cameraParams.fov;
  73094. const aspect = cameraParams.width / cameraParams.height;
  73095. const near = 1.0;
  73096. const far = 1000 * 1000;
  73097. const camera = new PerspectiveCamera(fov, aspect, near, far);
  73098. camera.rotation.order = viewer.scene.getActiveCamera().rotation.order;
  73099. camera.rotation.copy(img.mesh.rotation);
  73100. {
  73101. const mesh = img.mesh;
  73102. const dir = mesh.getWorldDirection();
  73103. const pos = mesh.position;
  73104. const alpha = MathUtils.degToRad(fov / 2);
  73105. const d = 0.5 / Math.tan(alpha);
  73106. const newCamPos = pos.clone().add(dir.clone().multiplyScalar(d));
  73107. const newCamDir = pos.clone().sub(newCamPos);
  73108. const newCamTarget = new Vector3().addVectors(
  73109. newCamPos,
  73110. newCamDir.clone().multiplyScalar(viewer.getMoveSpeed()));
  73111. camera.position.copy(newCamPos);
  73112. }
  73113. let volume = new Potree.PolygonClipVolume(camera);
  73114. let m0 = new Mesh();
  73115. let m1 = new Mesh();
  73116. let m2 = new Mesh();
  73117. let m3 = new Mesh();
  73118. m0.position.set(-1, -1, 0);
  73119. m1.position.set( 1, -1, 0);
  73120. m2.position.set( 1, 1, 0);
  73121. m3.position.set(-1, 1, 0);
  73122. volume.markers.push(m0, m1, m2, m3);
  73123. volume.initialized = true;
  73124. viewer.scene.addPolygonClipVolume(volume);
  73125. clipVolume = volume;
  73126. }
  73127. const tEnd = performance.now();
  73128. //console.log(tEnd - tStart);
  73129. };
  73130. const moveToImage = (image) => {
  73131. console.log("move to image " + image.id);
  73132. const mesh = image.mesh;
  73133. const newCamPos = image.position.clone();
  73134. const newCamTarget = mesh.position.clone();
  73135. viewer.scene.view.setView(newCamPos, newCamTarget, 500, () => {
  73136. orientedImageControls.capture(image);
  73137. });
  73138. if(image.texture === null){
  73139. const target = image;
  73140. const tmpImagePath = `${Potree.resourcePath}/images/loading.jpg`;
  73141. new TextureLoader().load(tmpImagePath,
  73142. (texture) => {
  73143. if(target.texture === null){
  73144. target.texture = texture;
  73145. target.mesh.material.uniforms.tColor.value = texture;
  73146. mesh.material.needsUpdate = true;
  73147. }
  73148. }
  73149. );
  73150. const imagePath = `${imageParamsPath}/../${target.id}`;
  73151. new TextureLoader().load(imagePath,
  73152. (texture) => {
  73153. target.texture = texture;
  73154. target.mesh.material.uniforms.tColor.value = texture;
  73155. mesh.material.needsUpdate = true;
  73156. }
  73157. );
  73158. }
  73159. };
  73160. const onMouseClick = (evt) => {
  73161. if(orientedImageControls.hasSomethingCaptured()){
  73162. return;
  73163. }
  73164. if(hoveredElement){
  73165. moveToImage(hoveredElement);
  73166. }
  73167. };
  73168. viewer.renderer.domElement.addEventListener( 'mousemove', onMouseMove, false );
  73169. viewer.renderer.domElement.addEventListener( 'mousedown', onMouseClick, false );
  73170. viewer.addEventListener("update", () => {
  73171. for(const image of orientedImages){
  73172. const world = image.mesh.matrixWorld;
  73173. const {width, height} = image;
  73174. const aspect = width / height;
  73175. const camera = viewer.scene.getActiveCamera();
  73176. const imgPos = image.mesh.getWorldPosition(new Vector3());
  73177. const camPos = camera.position;
  73178. const d = camPos.distanceTo(imgPos);
  73179. const minSize = 1; // in degrees of fov
  73180. const a = MathUtils.degToRad(minSize);
  73181. let r = d * Math.tan(a);
  73182. r = Math.max(r, 1);
  73183. image.mesh.scale.set(r * aspect, r, 1);
  73184. image.line.scale.set(r * aspect, r, 1);
  73185. image.mesh.material.uniforms.uNear.value = camera.near;
  73186. }
  73187. });
  73188. const images = new OrientedImages();
  73189. images.node = sceneNode;
  73190. images.cameraParamsPath = cameraParamsPath;
  73191. images.imageParamsPath = imageParamsPath;
  73192. images.cameraParams = cameraParams;
  73193. images.imageParams = imageParams;
  73194. images.images = orientedImages;
  73195. Potree.debug.moveToImage = moveToImage;
  73196. return images;
  73197. }
  73198. }
  73199. // This is a generated file. Do not edit.
  73200. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
  73201. 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]/;
  73202. 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]/;
  73203. var unicode = {
  73204. Space_Separator: Space_Separator,
  73205. ID_Start: ID_Start,
  73206. ID_Continue: ID_Continue
  73207. };
  73208. var util = {
  73209. isSpaceSeparator (c) {
  73210. return typeof c === 'string' && unicode.Space_Separator.test(c)
  73211. },
  73212. isIdStartChar (c) {
  73213. return typeof c === 'string' && (
  73214. (c >= 'a' && c <= 'z') ||
  73215. (c >= 'A' && c <= 'Z') ||
  73216. (c === '$') || (c === '_') ||
  73217. unicode.ID_Start.test(c)
  73218. )
  73219. },
  73220. isIdContinueChar (c) {
  73221. return typeof c === 'string' && (
  73222. (c >= 'a' && c <= 'z') ||
  73223. (c >= 'A' && c <= 'Z') ||
  73224. (c >= '0' && c <= '9') ||
  73225. (c === '$') || (c === '_') ||
  73226. (c === '\u200C') || (c === '\u200D') ||
  73227. unicode.ID_Continue.test(c)
  73228. )
  73229. },
  73230. isDigit (c) {
  73231. return typeof c === 'string' && /[0-9]/.test(c)
  73232. },
  73233. isHexDigit (c) {
  73234. return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
  73235. },
  73236. };
  73237. let source;
  73238. let parseState;
  73239. let stack$1;
  73240. let pos;
  73241. let line;
  73242. let column;
  73243. let token;
  73244. let key;
  73245. let root;
  73246. var parse = function parse (text, reviver) {
  73247. source = String(text);
  73248. parseState = 'start';
  73249. stack$1 = [];
  73250. pos = 0;
  73251. line = 1;
  73252. column = 0;
  73253. token = undefined;
  73254. key = undefined;
  73255. root = undefined;
  73256. do {
  73257. token = lex();
  73258. // This code is unreachable.
  73259. // if (!parseStates[parseState]) {
  73260. // throw invalidParseState()
  73261. // }
  73262. parseStates[parseState]();
  73263. } while (token.type !== 'eof')
  73264. if (typeof reviver === 'function') {
  73265. return internalize({'': root}, '', reviver)
  73266. }
  73267. return root
  73268. };
  73269. function internalize (holder, name, reviver) {
  73270. const value = holder[name];
  73271. if (value != null && typeof value === 'object') {
  73272. for (const key in value) {
  73273. const replacement = internalize(value, key, reviver);
  73274. if (replacement === undefined) {
  73275. delete value[key];
  73276. } else {
  73277. value[key] = replacement;
  73278. }
  73279. }
  73280. }
  73281. return reviver.call(holder, name, value)
  73282. }
  73283. let lexState;
  73284. let buffer;
  73285. let doubleQuote;
  73286. let sign$1;
  73287. let c$1;
  73288. function lex () {
  73289. lexState = 'default';
  73290. buffer = '';
  73291. doubleQuote = false;
  73292. sign$1 = 1;
  73293. for (;;) {
  73294. c$1 = peek();
  73295. // This code is unreachable.
  73296. // if (!lexStates[lexState]) {
  73297. // throw invalidLexState(lexState)
  73298. // }
  73299. const token = lexStates[lexState]();
  73300. if (token) {
  73301. return token
  73302. }
  73303. }
  73304. }
  73305. function peek () {
  73306. if (source[pos]) {
  73307. return String.fromCodePoint(source.codePointAt(pos))
  73308. }
  73309. }
  73310. function read () {
  73311. const c = peek();
  73312. if (c === '\n') {
  73313. line++;
  73314. column = 0;
  73315. } else if (c) {
  73316. column += c.length;
  73317. } else {
  73318. column++;
  73319. }
  73320. if (c) {
  73321. pos += c.length;
  73322. }
  73323. return c
  73324. }
  73325. const lexStates = {
  73326. default () {
  73327. switch (c$1) {
  73328. case '\t':
  73329. case '\v':
  73330. case '\f':
  73331. case ' ':
  73332. case '\u00A0':
  73333. case '\uFEFF':
  73334. case '\n':
  73335. case '\r':
  73336. case '\u2028':
  73337. case '\u2029':
  73338. read();
  73339. return
  73340. case '/':
  73341. read();
  73342. lexState = 'comment';
  73343. return
  73344. case undefined:
  73345. read();
  73346. return newToken('eof')
  73347. }
  73348. if (util.isSpaceSeparator(c$1)) {
  73349. read();
  73350. return
  73351. }
  73352. // This code is unreachable.
  73353. // if (!lexStates[parseState]) {
  73354. // throw invalidLexState(parseState)
  73355. // }
  73356. return lexStates[parseState]()
  73357. },
  73358. comment () {
  73359. switch (c$1) {
  73360. case '*':
  73361. read();
  73362. lexState = 'multiLineComment';
  73363. return
  73364. case '/':
  73365. read();
  73366. lexState = 'singleLineComment';
  73367. return
  73368. }
  73369. throw invalidChar(read())
  73370. },
  73371. multiLineComment () {
  73372. switch (c$1) {
  73373. case '*':
  73374. read();
  73375. lexState = 'multiLineCommentAsterisk';
  73376. return
  73377. case undefined:
  73378. throw invalidChar(read())
  73379. }
  73380. read();
  73381. },
  73382. multiLineCommentAsterisk () {
  73383. switch (c$1) {
  73384. case '*':
  73385. read();
  73386. return
  73387. case '/':
  73388. read();
  73389. lexState = 'default';
  73390. return
  73391. case undefined:
  73392. throw invalidChar(read())
  73393. }
  73394. read();
  73395. lexState = 'multiLineComment';
  73396. },
  73397. singleLineComment () {
  73398. switch (c$1) {
  73399. case '\n':
  73400. case '\r':
  73401. case '\u2028':
  73402. case '\u2029':
  73403. read();
  73404. lexState = 'default';
  73405. return
  73406. case undefined:
  73407. read();
  73408. return newToken('eof')
  73409. }
  73410. read();
  73411. },
  73412. value () {
  73413. switch (c$1) {
  73414. case '{':
  73415. case '[':
  73416. return newToken('punctuator', read())
  73417. case 'n':
  73418. read();
  73419. literal('ull');
  73420. return newToken('null', null)
  73421. case 't':
  73422. read();
  73423. literal('rue');
  73424. return newToken('boolean', true)
  73425. case 'f':
  73426. read();
  73427. literal('alse');
  73428. return newToken('boolean', false)
  73429. case '-':
  73430. case '+':
  73431. if (read() === '-') {
  73432. sign$1 = -1;
  73433. }
  73434. lexState = 'sign';
  73435. return
  73436. case '.':
  73437. buffer = read();
  73438. lexState = 'decimalPointLeading';
  73439. return
  73440. case '0':
  73441. buffer = read();
  73442. lexState = 'zero';
  73443. return
  73444. case '1':
  73445. case '2':
  73446. case '3':
  73447. case '4':
  73448. case '5':
  73449. case '6':
  73450. case '7':
  73451. case '8':
  73452. case '9':
  73453. buffer = read();
  73454. lexState = 'decimalInteger';
  73455. return
  73456. case 'I':
  73457. read();
  73458. literal('nfinity');
  73459. return newToken('numeric', Infinity)
  73460. case 'N':
  73461. read();
  73462. literal('aN');
  73463. return newToken('numeric', NaN)
  73464. case '"':
  73465. case "'":
  73466. doubleQuote = (read() === '"');
  73467. buffer = '';
  73468. lexState = 'string';
  73469. return
  73470. }
  73471. throw invalidChar(read())
  73472. },
  73473. identifierNameStartEscape () {
  73474. if (c$1 !== 'u') {
  73475. throw invalidChar(read())
  73476. }
  73477. read();
  73478. const u = unicodeEscape();
  73479. switch (u) {
  73480. case '$':
  73481. case '_':
  73482. break
  73483. default:
  73484. if (!util.isIdStartChar(u)) {
  73485. throw invalidIdentifier()
  73486. }
  73487. break
  73488. }
  73489. buffer += u;
  73490. lexState = 'identifierName';
  73491. },
  73492. identifierName () {
  73493. switch (c$1) {
  73494. case '$':
  73495. case '_':
  73496. case '\u200C':
  73497. case '\u200D':
  73498. buffer += read();
  73499. return
  73500. case '\\':
  73501. read();
  73502. lexState = 'identifierNameEscape';
  73503. return
  73504. }
  73505. if (util.isIdContinueChar(c$1)) {
  73506. buffer += read();
  73507. return
  73508. }
  73509. return newToken('identifier', buffer)
  73510. },
  73511. identifierNameEscape () {
  73512. if (c$1 !== 'u') {
  73513. throw invalidChar(read())
  73514. }
  73515. read();
  73516. const u = unicodeEscape();
  73517. switch (u) {
  73518. case '$':
  73519. case '_':
  73520. case '\u200C':
  73521. case '\u200D':
  73522. break
  73523. default:
  73524. if (!util.isIdContinueChar(u)) {
  73525. throw invalidIdentifier()
  73526. }
  73527. break
  73528. }
  73529. buffer += u;
  73530. lexState = 'identifierName';
  73531. },
  73532. sign () {
  73533. switch (c$1) {
  73534. case '.':
  73535. buffer = read();
  73536. lexState = 'decimalPointLeading';
  73537. return
  73538. case '0':
  73539. buffer = read();
  73540. lexState = 'zero';
  73541. return
  73542. case '1':
  73543. case '2':
  73544. case '3':
  73545. case '4':
  73546. case '5':
  73547. case '6':
  73548. case '7':
  73549. case '8':
  73550. case '9':
  73551. buffer = read();
  73552. lexState = 'decimalInteger';
  73553. return
  73554. case 'I':
  73555. read();
  73556. literal('nfinity');
  73557. return newToken('numeric', sign$1 * Infinity)
  73558. case 'N':
  73559. read();
  73560. literal('aN');
  73561. return newToken('numeric', NaN)
  73562. }
  73563. throw invalidChar(read())
  73564. },
  73565. zero () {
  73566. switch (c$1) {
  73567. case '.':
  73568. buffer += read();
  73569. lexState = 'decimalPoint';
  73570. return
  73571. case 'e':
  73572. case 'E':
  73573. buffer += read();
  73574. lexState = 'decimalExponent';
  73575. return
  73576. case 'x':
  73577. case 'X':
  73578. buffer += read();
  73579. lexState = 'hexadecimal';
  73580. return
  73581. }
  73582. return newToken('numeric', sign$1 * 0)
  73583. },
  73584. decimalInteger () {
  73585. switch (c$1) {
  73586. case '.':
  73587. buffer += read();
  73588. lexState = 'decimalPoint';
  73589. return
  73590. case 'e':
  73591. case 'E':
  73592. buffer += read();
  73593. lexState = 'decimalExponent';
  73594. return
  73595. }
  73596. if (util.isDigit(c$1)) {
  73597. buffer += read();
  73598. return
  73599. }
  73600. return newToken('numeric', sign$1 * Number(buffer))
  73601. },
  73602. decimalPointLeading () {
  73603. if (util.isDigit(c$1)) {
  73604. buffer += read();
  73605. lexState = 'decimalFraction';
  73606. return
  73607. }
  73608. throw invalidChar(read())
  73609. },
  73610. decimalPoint () {
  73611. switch (c$1) {
  73612. case 'e':
  73613. case 'E':
  73614. buffer += read();
  73615. lexState = 'decimalExponent';
  73616. return
  73617. }
  73618. if (util.isDigit(c$1)) {
  73619. buffer += read();
  73620. lexState = 'decimalFraction';
  73621. return
  73622. }
  73623. return newToken('numeric', sign$1 * Number(buffer))
  73624. },
  73625. decimalFraction () {
  73626. switch (c$1) {
  73627. case 'e':
  73628. case 'E':
  73629. buffer += read();
  73630. lexState = 'decimalExponent';
  73631. return
  73632. }
  73633. if (util.isDigit(c$1)) {
  73634. buffer += read();
  73635. return
  73636. }
  73637. return newToken('numeric', sign$1 * Number(buffer))
  73638. },
  73639. decimalExponent () {
  73640. switch (c$1) {
  73641. case '+':
  73642. case '-':
  73643. buffer += read();
  73644. lexState = 'decimalExponentSign';
  73645. return
  73646. }
  73647. if (util.isDigit(c$1)) {
  73648. buffer += read();
  73649. lexState = 'decimalExponentInteger';
  73650. return
  73651. }
  73652. throw invalidChar(read())
  73653. },
  73654. decimalExponentSign () {
  73655. if (util.isDigit(c$1)) {
  73656. buffer += read();
  73657. lexState = 'decimalExponentInteger';
  73658. return
  73659. }
  73660. throw invalidChar(read())
  73661. },
  73662. decimalExponentInteger () {
  73663. if (util.isDigit(c$1)) {
  73664. buffer += read();
  73665. return
  73666. }
  73667. return newToken('numeric', sign$1 * Number(buffer))
  73668. },
  73669. hexadecimal () {
  73670. if (util.isHexDigit(c$1)) {
  73671. buffer += read();
  73672. lexState = 'hexadecimalInteger';
  73673. return
  73674. }
  73675. throw invalidChar(read())
  73676. },
  73677. hexadecimalInteger () {
  73678. if (util.isHexDigit(c$1)) {
  73679. buffer += read();
  73680. return
  73681. }
  73682. return newToken('numeric', sign$1 * Number(buffer))
  73683. },
  73684. string () {
  73685. switch (c$1) {
  73686. case '\\':
  73687. read();
  73688. buffer += escape$1();
  73689. return
  73690. case '"':
  73691. if (doubleQuote) {
  73692. read();
  73693. return newToken('string', buffer)
  73694. }
  73695. buffer += read();
  73696. return
  73697. case "'":
  73698. if (!doubleQuote) {
  73699. read();
  73700. return newToken('string', buffer)
  73701. }
  73702. buffer += read();
  73703. return
  73704. case '\n':
  73705. case '\r':
  73706. throw invalidChar(read())
  73707. case '\u2028':
  73708. case '\u2029':
  73709. separatorChar(c$1);
  73710. break
  73711. case undefined:
  73712. throw invalidChar(read())
  73713. }
  73714. buffer += read();
  73715. },
  73716. start () {
  73717. switch (c$1) {
  73718. case '{':
  73719. case '[':
  73720. return newToken('punctuator', read())
  73721. // This code is unreachable since the default lexState handles eof.
  73722. // case undefined:
  73723. // return newToken('eof')
  73724. }
  73725. lexState = 'value';
  73726. },
  73727. beforePropertyName () {
  73728. switch (c$1) {
  73729. case '$':
  73730. case '_':
  73731. buffer = read();
  73732. lexState = 'identifierName';
  73733. return
  73734. case '\\':
  73735. read();
  73736. lexState = 'identifierNameStartEscape';
  73737. return
  73738. case '}':
  73739. return newToken('punctuator', read())
  73740. case '"':
  73741. case "'":
  73742. doubleQuote = (read() === '"');
  73743. lexState = 'string';
  73744. return
  73745. }
  73746. if (util.isIdStartChar(c$1)) {
  73747. buffer += read();
  73748. lexState = 'identifierName';
  73749. return
  73750. }
  73751. throw invalidChar(read())
  73752. },
  73753. afterPropertyName () {
  73754. if (c$1 === ':') {
  73755. return newToken('punctuator', read())
  73756. }
  73757. throw invalidChar(read())
  73758. },
  73759. beforePropertyValue () {
  73760. lexState = 'value';
  73761. },
  73762. afterPropertyValue () {
  73763. switch (c$1) {
  73764. case ',':
  73765. case '}':
  73766. return newToken('punctuator', read())
  73767. }
  73768. throw invalidChar(read())
  73769. },
  73770. beforeArrayValue () {
  73771. if (c$1 === ']') {
  73772. return newToken('punctuator', read())
  73773. }
  73774. lexState = 'value';
  73775. },
  73776. afterArrayValue () {
  73777. switch (c$1) {
  73778. case ',':
  73779. case ']':
  73780. return newToken('punctuator', read())
  73781. }
  73782. throw invalidChar(read())
  73783. },
  73784. end () {
  73785. // This code is unreachable since it's handled by the default lexState.
  73786. // if (c === undefined) {
  73787. // read()
  73788. // return newToken('eof')
  73789. // }
  73790. throw invalidChar(read())
  73791. },
  73792. };
  73793. function newToken (type, value) {
  73794. return {
  73795. type,
  73796. value,
  73797. line,
  73798. column,
  73799. }
  73800. }
  73801. function literal (s) {
  73802. for (const c of s) {
  73803. const p = peek();
  73804. if (p !== c) {
  73805. throw invalidChar(read())
  73806. }
  73807. read();
  73808. }
  73809. }
  73810. function escape$1 () {
  73811. const c = peek();
  73812. switch (c) {
  73813. case 'b':
  73814. read();
  73815. return '\b'
  73816. case 'f':
  73817. read();
  73818. return '\f'
  73819. case 'n':
  73820. read();
  73821. return '\n'
  73822. case 'r':
  73823. read();
  73824. return '\r'
  73825. case 't':
  73826. read();
  73827. return '\t'
  73828. case 'v':
  73829. read();
  73830. return '\v'
  73831. case '0':
  73832. read();
  73833. if (util.isDigit(peek())) {
  73834. throw invalidChar(read())
  73835. }
  73836. return '\0'
  73837. case 'x':
  73838. read();
  73839. return hexEscape()
  73840. case 'u':
  73841. read();
  73842. return unicodeEscape()
  73843. case '\n':
  73844. case '\u2028':
  73845. case '\u2029':
  73846. read();
  73847. return ''
  73848. case '\r':
  73849. read();
  73850. if (peek() === '\n') {
  73851. read();
  73852. }
  73853. return ''
  73854. case '1':
  73855. case '2':
  73856. case '3':
  73857. case '4':
  73858. case '5':
  73859. case '6':
  73860. case '7':
  73861. case '8':
  73862. case '9':
  73863. throw invalidChar(read())
  73864. case undefined:
  73865. throw invalidChar(read())
  73866. }
  73867. return read()
  73868. }
  73869. function hexEscape () {
  73870. let buffer = '';
  73871. let c = peek();
  73872. if (!util.isHexDigit(c)) {
  73873. throw invalidChar(read())
  73874. }
  73875. buffer += read();
  73876. c = peek();
  73877. if (!util.isHexDigit(c)) {
  73878. throw invalidChar(read())
  73879. }
  73880. buffer += read();
  73881. return String.fromCodePoint(parseInt(buffer, 16))
  73882. }
  73883. function unicodeEscape () {
  73884. let buffer = '';
  73885. let count = 4;
  73886. while (count-- > 0) {
  73887. const c = peek();
  73888. if (!util.isHexDigit(c)) {
  73889. throw invalidChar(read())
  73890. }
  73891. buffer += read();
  73892. }
  73893. return String.fromCodePoint(parseInt(buffer, 16))
  73894. }
  73895. const parseStates = {
  73896. start () {
  73897. if (token.type === 'eof') {
  73898. throw invalidEOF()
  73899. }
  73900. push();
  73901. },
  73902. beforePropertyName () {
  73903. switch (token.type) {
  73904. case 'identifier':
  73905. case 'string':
  73906. key = token.value;
  73907. parseState = 'afterPropertyName';
  73908. return
  73909. case 'punctuator':
  73910. // This code is unreachable since it's handled by the lexState.
  73911. // if (token.value !== '}') {
  73912. // throw invalidToken()
  73913. // }
  73914. pop();
  73915. return
  73916. case 'eof':
  73917. throw invalidEOF()
  73918. }
  73919. // This code is unreachable since it's handled by the lexState.
  73920. // throw invalidToken()
  73921. },
  73922. afterPropertyName () {
  73923. // This code is unreachable since it's handled by the lexState.
  73924. // if (token.type !== 'punctuator' || token.value !== ':') {
  73925. // throw invalidToken()
  73926. // }
  73927. if (token.type === 'eof') {
  73928. throw invalidEOF()
  73929. }
  73930. parseState = 'beforePropertyValue';
  73931. },
  73932. beforePropertyValue () {
  73933. if (token.type === 'eof') {
  73934. throw invalidEOF()
  73935. }
  73936. push();
  73937. },
  73938. beforeArrayValue () {
  73939. if (token.type === 'eof') {
  73940. throw invalidEOF()
  73941. }
  73942. if (token.type === 'punctuator' && token.value === ']') {
  73943. pop();
  73944. return
  73945. }
  73946. push();
  73947. },
  73948. afterPropertyValue () {
  73949. // This code is unreachable since it's handled by the lexState.
  73950. // if (token.type !== 'punctuator') {
  73951. // throw invalidToken()
  73952. // }
  73953. if (token.type === 'eof') {
  73954. throw invalidEOF()
  73955. }
  73956. switch (token.value) {
  73957. case ',':
  73958. parseState = 'beforePropertyName';
  73959. return
  73960. case '}':
  73961. pop();
  73962. }
  73963. // This code is unreachable since it's handled by the lexState.
  73964. // throw invalidToken()
  73965. },
  73966. afterArrayValue () {
  73967. // This code is unreachable since it's handled by the lexState.
  73968. // if (token.type !== 'punctuator') {
  73969. // throw invalidToken()
  73970. // }
  73971. if (token.type === 'eof') {
  73972. throw invalidEOF()
  73973. }
  73974. switch (token.value) {
  73975. case ',':
  73976. parseState = 'beforeArrayValue';
  73977. return
  73978. case ']':
  73979. pop();
  73980. }
  73981. // This code is unreachable since it's handled by the lexState.
  73982. // throw invalidToken()
  73983. },
  73984. end () {
  73985. // This code is unreachable since it's handled by the lexState.
  73986. // if (token.type !== 'eof') {
  73987. // throw invalidToken()
  73988. // }
  73989. },
  73990. };
  73991. function push () {
  73992. let value;
  73993. switch (token.type) {
  73994. case 'punctuator':
  73995. switch (token.value) {
  73996. case '{':
  73997. value = {};
  73998. break
  73999. case '[':
  74000. value = [];
  74001. break
  74002. }
  74003. break
  74004. case 'null':
  74005. case 'boolean':
  74006. case 'numeric':
  74007. case 'string':
  74008. value = token.value;
  74009. break
  74010. // This code is unreachable.
  74011. // default:
  74012. // throw invalidToken()
  74013. }
  74014. if (root === undefined) {
  74015. root = value;
  74016. } else {
  74017. const parent = stack$1[stack$1.length - 1];
  74018. if (Array.isArray(parent)) {
  74019. parent.push(value);
  74020. } else {
  74021. parent[key] = value;
  74022. }
  74023. }
  74024. if (value !== null && typeof value === 'object') {
  74025. stack$1.push(value);
  74026. if (Array.isArray(value)) {
  74027. parseState = 'beforeArrayValue';
  74028. } else {
  74029. parseState = 'beforePropertyName';
  74030. }
  74031. } else {
  74032. const current = stack$1[stack$1.length - 1];
  74033. if (current == null) {
  74034. parseState = 'end';
  74035. } else if (Array.isArray(current)) {
  74036. parseState = 'afterArrayValue';
  74037. } else {
  74038. parseState = 'afterPropertyValue';
  74039. }
  74040. }
  74041. }
  74042. function pop () {
  74043. stack$1.pop();
  74044. const current = stack$1[stack$1.length - 1];
  74045. if (current == null) {
  74046. parseState = 'end';
  74047. } else if (Array.isArray(current)) {
  74048. parseState = 'afterArrayValue';
  74049. } else {
  74050. parseState = 'afterPropertyValue';
  74051. }
  74052. }
  74053. // This code is unreachable.
  74054. // function invalidParseState () {
  74055. // return new Error(`JSON5: invalid parse state '${parseState}'`)
  74056. // }
  74057. // This code is unreachable.
  74058. // function invalidLexState (state) {
  74059. // return new Error(`JSON5: invalid lex state '${state}'`)
  74060. // }
  74061. function invalidChar (c) {
  74062. if (c === undefined) {
  74063. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  74064. }
  74065. return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  74066. }
  74067. function invalidEOF () {
  74068. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  74069. }
  74070. // This code is unreachable.
  74071. // function invalidToken () {
  74072. // if (token.type === 'eof') {
  74073. // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  74074. // }
  74075. // const c = String.fromCodePoint(token.value.codePointAt(0))
  74076. // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  74077. // }
  74078. function invalidIdentifier () {
  74079. column -= 5;
  74080. return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)
  74081. }
  74082. function separatorChar (c) {
  74083. console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
  74084. }
  74085. function formatChar (c) {
  74086. const replacements = {
  74087. "'": "\\'",
  74088. '"': '\\"',
  74089. '\\': '\\\\',
  74090. '\b': '\\b',
  74091. '\f': '\\f',
  74092. '\n': '\\n',
  74093. '\r': '\\r',
  74094. '\t': '\\t',
  74095. '\v': '\\v',
  74096. '\0': '\\0',
  74097. '\u2028': '\\u2028',
  74098. '\u2029': '\\u2029',
  74099. };
  74100. if (replacements[c]) {
  74101. return replacements[c]
  74102. }
  74103. if (c < ' ') {
  74104. const hexString = c.charCodeAt(0).toString(16);
  74105. return '\\x' + ('00' + hexString).substring(hexString.length)
  74106. }
  74107. return c
  74108. }
  74109. function syntaxError (message) {
  74110. const err = new SyntaxError(message);
  74111. err.lineNumber = line;
  74112. err.columnNumber = column;
  74113. return err
  74114. }
  74115. var stringify = function stringify (value, replacer, space) {
  74116. const stack = [];
  74117. let indent = '';
  74118. let propertyList;
  74119. let replacerFunc;
  74120. let gap = '';
  74121. let quote;
  74122. if (
  74123. replacer != null &&
  74124. typeof replacer === 'object' &&
  74125. !Array.isArray(replacer)
  74126. ) {
  74127. space = replacer.space;
  74128. quote = replacer.quote;
  74129. replacer = replacer.replacer;
  74130. }
  74131. if (typeof replacer === 'function') {
  74132. replacerFunc = replacer;
  74133. } else if (Array.isArray(replacer)) {
  74134. propertyList = [];
  74135. for (const v of replacer) {
  74136. let item;
  74137. if (typeof v === 'string') {
  74138. item = v;
  74139. } else if (
  74140. typeof v === 'number' ||
  74141. v instanceof String ||
  74142. v instanceof Number
  74143. ) {
  74144. item = String(v);
  74145. }
  74146. if (item !== undefined && propertyList.indexOf(item) < 0) {
  74147. propertyList.push(item);
  74148. }
  74149. }
  74150. }
  74151. if (space instanceof Number) {
  74152. space = Number(space);
  74153. } else if (space instanceof String) {
  74154. space = String(space);
  74155. }
  74156. if (typeof space === 'number') {
  74157. if (space > 0) {
  74158. space = Math.min(10, Math.floor(space));
  74159. gap = ' '.substr(0, space);
  74160. }
  74161. } else if (typeof space === 'string') {
  74162. gap = space.substr(0, 10);
  74163. }
  74164. return serializeProperty('', {'': value})
  74165. function serializeProperty (key, holder) {
  74166. let value = holder[key];
  74167. if (value != null) {
  74168. if (typeof value.toJSON5 === 'function') {
  74169. value = value.toJSON5(key);
  74170. } else if (typeof value.toJSON === 'function') {
  74171. value = value.toJSON(key);
  74172. }
  74173. }
  74174. if (replacerFunc) {
  74175. value = replacerFunc.call(holder, key, value);
  74176. }
  74177. if (value instanceof Number) {
  74178. value = Number(value);
  74179. } else if (value instanceof String) {
  74180. value = String(value);
  74181. } else if (value instanceof Boolean) {
  74182. value = value.valueOf();
  74183. }
  74184. switch (value) {
  74185. case null: return 'null'
  74186. case true: return 'true'
  74187. case false: return 'false'
  74188. }
  74189. if (typeof value === 'string') {
  74190. return quoteString(value, false)
  74191. }
  74192. if (typeof value === 'number') {
  74193. return String(value)
  74194. }
  74195. if (typeof value === 'object') {
  74196. return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
  74197. }
  74198. return undefined
  74199. }
  74200. function quoteString (value) {
  74201. const quotes = {
  74202. "'": 0.1,
  74203. '"': 0.2,
  74204. };
  74205. const replacements = {
  74206. "'": "\\'",
  74207. '"': '\\"',
  74208. '\\': '\\\\',
  74209. '\b': '\\b',
  74210. '\f': '\\f',
  74211. '\n': '\\n',
  74212. '\r': '\\r',
  74213. '\t': '\\t',
  74214. '\v': '\\v',
  74215. '\0': '\\0',
  74216. '\u2028': '\\u2028',
  74217. '\u2029': '\\u2029',
  74218. };
  74219. let product = '';
  74220. for (let i = 0; i < value.length; i++) {
  74221. const c = value[i];
  74222. switch (c) {
  74223. case "'":
  74224. case '"':
  74225. quotes[c]++;
  74226. product += c;
  74227. continue
  74228. case '\0':
  74229. if (util.isDigit(value[i + 1])) {
  74230. product += '\\x00';
  74231. continue
  74232. }
  74233. }
  74234. if (replacements[c]) {
  74235. product += replacements[c];
  74236. continue
  74237. }
  74238. if (c < ' ') {
  74239. let hexString = c.charCodeAt(0).toString(16);
  74240. product += '\\x' + ('00' + hexString).substring(hexString.length);
  74241. continue
  74242. }
  74243. product += c;
  74244. }
  74245. const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b);
  74246. product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
  74247. return quoteChar + product + quoteChar
  74248. }
  74249. function serializeObject (value) {
  74250. if (stack.indexOf(value) >= 0) {
  74251. throw TypeError('Converting circular structure to JSON5')
  74252. }
  74253. stack.push(value);
  74254. let stepback = indent;
  74255. indent = indent + gap;
  74256. let keys = propertyList || Object.keys(value);
  74257. let partial = [];
  74258. for (const key of keys) {
  74259. const propertyString = serializeProperty(key, value);
  74260. if (propertyString !== undefined) {
  74261. let member = serializeKey(key) + ':';
  74262. if (gap !== '') {
  74263. member += ' ';
  74264. }
  74265. member += propertyString;
  74266. partial.push(member);
  74267. }
  74268. }
  74269. let final;
  74270. if (partial.length === 0) {
  74271. final = '{}';
  74272. } else {
  74273. let properties;
  74274. if (gap === '') {
  74275. properties = partial.join(',');
  74276. final = '{' + properties + '}';
  74277. } else {
  74278. let separator = ',\n' + indent;
  74279. properties = partial.join(separator);
  74280. final = '{\n' + indent + properties + ',\n' + stepback + '}';
  74281. }
  74282. }
  74283. stack.pop();
  74284. indent = stepback;
  74285. return final
  74286. }
  74287. function serializeKey (key) {
  74288. if (key.length === 0) {
  74289. return quoteString(key, true)
  74290. }
  74291. const firstChar = String.fromCodePoint(key.codePointAt(0));
  74292. if (!util.isIdStartChar(firstChar)) {
  74293. return quoteString(key, true)
  74294. }
  74295. for (let i = firstChar.length; i < key.length; i++) {
  74296. if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
  74297. return quoteString(key, true)
  74298. }
  74299. }
  74300. return key
  74301. }
  74302. function serializeArray (value) {
  74303. if (stack.indexOf(value) >= 0) {
  74304. throw TypeError('Converting circular structure to JSON5')
  74305. }
  74306. stack.push(value);
  74307. let stepback = indent;
  74308. indent = indent + gap;
  74309. let partial = [];
  74310. for (let i = 0; i < value.length; i++) {
  74311. const propertyString = serializeProperty(String(i), value);
  74312. partial.push((propertyString !== undefined) ? propertyString : 'null');
  74313. }
  74314. let final;
  74315. if (partial.length === 0) {
  74316. final = '[]';
  74317. } else {
  74318. if (gap === '') {
  74319. let properties = partial.join(',');
  74320. final = '[' + properties + ']';
  74321. } else {
  74322. let separator = ',\n' + indent;
  74323. let properties = partial.join(separator);
  74324. final = '[\n' + indent + properties + ',\n' + stepback + ']';
  74325. }
  74326. }
  74327. stack.pop();
  74328. indent = stepback;
  74329. return final
  74330. }
  74331. };
  74332. const JSON5$1 = {
  74333. parse,
  74334. stringify,
  74335. };
  74336. var lib = JSON5$1;
  74337. class Sidebar{
  74338. constructor(viewer){
  74339. this.viewer = viewer;
  74340. this.measuringTool = viewer.measuringTool;
  74341. this.profileTool = viewer.profileTool;
  74342. this.volumeTool = viewer.volumeTool;
  74343. this.dom = $("#sidebar_root");
  74344. }
  74345. createToolIcon(icon, title, callback){
  74346. let element = $(`
  74347. <img src="${icon}"
  74348. style="width: 32px; height: 32px"
  74349. class="button-icon"
  74350. data-i18n="${title}" />
  74351. `);
  74352. element.click(callback);
  74353. return element;
  74354. }
  74355. init(){
  74356. if(Potree.settings.editType == 'merge'){
  74357. this.initMergeBar();
  74358. this.initToolbar();
  74359. this.initScene();
  74360. this.initNavigation();
  74361. }else {
  74362. this.initAccordion();
  74363. this.initAppearance();
  74364. this.initToolbar();
  74365. this.initScene();
  74366. this.initNavigation();
  74367. this.initFilters();
  74368. //this.initClippingTool(); //因为修改了clipping,所以这项有bug不能使用
  74369. this.initSettings();
  74370. if(Potree.settings.editType != 'pano'){
  74371. this.initAlignment();
  74372. this.initClipModel();
  74373. this.initSiteModel();
  74374. this.initParitcle();
  74375. this.initClippingModel();
  74376. }else {
  74377. this.initPanosEdit();
  74378. }
  74379. }
  74380. $('#potree_version_number').html(Potree.version.major + "." + Potree.version.minor + Potree.version.suffix);
  74381. }
  74382. initAlignment(){
  74383. let Alignment = viewer.modules.Alignment;
  74384. var pannel = $('#alignment');
  74385. var buttons = pannel.find('[name="transform"] button');
  74386. var applyToPointcloud = (fun, value)=>{
  74387. return function(){
  74388. var selected = $('#alignment li[name="selectPointCloud"] input:checked' );
  74389. Array.from(selected).forEach(e=>{
  74390. var pointcloud = viewer.scene.pointclouds.find(p=>p.name == e.name);
  74391. fun(pointcloud, value);
  74392. });
  74393. }
  74394. };
  74395. //逆时针是正数
  74396. buttons.eq(0).on('click', applyToPointcloud(Alignment.rotate, 10));
  74397. //viewer.scene.pointclouds[0].rotation.z += THREE.Math.degToRad(10)
  74398. buttons.eq(1).on('click' ,applyToPointcloud(Alignment.rotate, 1));
  74399. buttons.eq(2).on('click', applyToPointcloud(Alignment.rotate, 0.1));
  74400. buttons.eq(3).on('click', applyToPointcloud(Alignment.rotate, -10));
  74401. buttons.eq(4).on('click',applyToPointcloud(Alignment.rotate, -1));
  74402. buttons.eq(5).on('click',applyToPointcloud(Alignment.rotate, -0.1));
  74403. buttons.eq(6).on('click', applyToPointcloud(Alignment.translate, new Vector3(-1,0,0)));
  74404. buttons.eq(7).on('click', applyToPointcloud(Alignment.translate, new Vector3(1,0,0)));
  74405. buttons.eq(8).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,-1,0)));
  74406. buttons.eq(9).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,1,0)));
  74407. buttons.eq(10).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,0,-1)));
  74408. buttons.eq(11).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,0,1)));
  74409. pannel.find('#startAlignment').on('click', ()=>{
  74410. Alignment.enter();
  74411. });
  74412. pannel.find('#exitAlignment').on('click', ()=>{
  74413. Alignment.save();
  74414. Alignment.leave();
  74415. });
  74416. pannel.find('#rotTool').on('click', ()=>{
  74417. Alignment.switchHandle('rotate');
  74418. });
  74419. pannel.find('#moveTool').on('click', ()=>{
  74420. Alignment.switchHandle('translate');
  74421. });
  74422. }
  74423. initMergeBar(){//多元融合模块
  74424. var pannel = $('#mergeModel');
  74425. var buttons = pannel.find('button');
  74426. let MergeEditor = viewer.modules.MergeEditor;
  74427. let loading = false;
  74428. pannel.find('ul[name="model"] li button').on('click',(e)=>{
  74429. if(loading)return console.log('还在加载', loading)
  74430. let $elem = $(e.target);
  74431. let parent = $elem.parent();
  74432. let name = parent.attr('name');
  74433. if($elem.attr('name') == 'select'){
  74434. return Potree.selectModel(name)
  74435. }
  74436. if($elem.text() == '添加'){
  74437. let startTime = Date.now();
  74438. Potree.addModel(name,()=>{
  74439. loading = false;
  74440. //$elem.text('删除')
  74441. let now = Date.now();
  74442. console.log('加载完毕', name, '用时', (now-startTime)/1000, 's');
  74443. });
  74444. loading = name;
  74445. }else {
  74446. Potree.removeModel(name);
  74447. $elem.text('添加');
  74448. }
  74449. });
  74450. pannel.find('li button[name="splitScreen"]').on('click',(e)=>{
  74451. let $elem = $(e.target);
  74452. if($elem.text() == '分屏'){
  74453. $elem.text('恢复');
  74454. MergeEditor.enterSplit();
  74455. }else {
  74456. $elem.text('分屏');
  74457. MergeEditor.leaveSplit();
  74458. }
  74459. });
  74460. let addingTag = false;
  74461. pannel.find('li button[name="tag"]').on('click',(e)=>{
  74462. let $elem = $(e.target);
  74463. viewer.tagTool.startInsertion();
  74464. });
  74465. }
  74466. initClippingModel(){//实时裁剪
  74467. /* 总共两种box : 可见和不可见(都是并集)
  74468. 当有可见box时,需要在任一可见box内才可见
  74469. 当有不可见box时,不在所有不可见box内才可见 */
  74470. var clipping = viewer.modules.clipping;
  74471. var pannel = $('#clipping');
  74472. var addBtn = pannel.find('[name="operation"] button[name="add"] ');
  74473. var switchBtn = pannel.find('[name="operation"] button[name="switchView"] ');
  74474. var enterBtn = pannel.find(' button[name="enter"] ');
  74475. var exitBtn = pannel.find(' button[name="exit"] ');
  74476. let list = pannel.find('[name="list"] ul ');
  74477. enterBtn.on('click',()=>{
  74478. clipping.enter();
  74479. pannel.find('li[name=operation]').css('display','block');
  74480. pannel.find('li[name=list]').css('display','block');
  74481. });
  74482. exitBtn.on('click',()=>{
  74483. clipping.leave();
  74484. pannel.find('li[name=operation]').css('display','none');
  74485. pannel.find('li[name=list]').css('display','none');
  74486. });
  74487. switchBtn.on('click',()=>{
  74488. clipping.switchView(clipping.activeViewName == 'top' ? 'mainView' : 'top');
  74489. });
  74490. pannel.find('[name="operation"] button[name="translation"] ').on('click',()=>{
  74491. clipping.setTranMode('translation');
  74492. });
  74493. pannel.find('[name="operation"] button[name="rotation"] ').on('click',()=>{
  74494. clipping.setTranMode('rotation');
  74495. });
  74496. pannel.find('[name="operation"] button[name="scale"] ').on('click',()=>{
  74497. clipping.setTranMode('scale');
  74498. });
  74499. addBtn.on('click',()=>{
  74500. let volumeBox = this.volumeTool.startInsertion({clip: true, clipTask:Potree.ClipTask.SHOW_OUTSIDE});
  74501. let li = $("<li><button name='changeTask'>不可见</button><button name='chose'>选择</button><button name='delete'>删除</button></li>");
  74502. list.append(li);
  74503. li.find('button[name=changeTask]').on('click',(e)=>{
  74504. if(e.target.innerText == '不可见'){
  74505. volumeBox.clipTask = Potree.ClipTask.SHOW_INSIDE;
  74506. e.target.innerText = '可见';
  74507. }else {
  74508. volumeBox.clipTask = Potree.ClipTask.SHOW_OUTSIDE;
  74509. e.target.innerText = '不可见';
  74510. }
  74511. volumeBox.update();
  74512. });
  74513. li.find('button[name=chose]').on('click',(e)=>{
  74514. viewer.transformObject(volumeBox);//viewer.inputHandler.toggleSelection(volumeBox)
  74515. });
  74516. li.find('button[name=delete]').on('click',(e)=>{
  74517. li.remove();
  74518. viewer.scene.removeVolume(volumeBox);
  74519. });
  74520. });
  74521. pannel.find('button[name=save]').on('click',(e)=>{
  74522. let data = clipping.saveClipData();
  74523. });
  74524. }
  74525. addAlignmentButton(pointcloud){
  74526. var pannel = $('#alignment li[name="selectPointCloud"]>div');
  74527. var option = $(` <input name="${pointcloud.name}" class="editCheckbox" type="checkbox" >
  74528. <label for="showingLabels">${pointcloud.name}</label>`);
  74529. pannel.append(option);
  74530. /* option.find("input").on('change',function(){
  74531. })
  74532. */
  74533. }
  74534. initClipModel(){
  74535. let Clip = viewer.modules.Clip;
  74536. var pannel = $('#clipModel');
  74537. var buttons = pannel.find('button');
  74538. buttons.eq(0).on('click', Clip.enter.bind(Clip));
  74539. buttons.eq(1).on('click', Clip.download.bind(Clip));
  74540. buttons.eq(2).on('click', Clip.leave.bind(Clip));
  74541. }
  74542. initSiteModel(){
  74543. let SiteModel = viewer.modules.SiteModel;
  74544. var pannel = $('#siteModel');
  74545. pannel.find('button[name="start"] ').on('click', SiteModel.enter.bind(SiteModel));
  74546. pannel.find('button[name="exit"] ').on('click', SiteModel.leave.bind(SiteModel));
  74547. pannel.find('button[name="building"] ').on('click', SiteModel.startInsertion.bind(SiteModel,'building'));
  74548. pannel.find('button[name="floor"] ').on('click', ()=>{
  74549. SiteModel.addFloor(SiteModel.buildings[0], 'top');
  74550. } );
  74551. pannel.find('button[name="room"] ').on('click', ()=>{
  74552. SiteModel.startInsertion('room', SiteModel.buildings[0].buildChildren[0]);
  74553. });
  74554. pannel.find('button[name="digHole"] ').on('click', ()=>{
  74555. SiteModel.selected && SiteModel.startInsertion('hole', SiteModel.selected);
  74556. });
  74557. pannel.find('button[name="selectBuilding"] ').on('click', ()=>{
  74558. SiteModel.selectEntity(SiteModel.buildings[0] );
  74559. } );
  74560. pannel.find('button[name="selectFloor"] ').on('click', ()=>{
  74561. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0]);
  74562. } );
  74563. pannel.find('button[name="selectRoom"] ').on('click', ()=>{
  74564. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  74565. });
  74566. pannel.find('button[name="removeFirstBuilding"] ').on('click', ()=>{
  74567. SiteModel.removeEntity(SiteModel.buildings[0]);
  74568. });
  74569. pannel.find('button[name="removeFirstFloor"] ').on('click', ()=>{
  74570. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0]);
  74571. });
  74572. pannel.find('button[name="removeFirstRoom"] ').on('click', ()=>{
  74573. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  74574. });
  74575. pannel.find('button[name="removeFirstHole"] ').on('click', ()=>{
  74576. SiteModel.selected.removeHole(SiteModel.selected.holes[0]);
  74577. });
  74578. pannel.find('button[name="removeFirstMarker"] ').on('click', ()=>{
  74579. //SiteModel.removeMarker(SiteModel.selected.markers[0])
  74580. SiteModel.selected.removeMarker(0);
  74581. });
  74582. }
  74583. initParitcle(){
  74584. let ParticleEditor = viewer.modules.ParticleEditor;
  74585. var pannel = $('#particle');
  74586. pannel.find('button[name="addFire"] ').on('click', ()=>{
  74587. ParticleEditor.startInsertion('fire+smoke');
  74588. });
  74589. pannel.find('button[name="addExplode"] ').on('click', ()=>{
  74590. ParticleEditor.startInsertion('explode');
  74591. });
  74592. }
  74593. initPanosEdit(){
  74594. let PanoEditor = viewer.modules.PanoEditor;
  74595. let Alignment = viewer.modules.Alignment;
  74596. var pannel = $('#panos');
  74597. pannel.find('button[name="save"] ').on('click', ()=>{
  74598. console.log('saveData',PanoEditor.exportSavingData());
  74599. });
  74600. pannel.find('button[name="translate"] ').on('click', ()=>{
  74601. Alignment.switchHandle('translate');
  74602. });
  74603. pannel.find('button[name="rotate"] ').on('click', ()=>{
  74604. Alignment.switchHandle('rotate');
  74605. });
  74606. pannel.find('button[name="topView"] ').on('click', ()=>{
  74607. PanoEditor.switchView('top');
  74608. });
  74609. pannel.find('button[name="sideView"] ').on('click', ()=>{
  74610. PanoEditor.switchView('right');
  74611. });
  74612. pannel.find('button[name="3DView"] ').on('click', ()=>{
  74613. PanoEditor.switchView('mainView');
  74614. });
  74615. pannel.find('button[name="addLink"] ').on('click', ()=>{
  74616. PanoEditor.setLinkOperateState('addLink', true);
  74617. });
  74618. pannel.find('button[name="removeLink"] ').on('click', ()=>{
  74619. PanoEditor.setLinkOperateState('removeLink', true);
  74620. });
  74621. pannel.find('button[name="getCloser"] ').on('click', ()=>{
  74622. PanoEditor.setZoomInState(true);
  74623. });
  74624. }
  74625. initToolbar(){
  74626. // ANGLE
  74627. let elToolbar = $('#tools');
  74628. elToolbar.append(this.createToolIcon(
  74629. Potree.resourcePath + '/icons/angle.png',
  74630. '[title]tt.angle_measurement',
  74631. () => {
  74632. $('#menu_measurements').next().slideDown();
  74633. let measurement = this.measuringTool.startInsertion({
  74634. showDistances: false,
  74635. showAngles: true,
  74636. showArea: false,
  74637. closed: true,
  74638. maxMarkers: 3,
  74639. minMarkers:3,
  74640. measureType: 'Angle'});
  74641. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74642. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74643. $.jstree.reference(jsonNode.id).deselect_all();
  74644. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74645. }
  74646. ));
  74647. // POINT
  74648. elToolbar.append(this.createToolIcon(
  74649. Potree.resourcePath + '/icons/point.svg',
  74650. '[title]tt.point_measurement',
  74651. () => {
  74652. $('#menu_measurements').next().slideDown();
  74653. let measurement = this.measuringTool.startInsertion({
  74654. showDistances: false,
  74655. showAngles: false,
  74656. showCoordinates: true,
  74657. showEdges:false,
  74658. showArea: false,
  74659. closed: true,
  74660. maxMarkers: 1,
  74661. minMarkers:1,
  74662. measureType: 'Point'});
  74663. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74664. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74665. $.jstree.reference(jsonNode.id).deselect_all();
  74666. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74667. }
  74668. ));
  74669. // DISTANCE
  74670. elToolbar.append(this.createToolIcon(
  74671. Potree.resourcePath + '/icons/distance.svg',
  74672. '[title]tt.distance_measurement',
  74673. () => {
  74674. $('#menu_measurements').next().slideDown();
  74675. let measurement = this.measuringTool.startInsertion({
  74676. showDistances: true,
  74677. showArea: false,
  74678. closed: false,
  74679. minMarkers:2,
  74680. maxMarkers: 2,
  74681. measureType: 'Distance'
  74682. });
  74683. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74684. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74685. $.jstree.reference(jsonNode.id).deselect_all();
  74686. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74687. }
  74688. ));
  74689. // DISTANCE2
  74690. elToolbar.append(this.createToolIcon(
  74691. Potree.resourcePath + '/icons/distance.svg',
  74692. '[title]MulDistance',
  74693. () => {
  74694. $('#menu_measurements').next().slideDown();
  74695. let measurement = this.measuringTool.startInsertion({
  74696. showDistances: true,
  74697. showArea: false,
  74698. closed: false,
  74699. minMarkers:2,
  74700. measureType: 'MulDistance'
  74701. });
  74702. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74703. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74704. $.jstree.reference(jsonNode.id).deselect_all();
  74705. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74706. }
  74707. ));
  74708. elToolbar.append(this.createToolIcon(
  74709. Potree.resourcePath + '/icons/distance.svg',
  74710. '[title]Ver MulDistance',
  74711. () => {
  74712. $('#menu_measurements').next().slideDown();
  74713. let measurement = this.measuringTool.startInsertion({
  74714. measureType: 'Ver MulDistance'
  74715. });
  74716. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74717. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74718. $.jstree.reference(jsonNode.id).deselect_all();
  74719. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74720. }
  74721. ));
  74722. elToolbar.append(this.createToolIcon(
  74723. Potree.resourcePath + '/icons/distance.svg',
  74724. '[title]Hor MulDistance',
  74725. () => {
  74726. $('#menu_measurements').next().slideDown();
  74727. let measurement = this.measuringTool.startInsertion({
  74728. measureType: 'Hor MulDistance'
  74729. });
  74730. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74731. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74732. $.jstree.reference(jsonNode.id).deselect_all();
  74733. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74734. }
  74735. ));
  74736. // HEIGHT
  74737. elToolbar.append(this.createToolIcon(
  74738. Potree.resourcePath + '/icons/height.svg',
  74739. '[title]tt.height_measurement',
  74740. () => {
  74741. $('#menu_measurements').next().slideDown();
  74742. let measurement = this.measuringTool.startInsertion({
  74743. showDistances: true,//false,
  74744. showHeight: true,
  74745. showArea: false,
  74746. closed: false,
  74747. maxMarkers: 2,
  74748. minMarkers:2,
  74749. //showGuideLine: true: true
  74750. measureType: 'Ver Distance',
  74751. });
  74752. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74753. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74754. $.jstree.reference(jsonNode.id).deselect_all();
  74755. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74756. }
  74757. ));
  74758. // CIRCLE
  74759. elToolbar.append(this.createToolIcon(
  74760. Potree.resourcePath + '/icons/circle.svg',
  74761. '[title]tt.circle_measurement',
  74762. () => {
  74763. $('#menu_measurements').next().slideDown();
  74764. let measurement = this.measuringTool.startInsertion({
  74765. showDistances: false,
  74766. showHeight: false,
  74767. showArea: false,
  74768. showCircle: true,
  74769. showEdges: false,
  74770. closed: false,
  74771. maxMarkers: 3,
  74772. minMarkers:3,
  74773. measureType: 'Circle'
  74774. });
  74775. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74776. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74777. $.jstree.reference(jsonNode.id).deselect_all();
  74778. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74779. }
  74780. ));
  74781. // AZIMUTH
  74782. elToolbar.append(this.createToolIcon(
  74783. Potree.resourcePath + '/icons/azimuth.svg',
  74784. 'Azimuth',
  74785. () => {
  74786. $('#menu_measurements').next().slideDown();
  74787. let measurement = this.measuringTool.startInsertion({
  74788. showDistances: false,
  74789. showHeight: false,
  74790. showArea: false,
  74791. showCircle: false,
  74792. showEdges: false,
  74793. showAzimuth: true,
  74794. closed: false,
  74795. maxMarkers: 2,
  74796. minMarkers:2,
  74797. measureType: 'Azimuth'});
  74798. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74799. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74800. $.jstree.reference(jsonNode.id).deselect_all();
  74801. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74802. }
  74803. ));
  74804. // AREA
  74805. elToolbar.append(this.createToolIcon(
  74806. Potree.resourcePath + '/icons/area.svg',
  74807. '[title]tt.area_measurement',
  74808. () => {
  74809. $('#menu_measurements').next().slideDown();
  74810. let measurement = this.measuringTool.startInsertion({
  74811. showDistances: true,
  74812. showArea: true,
  74813. closed: true,
  74814. minMarkers:3,
  74815. //showGuideLine: true: true,
  74816. measureType: 'Area'});
  74817. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74818. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74819. $.jstree.reference(jsonNode.id).deselect_all();
  74820. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74821. }
  74822. ));
  74823. //Hor AREA
  74824. elToolbar.append(this.createToolIcon(
  74825. Potree.resourcePath + '/icons/area.svg',
  74826. '[title]Hor Area',
  74827. () => {
  74828. $('#menu_measurements').next().slideDown();
  74829. let measurement = this.measuringTool.startInsertion({
  74830. showDistances: true,
  74831. showArea: true,
  74832. closed: true,
  74833. minMarkers:3,
  74834. measureType: 'Hor Area'});
  74835. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74836. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74837. $.jstree.reference(jsonNode.id).deselect_all();
  74838. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74839. }
  74840. ));
  74841. // Ver Area
  74842. elToolbar.append(this.createToolIcon(
  74843. Potree.resourcePath + '/icons/area.svg',
  74844. '[title]Ver Area',
  74845. () => {
  74846. $('#menu_measurements').next().slideDown();
  74847. let measurement = this.measuringTool.startInsertion({
  74848. showDistances: true,
  74849. showArea: true,
  74850. closed: true,
  74851. minMarkers:3,
  74852. measureType: 'Ver Area'});
  74853. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74854. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74855. $.jstree.reference(jsonNode.id).deselect_all();
  74856. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74857. }
  74858. ));
  74859. // rect area freedom direction
  74860. elToolbar.append(this.createToolIcon(
  74861. Potree.resourcePath + '/icons/area.svg',
  74862. '[title]area_freedom_rect',
  74863. () => {
  74864. $('#menu_measurements').next().slideDown();
  74865. let measurement = this.measuringTool.startInsertion({
  74866. showDistances: true,
  74867. showArea: true,
  74868. closed: true,
  74869. minMarkers:4,
  74870. maxMarkers:4,
  74871. //showGuideLine: true: true,
  74872. isRect:true,
  74873. measureType: 'Rect Area'});
  74874. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74875. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74876. $.jstree.reference(jsonNode.id).deselect_all();
  74877. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74878. }
  74879. ));
  74880. // rect area horizontal
  74881. elToolbar.append(this.createToolIcon(
  74882. Potree.resourcePath + '/icons/area.svg',
  74883. '[title]area_horizontal_rect',
  74884. () => {
  74885. $('#menu_measurements').next().slideDown();
  74886. let measurement = this.measuringTool.startInsertion({
  74887. showDistances: true,
  74888. showArea: true,
  74889. closed: true,
  74890. minMarkers:4,
  74891. maxMarkers:4,
  74892. //showGuideLine: true: true,
  74893. isRect:true,
  74894. faceDirection:"horizontal",
  74895. measureType: 'Hor Rect Area'});
  74896. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74897. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74898. $.jstree.reference(jsonNode.id).deselect_all();
  74899. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74900. }
  74901. ));
  74902. // rect area vertical
  74903. elToolbar.append(this.createToolIcon(
  74904. Potree.resourcePath + '/icons/area.svg',
  74905. '[title]area_vertical_rect',
  74906. () => {
  74907. $('#menu_measurements').next().slideDown();
  74908. let measurement = this.measuringTool.startInsertion({
  74909. showDistances: true,
  74910. showArea: true,
  74911. closed: true,
  74912. minMarkers:4,
  74913. maxMarkers:4,
  74914. //showGuideLine: true: true,
  74915. isRect:true,
  74916. faceDirection:"vertical",
  74917. measureType: 'Ver Rect Area'});
  74918. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74919. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  74920. $.jstree.reference(jsonNode.id).deselect_all();
  74921. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74922. }
  74923. ));
  74924. // VOLUME
  74925. elToolbar.append(this.createToolIcon(
  74926. Potree.resourcePath + '/icons/volume.svg',
  74927. '[title]tt.volume_measurement',
  74928. () => {
  74929. let volume = this.volumeTool.startInsertion();
  74930. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74931. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  74932. $.jstree.reference(jsonNode.id).deselect_all();
  74933. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74934. }
  74935. ));
  74936. // SPHERE VOLUME
  74937. elToolbar.append(this.createToolIcon(
  74938. Potree.resourcePath + '/icons/sphere_distances.svg',
  74939. '[title]tt.volume_measurement',
  74940. () => {
  74941. let volume = this.volumeTool.startInsertion({type: SphereVolume$2});
  74942. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74943. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  74944. $.jstree.reference(jsonNode.id).deselect_all();
  74945. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74946. }
  74947. ));
  74948. // PROFILE
  74949. elToolbar.append(this.createToolIcon(
  74950. Potree.resourcePath + '/icons/profile.svg',
  74951. '[title]tt.height_profile',
  74952. () => {
  74953. $('#menu_measurements').next().slideDown(); ;
  74954. let profile = this.profileTool.startInsertion();
  74955. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  74956. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === profile.uuid);
  74957. $.jstree.reference(jsonNode.id).deselect_all();
  74958. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74959. }
  74960. ));
  74961. // ANNOTATION
  74962. elToolbar.append(this.createToolIcon(
  74963. Potree.resourcePath + '/icons/annotation.svg',
  74964. '[title]tt.annotation',
  74965. () => {
  74966. $('#menu_measurements').next().slideDown(); ;
  74967. let annotation = this.viewer.annotationTool.startInsertion();
  74968. let annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  74969. let jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  74970. $.jstree.reference(jsonNode.id).deselect_all();
  74971. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  74972. }
  74973. ));
  74974. // REMOVE ALL
  74975. elToolbar.append(this.createToolIcon(
  74976. Potree.resourcePath + '/icons/reset_tools.svg',
  74977. '[title]tt.remove_all_measurement',
  74978. () => {
  74979. this.viewer.scene.removeAllMeasurements();
  74980. }
  74981. ));
  74982. { // SHOW / HIDE Measurements
  74983. let elShow = $("#measurement_options_show");
  74984. elShow.selectgroup({title: "Show/Hide labels"});
  74985. elShow.find("input").click( (e) => {
  74986. const show = e.target.value === "SHOW";
  74987. this.measuringTool.showLabels = show;
  74988. });
  74989. let currentShow = this.measuringTool.showLabels ? "SHOW" : "HIDE";
  74990. elShow.find(`input[value=${currentShow}]`).trigger("click");
  74991. }
  74992. }
  74993. initScene(){
  74994. let elScene = $("#menu_scene");
  74995. let elObjects = elScene.next().find("#scene_objects");
  74996. let elProperties = elScene.next().find("#scene_object_properties");
  74997. {
  74998. let elExport = elScene.next().find("#scene_export");
  74999. let geoJSONIcon = `${Potree.resourcePath}/icons/file_geojson.svg`;
  75000. let dxfIcon = `${Potree.resourcePath}/icons/file_dxf.svg`;
  75001. let potreeIcon = `${Potree.resourcePath}/icons/file_potree.svg`;
  75002. elExport.append(`
  75003. Export: <br>
  75004. <a href="#" download="measure.json"><img name="geojson_export_button" src="${geoJSONIcon}" class="button-icon" style="height: 24px" /></a>
  75005. <a href="#" download="measure.dxf"><img name="dxf_export_button" src="${dxfIcon}" class="button-icon" style="height: 24px" /></a>
  75006. <a href="#" download="potree.json5"><img name="potree_export_button" src="${potreeIcon}" class="button-icon" style="height: 24px" /></a>
  75007. `);
  75008. let elDownloadJSON = elExport.find("img[name=geojson_export_button]").parent();
  75009. elDownloadJSON.click( (event) => {
  75010. let scene = this.viewer.scene;
  75011. let measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  75012. if(measurements.length > 0){
  75013. let geoJson = GeoJSONExporter.toString(measurements);
  75014. let url = window.URL.createObjectURL(new Blob([geoJson], {type: 'data:application/octet-stream'}));
  75015. elDownloadJSON.attr('href', url);
  75016. }else {
  75017. this.viewer.postError("nothing to export");
  75018. event.preventDefault();
  75019. }
  75020. });
  75021. let elDownloadDXF = elExport.find("img[name=dxf_export_button]").parent();
  75022. elDownloadDXF.click( (event) => {
  75023. let scene = this.viewer.scene;
  75024. let measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  75025. if(measurements.length > 0){
  75026. let dxf = DXFExporter.toString(measurements);
  75027. let url = window.URL.createObjectURL(new Blob([dxf], {type: 'data:application/octet-stream'}));
  75028. elDownloadDXF.attr('href', url);
  75029. }else {
  75030. this.viewer.postError("no measurements to export");
  75031. event.preventDefault();
  75032. }
  75033. });
  75034. let elDownloadPotree = elExport.find("img[name=potree_export_button]").parent();
  75035. elDownloadPotree.click( (event) => {
  75036. let data = Potree.saveProject(this.viewer);
  75037. let dataString = lib.stringify(data, null, "\t");
  75038. let url = window.URL.createObjectURL(new Blob([dataString], {type: 'data:application/octet-stream'}));
  75039. elDownloadPotree.attr('href', url);
  75040. });
  75041. }
  75042. let propertiesPanel = new PropertiesPanel(elProperties, this.viewer);
  75043. propertiesPanel.setScene(this.viewer.scene);
  75044. localStorage.removeItem('jstree');
  75045. let tree = $(`<div id="jstree_scene"></div>`);
  75046. elObjects.append(tree);
  75047. tree.jstree({
  75048. 'plugins': ["checkbox", "state"],
  75049. 'core': {
  75050. "dblclick_toggle": false,
  75051. "state": {
  75052. "checked" : true
  75053. },
  75054. 'check_callback': true,
  75055. "expand_selected_onload": true
  75056. },
  75057. "checkbox" : {
  75058. "keep_selected_style": true,
  75059. "three_state": false,
  75060. "whole_node": false,
  75061. "tie_selection": false,
  75062. },
  75063. });
  75064. let createNode = (parent, text, icon, object) => {
  75065. let nodeID = tree.jstree('create_node', parent, {
  75066. "text": text,
  75067. "icon": icon,
  75068. "data": object
  75069. },
  75070. "last", false, false);
  75071. if(object.visible){
  75072. tree.jstree('check_node', nodeID);
  75073. }else {
  75074. tree.jstree('uncheck_node', nodeID);
  75075. }
  75076. return nodeID;
  75077. };
  75078. let pcID = tree.jstree('create_node', "#", { "text": "<b>Point Clouds</b>", "id": "pointclouds"}, "last", false, false);
  75079. let measurementID = tree.jstree('create_node', "#", { "text": "<b>Measurements</b>", "id": "measurements" }, "last", false, false);
  75080. let annotationsID = tree.jstree('create_node', "#", { "text": "<b>Annotations</b>", "id": "annotations" }, "last", false, false);
  75081. let otherID = tree.jstree('create_node', "#", { "text": "<b>Other</b>", "id": "other" }, "last", false, false);
  75082. let vectorsID = tree.jstree('create_node', "#", { "text": "<b>Vectors</b>", "id": "vectors" }, "last", false, false);
  75083. let imagesID = tree.jstree('create_node', "#", { "text": "<b> Images</b>", "id": "images" }, "last", false, false);
  75084. tree.jstree("check_node", pcID);
  75085. tree.jstree("check_node", measurementID);
  75086. tree.jstree("check_node", annotationsID);
  75087. tree.jstree("check_node", otherID);
  75088. tree.jstree("check_node", vectorsID);
  75089. tree.jstree("check_node", imagesID);
  75090. tree.on('create_node.jstree', (e, data) => {
  75091. tree.jstree("open_all");
  75092. });
  75093. tree.on("select_node.jstree", (e, data) => {
  75094. let object = data.node.data;
  75095. propertiesPanel.set(object);
  75096. this.viewer.inputHandler.deselectAll();
  75097. if(object instanceof Volume$1){
  75098. this.viewer.inputHandler.toggleSelection(object);
  75099. }
  75100. $(this.viewer.renderer.domElement).focus();
  75101. });
  75102. tree.on("deselect_node.jstree", (e, data) => {
  75103. propertiesPanel.set(null);
  75104. });
  75105. tree.on("delete_node.jstree", (e, data) => {
  75106. propertiesPanel.set(null);
  75107. });
  75108. tree.on('dblclick','.jstree-anchor', (e) => {
  75109. let instance = $.jstree.reference(e.target);
  75110. let node = instance.get_node(e.target);
  75111. let object = node.data;
  75112. // ignore double click on checkbox
  75113. if(e.target.classList.contains("jstree-checkbox")){
  75114. return;
  75115. }
  75116. if(object instanceof PointCloudTree){
  75117. let box = this.viewer.getBoundingBox([object]);
  75118. let node = new Object3D();
  75119. node.boundingBox = box;
  75120. this.viewer.zoomTo(node, 1, 500);
  75121. }else if(object instanceof Measure$1){
  75122. let points = object.points.map(p => p.position);
  75123. let box = new Box3().setFromPoints(points);
  75124. if(box.getSize(new Vector3()).length() == 0){
  75125. box.min = box.max.clone();//禁止相同
  75126. box.expandByVector(new Vector3(1,1,1));
  75127. }
  75128. let node = new Object3D();
  75129. node.boundingBox = box;
  75130. this.viewer.zoomTo(node, 2, 500);
  75131. }else if(object instanceof Profile){
  75132. let points = object.points;
  75133. let box = new Box3().setFromPoints(points);
  75134. if(box.getSize(new Vector3()).length() > 0){
  75135. let node = new Object3D();
  75136. node.boundingBox = box;
  75137. this.viewer.zoomTo(node, 1, 500);
  75138. }
  75139. }else if(object instanceof Volume$1){
  75140. let box = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  75141. if(box.getSize(new Vector3()).length() > 0){
  75142. let node = new Object3D();
  75143. node.boundingBox = box;
  75144. this.viewer.zoomTo(node, 1, 500);
  75145. }
  75146. }else if(object instanceof Annotation){
  75147. object.moveHere(this.viewer.scene.getActiveCamera());
  75148. }else if(object instanceof PolygonClipVolume){
  75149. let dir = object.camera.getWorldDirection(new Vector3());
  75150. let target;
  75151. if(object.camera instanceof OrthographicCamera){
  75152. dir.multiplyScalar(object.camera.right);
  75153. target = new Vector3().addVectors(object.camera.position, dir);
  75154. this.viewer.setCameraMode(CameraMode.ORTHOGRAPHIC);
  75155. }else if(object.camera instanceof PerspectiveCamera){
  75156. dir.multiplyScalar(this.viewer.scene.view.radius);
  75157. target = new Vector3().addVectors(object.camera.position, dir);
  75158. this.viewer.setCameraMode(CameraMode.PERSPECTIVE);
  75159. }
  75160. this.viewer.scene.view.position.copy(object.camera.position);
  75161. this.viewer.scene.view.lookAt(target);
  75162. }else if(object.type === "SpotLight"){
  75163. let distance = (object.distance > 0) ? object.distance / 4 : 5 * 1000;
  75164. let position = object.position;
  75165. let target = new Vector3().addVectors(
  75166. position,
  75167. object.getWorldDirection(new Vector3()).multiplyScalar(distance));
  75168. this.viewer.scene.view.position.copy(object.position);
  75169. this.viewer.scene.view.lookAt(target);
  75170. }else if(object instanceof Object3D){
  75171. let box = new Box3().setFromObject(object);
  75172. if(box.getSize(new Vector3()).length() > 0){
  75173. let node = new Object3D();
  75174. node.boundingBox = box;
  75175. this.viewer.zoomTo(node, 1, 500);
  75176. }
  75177. }else if(object instanceof OrientedImage){
  75178. // TODO zoom to images
  75179. // let box = new THREE.Box3().setFromObject(object);
  75180. // if(box.getSize(new THREE.Vector3()).length() > 0){
  75181. // let node = new THREE.Object3D();
  75182. // node.boundingBox = box;
  75183. // this.viewer.zoomTo(node, 1, 500);
  75184. // }
  75185. }else if(object instanceof Images360){
  75186. // TODO
  75187. }else if(object instanceof Geopackage){
  75188. // TODO
  75189. }
  75190. });
  75191. tree.on("uncheck_node.jstree", (e, data) => {
  75192. let object = data.node.data;
  75193. if(object){
  75194. object.visible = false;
  75195. }
  75196. });
  75197. tree.on("check_node.jstree", (e, data) => {
  75198. let object = data.node.data;
  75199. if(object){
  75200. object.visible = true;
  75201. }
  75202. });
  75203. let onPointCloudAdded = (e) => {
  75204. let pointcloud = e.pointcloud;
  75205. let cloudIcon = `${Potree.resourcePath}/icons/cloud.svg`;
  75206. let node = createNode(pcID, pointcloud.name, cloudIcon, pointcloud);
  75207. pointcloud.addEventListener("visibility_changed", () => {
  75208. if(pointcloud.visible){
  75209. tree.jstree('check_node', node);
  75210. }else {
  75211. tree.jstree('uncheck_node', node);
  75212. }
  75213. });
  75214. };
  75215. let onMeasurementAdded = (e) => {
  75216. let measurement = e.measurement;
  75217. let icon = Utils.getMeasurementIcon(measurement);
  75218. createNode(measurementID, measurement.name, icon, measurement);
  75219. };
  75220. let onVolumeAdded = (e) => {
  75221. let volume = e.volume;
  75222. let icon = Utils.getMeasurementIcon(volume);
  75223. let node = createNode(measurementID, volume.name, icon, volume);
  75224. volume.addEventListener("visibility_changed", () => {
  75225. if(volume.visible){
  75226. tree.jstree('check_node', node);
  75227. }else {
  75228. tree.jstree('uncheck_node', node);
  75229. }
  75230. });
  75231. };
  75232. let onProfileAdded = (e) => {
  75233. let profile = e.profile;
  75234. let icon = Utils.getMeasurementIcon(profile);
  75235. createNode(measurementID, profile.name, icon, profile);
  75236. };
  75237. let onAnnotationAdded = (e) => {
  75238. let annotation = e.annotation;
  75239. let annotationIcon = `${Potree.resourcePath}/icons/annotation.svg`;
  75240. let parentID = this.annotationMapping.get(annotation.parent);
  75241. let annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  75242. this.annotationMapping.set(annotation, annotationID);
  75243. annotation.addEventListener("annotation_changed", (e) => {
  75244. let annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  75245. let jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  75246. $.jstree.reference(jsonNode.id).rename_node(jsonNode.id, annotation.title);
  75247. });
  75248. };
  75249. let onCameraAnimationAdded = (e) => {
  75250. const animation = e.animation;
  75251. const animationIcon = `${Potree.resourcePath}/icons/camera_animation.svg`;
  75252. createNode(otherID, "animation", animationIcon, animation);
  75253. };
  75254. let onOrientedImagesAdded = (e) => {
  75255. const images = e.images;
  75256. const imagesIcon = `${Potree.resourcePath}/icons/picture.svg`;
  75257. const node = createNode(imagesID, "images", imagesIcon, images);
  75258. images.addEventListener("visibility_changed", () => {
  75259. if(images.visible){
  75260. tree.jstree('check_node', node);
  75261. }else {
  75262. tree.jstree('uncheck_node', node);
  75263. }
  75264. });
  75265. };
  75266. let onImages360Added = (e) => {
  75267. const images = e.images;
  75268. const imagesIcon = `${Potree.resourcePath}/icons/picture.svg`;
  75269. const node = createNode(imagesID, "360° images", imagesIcon, images);
  75270. images.addEventListener("visibility_changed", () => {
  75271. if(images.visible){
  75272. tree.jstree('check_node', node);
  75273. }else {
  75274. tree.jstree('uncheck_node', node);
  75275. }
  75276. });
  75277. };
  75278. const onGeopackageAdded = (e) => {
  75279. const geopackage = e.geopackage;
  75280. const geopackageIcon = `${Potree.resourcePath}/icons/triangle.svg`;
  75281. const tree = $(`#jstree_scene`);
  75282. const parentNode = "vectors";
  75283. for(const layer of geopackage.node.children){
  75284. const name = layer.name;
  75285. let shpPointsID = tree.jstree('create_node', parentNode, {
  75286. "text": name,
  75287. "icon": geopackageIcon,
  75288. "object": layer,
  75289. "data": layer,
  75290. },
  75291. "last", false, false);
  75292. tree.jstree(layer.visible ? "check_node" : "uncheck_node", shpPointsID);
  75293. }
  75294. };
  75295. this.viewer.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  75296. this.viewer.scene.addEventListener("measurement_added", onMeasurementAdded);
  75297. this.viewer.scene.addEventListener("profile_added", onProfileAdded);
  75298. this.viewer.scene.addEventListener("volume_added", onVolumeAdded);
  75299. this.viewer.scene.addEventListener("camera_animation_added", onCameraAnimationAdded);
  75300. this.viewer.scene.addEventListener("oriented_images_added", onOrientedImagesAdded);
  75301. this.viewer.scene.addEventListener("360_images_added", onImages360Added);
  75302. this.viewer.scene.addEventListener("geopackage_added", onGeopackageAdded);
  75303. this.viewer.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  75304. this.viewer.scene.annotations.addEventListener("annotation_added", onAnnotationAdded);
  75305. let onMeasurementRemoved = (e) => {
  75306. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  75307. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.measurement.uuid);
  75308. tree.jstree("delete_node", jsonNode.id);
  75309. };
  75310. let onVolumeRemoved = (e) => {
  75311. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  75312. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  75313. tree.jstree("delete_node", jsonNode.id);
  75314. };
  75315. let onPolygonClipVolumeRemoved = (e) => {
  75316. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  75317. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  75318. tree.jstree("delete_node", jsonNode.id);
  75319. };
  75320. let onProfileRemoved = (e) => {
  75321. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  75322. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.profile.uuid);
  75323. tree.jstree("delete_node", jsonNode.id);
  75324. };
  75325. this.viewer.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  75326. this.viewer.scene.addEventListener("volume_removed", onVolumeRemoved);
  75327. this.viewer.scene.addEventListener("polygon_clip_volume_removed", onPolygonClipVolumeRemoved);
  75328. this.viewer.scene.addEventListener("profile_removed", onProfileRemoved);
  75329. {
  75330. let annotationIcon = `${Potree.resourcePath}/icons/annotation.svg`;
  75331. this.annotationMapping = new Map();
  75332. this.annotationMapping.set(this.viewer.scene.annotations, annotationsID);
  75333. this.viewer.scene.annotations.traverseDescendants(annotation => {
  75334. let parentID = this.annotationMapping.get(annotation.parent);
  75335. let annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  75336. this.annotationMapping.set(annotation, annotationID);
  75337. });
  75338. }
  75339. const scene = this.viewer.scene;
  75340. for(let pointcloud of scene.pointclouds){
  75341. onPointCloudAdded({pointcloud: pointcloud});
  75342. }
  75343. for(let measurement of scene.measurements){
  75344. onMeasurementAdded({measurement: measurement});
  75345. }
  75346. for(let volume of [...scene.volumes, ...scene.polygonClipVolumes]){
  75347. onVolumeAdded({volume: volume});
  75348. }
  75349. for(let animation of scene.cameraAnimations){
  75350. onCameraAnimationAdded({animation: animation});
  75351. }
  75352. for(let images of scene.orientedImages){
  75353. onOrientedImagesAdded({images: images});
  75354. }
  75355. for(let images of scene.images360){
  75356. onImages360Added({images: images});
  75357. }
  75358. for(const geopackage of scene.geopackages){
  75359. onGeopackageAdded({geopackage: geopackage});
  75360. }
  75361. for(let profile of scene.profiles){
  75362. onProfileAdded({profile: profile});
  75363. }
  75364. {
  75365. createNode(otherID, "Camera", null, new Camera());
  75366. }
  75367. this.viewer.addEventListener("scene_changed", (e) => {
  75368. propertiesPanel.setScene(e.scene);
  75369. e.oldScene.removeEventListener("pointcloud_added", onPointCloudAdded);
  75370. e.oldScene.removeEventListener("measurement_added", onMeasurementAdded);
  75371. e.oldScene.removeEventListener("profile_added", onProfileAdded);
  75372. e.oldScene.removeEventListener("volume_added", onVolumeAdded);
  75373. e.oldScene.removeEventListener("polygon_clip_volume_added", onVolumeAdded);
  75374. e.oldScene.removeEventListener("measurement_removed", onMeasurementRemoved);
  75375. e.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  75376. e.scene.addEventListener("measurement_added", onMeasurementAdded);
  75377. e.scene.addEventListener("profile_added", onProfileAdded);
  75378. e.scene.addEventListener("volume_added", onVolumeAdded);
  75379. e.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  75380. e.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  75381. });
  75382. }
  75383. initClippingTool(){
  75384. this.viewer.addEventListener("cliptask_changed", (event) => {
  75385. console.log("TODO");
  75386. });
  75387. this.viewer.addEventListener("clipmethod_changed", (event) => {
  75388. console.log("TODO");
  75389. });
  75390. {
  75391. let elClipTask = $("#cliptask_options");
  75392. elClipTask.selectgroup({title: "Clip Task"});
  75393. elClipTask.find("input").click( (e) => {
  75394. this.viewer.setClipTask(ClipTask[e.target.value]);
  75395. });
  75396. let currentClipTask = Object.keys(ClipTask)
  75397. .filter(key => ClipTask[key] === this.viewer.clipTask);
  75398. elClipTask.find(`input[value=${currentClipTask}]`).trigger("click");
  75399. }
  75400. {
  75401. let elClipMethod = $("#clipmethod_options");
  75402. elClipMethod.selectgroup({title: "Clip Method"});
  75403. elClipMethod.find("input").click( (e) => {
  75404. this.viewer.setClipMethod(ClipMethod[e.target.value]);
  75405. });
  75406. let currentClipMethod = Object.keys(ClipMethod)
  75407. .filter(key => ClipMethod[key] === this.viewer.clipMethod);
  75408. elClipMethod.find(`input[value=${currentClipMethod}]`).trigger("click");
  75409. }
  75410. let clippingToolBar = $("#clipping_tools");
  75411. // CLIP VOLUME
  75412. clippingToolBar.append(this.createToolIcon(
  75413. Potree.resourcePath + '/icons/clip_volume.svg',
  75414. '[title]tt.clip_volume',
  75415. () => {
  75416. let item = this.volumeTool.startInsertion({clip: true});
  75417. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  75418. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  75419. $.jstree.reference(jsonNode.id).deselect_all();
  75420. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  75421. }
  75422. ));
  75423. // CLIP POLYGON
  75424. clippingToolBar.append(this.createToolIcon(
  75425. Potree.resourcePath + "/icons/clip-polygon.svg",
  75426. "[title]tt.clip_polygon",
  75427. () => {
  75428. let item = this.viewer.clippingTool.startInsertion({type: "polygon"});
  75429. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  75430. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  75431. $.jstree.reference(jsonNode.id).deselect_all();
  75432. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  75433. }
  75434. ));
  75435. {// SCREEN BOX SELECT
  75436. let boxSelectTool = new ScreenBoxSelectTool(this.viewer);
  75437. clippingToolBar.append(this.createToolIcon(
  75438. Potree.resourcePath + "/icons/clip-screen.svg",
  75439. "[title]tt.screen_clip_box",
  75440. () => {
  75441. if(!(this.viewer.scene.getActiveCamera() instanceof OrthographicCamera)){
  75442. this.viewer.postMessage(`Switch to Orthographic Camera Mode before using the Screen-Box-Select tool.`,
  75443. {duration: 2000});
  75444. return;
  75445. }
  75446. let item = boxSelectTool.startInsertion();
  75447. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  75448. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  75449. $.jstree.reference(jsonNode.id).deselect_all();
  75450. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  75451. }
  75452. ));
  75453. }
  75454. { // REMOVE CLIPPING TOOLS
  75455. clippingToolBar.append(this.createToolIcon(
  75456. Potree.resourcePath + "/icons/remove.svg",
  75457. "[title]tt.remove_all_clipping_volumes",
  75458. () => {
  75459. this.viewer.scene.removeAllClipVolumes();
  75460. }
  75461. ));
  75462. }
  75463. }
  75464. initFilters(){
  75465. this.initClassificationList();
  75466. this.initReturnFilters();
  75467. this.initGPSTimeFilters();
  75468. this.initPointSourceIDFilters();
  75469. }
  75470. initReturnFilters(){
  75471. let elReturnFilterPanel = $('#return_filter_panel');
  75472. { // RETURN NUMBER
  75473. let sldReturnNumber = elReturnFilterPanel.find('#sldReturnNumber');
  75474. let lblReturnNumber = elReturnFilterPanel.find('#lblReturnNumber');
  75475. sldReturnNumber.slider({
  75476. range: true,
  75477. min: 0, max: 7, step: 1,
  75478. values: [0, 7],
  75479. slide: (event, ui) => {
  75480. this.viewer.setFilterReturnNumberRange(ui.values[0], ui.values[1]);
  75481. }
  75482. });
  75483. let onReturnNumberChanged = (event) => {
  75484. let [from, to] = this.viewer.filterReturnNumberRange;
  75485. lblReturnNumber[0].innerHTML = `${from} to ${to}`;
  75486. sldReturnNumber.slider({values: [from, to]});
  75487. };
  75488. this.viewer.addEventListener('filter_return_number_range_changed', onReturnNumberChanged);
  75489. onReturnNumberChanged();
  75490. }
  75491. { // NUMBER OF RETURNS
  75492. let sldNumberOfReturns = elReturnFilterPanel.find('#sldNumberOfReturns');
  75493. let lblNumberOfReturns = elReturnFilterPanel.find('#lblNumberOfReturns');
  75494. sldNumberOfReturns.slider({
  75495. range: true,
  75496. min: 0, max: 7, step: 1,
  75497. values: [0, 7],
  75498. slide: (event, ui) => {
  75499. this.viewer.setFilterNumberOfReturnsRange(ui.values[0], ui.values[1]);
  75500. }
  75501. });
  75502. let onNumberOfReturnsChanged = (event) => {
  75503. let [from, to] = this.viewer.filterNumberOfReturnsRange;
  75504. lblNumberOfReturns[0].innerHTML = `${from} to ${to}`;
  75505. sldNumberOfReturns.slider({values: [from, to]});
  75506. };
  75507. this.viewer.addEventListener('filter_number_of_returns_range_changed', onNumberOfReturnsChanged);
  75508. onNumberOfReturnsChanged();
  75509. }
  75510. }
  75511. initGPSTimeFilters(){
  75512. let elGPSTimeFilterPanel = $('#gpstime_filter_panel');
  75513. {
  75514. let slider = new HierarchicalSlider({
  75515. levels: 4,
  75516. slide: (event) => {
  75517. this.viewer.setFilterGPSTimeRange(...event.values);
  75518. },
  75519. });
  75520. let initialized = false;
  75521. let initialize = () => {
  75522. let elRangeContainer = $("#gpstime_multilevel_range_container");
  75523. elRangeContainer[0].prepend(slider.element);
  75524. let extent = this.viewer.getGpsTimeExtent();
  75525. slider.setRange(extent);
  75526. slider.setValues(extent);
  75527. initialized = true;
  75528. };
  75529. this.viewer.addEventListener("update", (e) => {
  75530. let extent = this.viewer.getGpsTimeExtent();
  75531. let gpsTimeAvailable = extent[0] !== Infinity;
  75532. if(!initialized && gpsTimeAvailable){
  75533. initialize();
  75534. }
  75535. slider.setRange(extent); //高耗cpu
  75536. });
  75537. }
  75538. {
  75539. const txtGpsTime = elGPSTimeFilterPanel.find("#txtGpsTime");
  75540. const btnFindGpsTime = elGPSTimeFilterPanel.find("#btnFindGpsTime");
  75541. let targetTime = null;
  75542. txtGpsTime.on("input", (e) => {
  75543. const str = txtGpsTime.val();
  75544. if(!isNaN(str)){
  75545. const value = parseFloat(str);
  75546. targetTime = value;
  75547. txtGpsTime.css("background-color", "");
  75548. }else {
  75549. targetTime = null;
  75550. txtGpsTime.css("background-color", "#ff9999");
  75551. }
  75552. });
  75553. btnFindGpsTime.click( () => {
  75554. if(targetTime !== null){
  75555. viewer.moveToGpsTimeVicinity(targetTime);
  75556. }
  75557. });
  75558. }
  75559. }
  75560. initPointSourceIDFilters() {
  75561. let elPointSourceIDFilterPanel = $('#pointsourceid_filter_panel');
  75562. {
  75563. let slider = new HierarchicalSlider({
  75564. levels: 4,
  75565. range: [0, 65535],
  75566. precision: 1,
  75567. slide: (event) => {
  75568. let values = event.values;
  75569. this.viewer.setFilterPointSourceIDRange(values[0], values[1]);
  75570. }
  75571. });
  75572. let initialized = false;
  75573. let initialize = () => {
  75574. elPointSourceIDFilterPanel[0].prepend(slider.element);
  75575. initialized = true;
  75576. };
  75577. this.viewer.addEventListener("update", (e) => {
  75578. let extent = this.viewer.filterPointSourceIDRange;
  75579. if(!initialized){
  75580. initialize();
  75581. slider.setValues(extent);
  75582. }
  75583. });
  75584. }
  75585. // let lblPointSourceID = elPointSourceIDFilterPanel.find("#lblPointSourceID");
  75586. // let elPointSourceID = elPointSourceIDFilterPanel.find("#spnPointSourceID");
  75587. // let slider = new ZoomableSlider();
  75588. // elPointSourceID[0].appendChild(slider.element);
  75589. // slider.update();
  75590. // slider.change( () => {
  75591. // let range = slider.chosenRange;
  75592. // this.viewer.setFilterPointSourceIDRange(range[0], range[1]);
  75593. // });
  75594. // let onPointSourceIDExtentChanged = (event) => {
  75595. // let range = this.viewer.filterPointSourceIDExtent;
  75596. // slider.setVisibleRange(range);
  75597. // };
  75598. // let onPointSourceIDChanged = (event) => {
  75599. // let range = this.viewer.filterPointSourceIDRange;
  75600. // let precision = 1;
  75601. // let from = `${Utils.addCommas(range[0].toFixed(precision))}`;
  75602. // let to = `${Utils.addCommas(range[1].toFixed(precision))}`;
  75603. // lblPointSourceID[0].innerHTML = `${from} to ${to}`;
  75604. // slider.setRange(range);
  75605. // };
  75606. // this.viewer.addEventListener('filter_point_source_id_range_changed', onPointSourceIDChanged);
  75607. // this.viewer.addEventListener('filter_point_source_id_extent_changed', onPointSourceIDExtentChanged);
  75608. }
  75609. initClassificationList(){
  75610. let elClassificationList = $('#classificationList');
  75611. let addClassificationItem = (code, name) => {
  75612. const classification = this.viewer.classifications[code];
  75613. const inputID = 'chkClassification_' + code;
  75614. const colorPickerID = 'colorPickerClassification_' + code;
  75615. const checked = classification.visible ? "checked" : "";
  75616. let element = $(`
  75617. <li>
  75618. <label style="whitespace: nowrap; display: flex">
  75619. <input id="${inputID}" type="checkbox" ${checked}/>
  75620. <span style="flex-grow: 1">${name}</span>
  75621. <input id="${colorPickerID}" style="zoom: 0.5" />
  75622. </label>
  75623. </li>
  75624. `);
  75625. const elInput = element.find('input');
  75626. const elColorPicker = element.find(`#${colorPickerID}`);
  75627. elInput.click(event => {
  75628. this.viewer.setClassificationVisibility(code, event.target.checked);
  75629. });
  75630. let defaultColor = classification.color.map(c => c * 255).join(", ");
  75631. defaultColor = `rgb(${defaultColor})`;
  75632. elColorPicker.spectrum({
  75633. // flat: true,
  75634. color: defaultColor,
  75635. showInput: true,
  75636. preferredFormat: 'rgb',
  75637. cancelText: '',
  75638. chooseText: 'Apply',
  75639. move: color => {
  75640. let rgb = color.toRgb();
  75641. const c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  75642. classification.color = c;
  75643. },
  75644. change: color => {
  75645. let rgb = color.toRgb();
  75646. const c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  75647. classification.color = c;
  75648. }
  75649. });
  75650. elClassificationList.append(element);
  75651. };
  75652. const addToggleAllButton = () => { // toggle all button
  75653. const element = $(`
  75654. <li>
  75655. <label style="whitespace: nowrap">
  75656. <input id="toggleClassificationFilters" type="checkbox" checked/>
  75657. <span>show/hide all</span>
  75658. </label>
  75659. </li>
  75660. `);
  75661. let elInput = element.find('input');
  75662. elInput.click(event => {
  75663. this.viewer.toggleAllClassificationsVisibility();
  75664. });
  75665. elClassificationList.append(element);
  75666. };
  75667. const addInvertButton = () => {
  75668. const element = $(`
  75669. <li>
  75670. <input type="button" value="invert" />
  75671. </li>
  75672. `);
  75673. let elInput = element.find('input');
  75674. elInput.click( () => {
  75675. const classifications = this.viewer.classifications;
  75676. for(let key of Object.keys(classifications)){
  75677. let value = classifications[key];
  75678. this.viewer.setClassificationVisibility(key, !value.visible);
  75679. }
  75680. });
  75681. elClassificationList.append(element);
  75682. };
  75683. const populate = () => {
  75684. addToggleAllButton();
  75685. for (let classID in this.viewer.classifications) {
  75686. addClassificationItem(classID, this.viewer.classifications[classID].name);
  75687. }
  75688. addInvertButton();
  75689. };
  75690. populate();
  75691. this.viewer.addEventListener("classifications_changed", () => {
  75692. elClassificationList.empty();
  75693. populate();
  75694. });
  75695. this.viewer.addEventListener("classification_visibility_changed", () => {
  75696. { // set checked state of classification buttons
  75697. for(const classID of Object.keys(this.viewer.classifications)){
  75698. const classValue = this.viewer.classifications[classID];
  75699. let elItem = elClassificationList.find(`#chkClassification_${classID}`);
  75700. elItem.prop("checked", classValue.visible);
  75701. }
  75702. }
  75703. { // set checked state of toggle button based on state of all other buttons
  75704. let numVisible = 0;
  75705. let numItems = 0;
  75706. for(const key of Object.keys(this.viewer.classifications)){
  75707. if(this.viewer.classifications[key].visible){
  75708. numVisible++;
  75709. }
  75710. numItems++;
  75711. }
  75712. const allVisible = numVisible === numItems;
  75713. let elToggle = elClassificationList.find("#toggleClassificationFilters");
  75714. elToggle.prop("checked", allVisible);
  75715. }
  75716. });
  75717. }
  75718. initAccordion(){
  75719. $('.accordion > h3').each(function(){
  75720. let header = $(this);
  75721. let content = $(this).next();
  75722. //header.addClass('accordion-header ui-widget');
  75723. //content.addClass('accordion-content ui-widget');
  75724. content.hide();
  75725. header.click(() => {
  75726. content.slideToggle();
  75727. });
  75728. });
  75729. let languages = [
  75730. ["EN", "en"],
  75731. ["FR", "fr"],
  75732. ["DE", "de"],
  75733. ["JP", "jp"],
  75734. ["ES", "es"],
  75735. ["SE", "se"],
  75736. ["ZH", "zh"]
  75737. ];
  75738. let elLanguages = $('#potree_languages');
  75739. for(let i = 0; i < languages.length; i++){
  75740. let [key, value] = languages[i];
  75741. let element = $(`<a>${key}</a>`);
  75742. element.click(() => this.viewer.setLanguage(value));
  75743. if(i === 0){
  75744. element.css("margin-left", "30px");
  75745. }
  75746. elLanguages.append(element);
  75747. if(i < languages.length - 1){
  75748. elLanguages.append($(document.createTextNode(' - ')));
  75749. }
  75750. }
  75751. // to close all, call
  75752. // $(".accordion > div").hide()
  75753. // to open the, for example, tool menu, call:
  75754. // $("#menu_tools").next().show()
  75755. }
  75756. initAppearance(){
  75757. const sldPointBudget = this.dom.find('#sldPointBudget');
  75758. sldPointBudget.slider({
  75759. value: this.viewer.getPointBudget(),
  75760. min: 100 * 1000,
  75761. max: 10 * 1000 * 1000,
  75762. step: 1000,
  75763. slide: (event, ui) => { this.viewer.setPointBudget(ui.value); }
  75764. });
  75765. this.dom.find('#sldFOV').slider({
  75766. value: this.viewer.getFOV(),
  75767. min: 20,
  75768. max: 100,
  75769. step: 1,
  75770. slide: (event, ui) => { this.viewer.setFOV(ui.value); }
  75771. });
  75772. $('#sldEDLRadius').slider({
  75773. value: this.viewer.getEDLRadius(),
  75774. min: 1,
  75775. max: 4,
  75776. step: 0.01,
  75777. slide: (event, ui) => { this.viewer.setEDLRadius(ui.value); }
  75778. });
  75779. $('#sldEDLStrength').slider({
  75780. value: this.viewer.getEDLStrength(),
  75781. min: 0,
  75782. max: 5,
  75783. step: 0.01,
  75784. slide: (event, ui) => { this.viewer.setEDLStrength(ui.value); }
  75785. });
  75786. $('#sldEDLOpacity').slider({
  75787. value: this.viewer.getEDLOpacity(),
  75788. min: 0,
  75789. max: 1,
  75790. step: 0.01,
  75791. slide: (event, ui) => { this.viewer.setEDLOpacity(ui.value); }
  75792. });
  75793. this.viewer.addEventListener('point_budget_changed', (event) => {
  75794. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  75795. sldPointBudget.slider({value: this.viewer.getPointBudget()});
  75796. });
  75797. this.viewer.addEventListener('fov_changed', (event) => {
  75798. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  75799. $('#sldFOV').slider({value: this.viewer.getFOV()});
  75800. });
  75801. this.viewer.addEventListener('use_edl_changed', (event) => {
  75802. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  75803. });
  75804. this.viewer.addEventListener('edl_radius_changed', (event) => {
  75805. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  75806. $('#sldEDLRadius').slider({value: this.viewer.getEDLRadius()});
  75807. });
  75808. this.viewer.addEventListener('edl_strength_changed', (event) => {
  75809. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  75810. $('#sldEDLStrength').slider({value: this.viewer.getEDLStrength()});
  75811. });
  75812. this.viewer.addEventListener('background_changed', (event) => {
  75813. $("input[name=background][value='" + this.viewer.getBackground() + "']").prop('checked', true);
  75814. });
  75815. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  75816. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  75817. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  75818. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  75819. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  75820. {
  75821. let elBackground = $(`#background_options`);
  75822. elBackground.selectgroup();
  75823. elBackground.find("input").click( (e) => {
  75824. this.viewer.setBackground(e.target.value);
  75825. });
  75826. let currentBackground = this.viewer.getBackground();
  75827. try{
  75828. $(`input[name=background_options][value=${currentBackground}]`).trigger("click");
  75829. }catch(e){}
  75830. }
  75831. $('#chkEDLEnabled').click( () => {
  75832. this.viewer.setEDLEnabled($('#chkEDLEnabled').prop("checked"));
  75833. });
  75834. }
  75835. initNavigation(){
  75836. let elNavigation = $('#navigation');
  75837. let sldMoveSpeed = $('#sldMoveSpeed');
  75838. let lblMoveSpeed = $('#lblMoveSpeed');
  75839. elNavigation.append(this.createToolIcon(
  75840. Potree.resourcePath + '/icons/earth_controls_1.png',
  75841. '[title]tt.earth_control',
  75842. () => { this.viewer.setControls(this.viewer.earthControls); }
  75843. ));
  75844. elNavigation.append(this.createToolIcon(
  75845. Potree.resourcePath + '/icons/fps_controls.svg',
  75846. '[title]tt.flight_control',
  75847. () => {
  75848. this.viewer.setControls(this.viewer.fpControls);
  75849. this.viewer.fpControls.lockElevation = false;
  75850. }
  75851. ));
  75852. elNavigation.append(this.createToolIcon(
  75853. Potree.resourcePath + '/icons/helicopter_controls.svg',
  75854. '[title]tt.heli_control',
  75855. () => {
  75856. this.viewer.setControls(this.viewer.fpControls);
  75857. this.viewer.fpControls.lockElevation = true;
  75858. }
  75859. ));
  75860. elNavigation.append(this.createToolIcon(
  75861. Potree.resourcePath + '/icons/orbit_controls.svg',
  75862. '[title]tt.orbit_control',
  75863. () => { this.viewer.setControls(this.viewer.orbitControls); }
  75864. ));
  75865. elNavigation.append(this.createToolIcon(
  75866. Potree.resourcePath + '/icons/focus.svg',
  75867. '[title]tt.focus_control',
  75868. () => { this.viewer.fitToScreen(); }
  75869. ));
  75870. elNavigation.append(this.createToolIcon(
  75871. Potree.resourcePath + "/icons/navigation_cube.svg",
  75872. "[title]tt.navigation_cube_control",
  75873. () => {this.viewer.toggleNavigationCube();}
  75874. ));
  75875. elNavigation.append(this.createToolIcon(
  75876. Potree.resourcePath + "/images/compas.svg",
  75877. "[title]tt.compass",
  75878. () => {
  75879. const visible = !this.viewer.compass.isVisible();
  75880. this.viewer.compass.setVisible(visible);
  75881. }
  75882. ));
  75883. elNavigation.append(this.createToolIcon(
  75884. Potree.resourcePath + "/icons/camera_animation.svg",
  75885. "[title]tt.camera_animation",
  75886. () => {
  75887. const animation = CameraAnimation$1.defaultFromView(this.viewer);
  75888. viewer.scene.addCameraAnimation(animation);
  75889. }
  75890. ));
  75891. elNavigation.append("<br>");
  75892. elNavigation.append(this.createToolIcon(
  75893. Potree.resourcePath + "/icons/left.svg",
  75894. "[title]tt.left_view_control",
  75895. () => {this.viewer.setLeftView();}
  75896. ));
  75897. elNavigation.append(this.createToolIcon(
  75898. Potree.resourcePath + "/icons/right.svg",
  75899. "[title]tt.right_view_control",
  75900. () => {this.viewer.setRightView();}
  75901. ));
  75902. elNavigation.append(this.createToolIcon(
  75903. Potree.resourcePath + "/icons/front.svg",
  75904. "[title]tt.front_view_control",
  75905. () => {this.viewer.setFrontView();}
  75906. ));
  75907. elNavigation.append(this.createToolIcon(
  75908. Potree.resourcePath + "/icons/back.svg",
  75909. "[title]tt.back_view_control",
  75910. () => {this.viewer.setBackView();}
  75911. ));
  75912. elNavigation.append(this.createToolIcon(
  75913. Potree.resourcePath + "/icons/top.svg",
  75914. "[title]tt.top_view_control",
  75915. () => {this.viewer.setTopView();}
  75916. ));
  75917. elNavigation.append(this.createToolIcon(
  75918. Potree.resourcePath + "/icons/bottom.svg",
  75919. "[title]tt.bottom_view_control",
  75920. () => {this.viewer.setBottomView();}
  75921. ));
  75922. let elCameraProjection = $(`
  75923. <selectgroup id="camera_projection_options">
  75924. <option id="camera_projection_options_perspective" value="PERSPECTIVE">Perspective</option>
  75925. <option id="camera_projection_options_orthigraphic" value="ORTHOGRAPHIC">Orthographic</option>
  75926. </selectgroup>
  75927. `);
  75928. elNavigation.append(elCameraProjection);
  75929. elCameraProjection.selectgroup({title: "Camera Projection"});
  75930. elCameraProjection.find("input").click( (e) => {
  75931. this.viewer.setCameraMode(CameraMode[e.target.value]);
  75932. });
  75933. let cameraMode = Object.keys(CameraMode)
  75934. .filter(key => CameraMode[key] === this.viewer.scene.cameraMode);
  75935. elCameraProjection.find(`input[value=${cameraMode}]`).trigger("click");
  75936. let speedRange = new Vector2(1, 10 * 1000);
  75937. let toLinearSpeed = (value) => {
  75938. return Math.pow(value, 4) * speedRange.y + speedRange.x;
  75939. };
  75940. let toExpSpeed = (value) => {
  75941. return Math.pow((value - speedRange.x) / speedRange.y, 1 / 4);
  75942. };
  75943. sldMoveSpeed.slider({
  75944. value: toExpSpeed(this.viewer.getMoveSpeed()),
  75945. min: 0,
  75946. max: 1,
  75947. step: 0.01,
  75948. slide: (event, ui) => { this.viewer.setMoveSpeed(toLinearSpeed(ui.value)); }
  75949. });
  75950. this.viewer.addEventListener('move_speed_changed', (event) => {
  75951. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  75952. sldMoveSpeed.slider({value: toExpSpeed(this.viewer.getMoveSpeed())});
  75953. });
  75954. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  75955. }
  75956. initSettings(){
  75957. {
  75958. $('#sldMinNodeSize').slider({
  75959. value: this.viewer.getMinNodeSize(),
  75960. min: 0,
  75961. max: 1000,
  75962. step: 0.01,
  75963. slide: (event, ui) => { this.viewer.setMinNodeSize(ui.value); }
  75964. });
  75965. this.viewer.addEventListener('minnodesize_changed', (event) => {
  75966. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  75967. $('#sldMinNodeSize').slider({value: this.viewer.getMinNodeSize()});
  75968. });
  75969. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  75970. }
  75971. {
  75972. let elSplatQuality = $("#splat_quality_options");
  75973. elSplatQuality.selectgroup({title: "Splat Quality"});
  75974. elSplatQuality.find("input").click( (e) => {
  75975. if(e.target.value === "standard"){
  75976. this.viewer.useHQ = false;
  75977. }else if(e.target.value === "hq"){
  75978. this.viewer.useHQ = true;
  75979. }
  75980. });
  75981. let currentQuality = this.viewer.useHQ ? "hq" : "standard";
  75982. elSplatQuality.find(`input[value=${currentQuality}]`).trigger("click");
  75983. }
  75984. $('#show_bounding_box').click(() => {
  75985. this.viewer.setShowBoundingBox($('#show_bounding_box').prop("checked"));
  75986. });
  75987. $('#set_freeze').click(() => {
  75988. this.viewer.setFreeze($('#set_freeze').prop("checked"));
  75989. });
  75990. }
  75991. }
  75992. class AnnotationTool extends EventDispatcher$1{
  75993. constructor (viewer) {
  75994. super();
  75995. this.viewer = viewer;
  75996. this.renderer = viewer.renderer;
  75997. this.sg = new SphereGeometry(0.1);
  75998. this.sm = new MeshNormalMaterial();
  75999. this.s = new Mesh(this.sg, this.sm);
  76000. }
  76001. startInsertion (args = {}) {
  76002. let domElement = this.viewer.renderer.domElement;
  76003. let annotation = new Annotation({
  76004. position: [589748.270, 231444.540, 753.675],
  76005. title: "Annotation Title",
  76006. description: `Annotation Description`
  76007. });
  76008. this.dispatchEvent({type: 'start_inserting_annotation', annotation: annotation});
  76009. const annotations = this.viewer.scene.annotations;
  76010. annotations.add(annotation);
  76011. let callbacks = {
  76012. cancel: null,
  76013. finish: null,
  76014. };
  76015. let insertionCallback = (e) => {
  76016. if (e.button === MOUSE.LEFT) {
  76017. callbacks.finish();
  76018. } else if (e.button === MOUSE.RIGHT) {
  76019. callbacks.cancel();
  76020. }
  76021. };
  76022. callbacks.cancel = e => {
  76023. annotations.remove(annotation);
  76024. domElement.removeEventListener('mouseup', insertionCallback, true);
  76025. };
  76026. callbacks.finish = e => {
  76027. domElement.removeEventListener('mouseup', insertionCallback, true);
  76028. };
  76029. domElement.addEventListener('mouseup', insertionCallback, true);
  76030. let drag = (e) => {
  76031. let I = Utils.getMousePointCloudIntersection(
  76032. e.drag.end,
  76033. e.viewer.scene.getActiveCamera(),
  76034. e.viewer,
  76035. e.viewer.scene.pointclouds,
  76036. {pickClipped: true});
  76037. if (I) {
  76038. this.s.position.copy(I.location);
  76039. annotation.position.copy(I.location);
  76040. }
  76041. };
  76042. let drop = (e) => {
  76043. viewer.scene.scene.remove(this.s);
  76044. this.s.removeEventListener("drag", drag);
  76045. this.s.removeEventListener("drop", drop);
  76046. };
  76047. this.s.addEventListener('drag', drag);
  76048. this.s.addEventListener('drop', drop);
  76049. this.viewer.scene.scene.add(this.s);
  76050. this.viewer.inputHandler.startDragging(this.s);
  76051. return annotation;
  76052. }
  76053. update(){
  76054. // let camera = this.viewer.scene.getActiveCamera();
  76055. // let domElement = this.renderer.domElement;
  76056. // let measurements = this.viewer.scene.measurements;
  76057. // const renderAreaSize = this.renderer.getSize(new THREE.Vector2());
  76058. // let clientWidth = renderAreaSize.width;
  76059. // let clientHeight = renderAreaSize.height;
  76060. }
  76061. render(){
  76062. //this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  76063. }
  76064. };
  76065. //处理cursor优先级
  76066. var CursorDeal = {
  76067. priorityEvent : [//在前面的优先级高
  76068. {'zoomInCloud':'zoom-in'},
  76069. {'hoverPano':'pointer'},
  76070. {'connectPano':`url({Potree.resourcePath}/images/connect.png),auto`},
  76071. {'disconnectPano':`url({Potree.resourcePath}/images/connect-dis.png),auto`},
  76072. {'hoverLine':'pointer'},
  76073. {'hoverTranHandle':'grab'},
  76074. {"movePointcloud":'move'},
  76075. {"polygon_isIntersectSelf":'not-allowed'},
  76076. {"polygon_AtWrongPlace":'not-allowed'},
  76077. {"markerMove":'grab'},
  76078. {'mapClipMove':'move'},
  76079. {'mapClipRotate':`url({Potree.resourcePath}/images/rotate-cursor.png),auto`},
  76080. {'rotatePointcloud':`url({Potree.resourcePath}/images/rotate-cursor.png),auto`},
  76081. {'siteModelFloorDrag':'row-resize'},
  76082. {'addSth':'cell'},//or crosshair
  76083. ],
  76084. list:[], //当前存在的cursor状态
  76085. currentCursorIndex:null,
  76086. init : function(viewer, viewers){
  76087. this.priorityEvent.forEach(e=>{//刚开始Potree.resourcePath没值,现在换
  76088. for(let i in e){
  76089. e[i] = Common$1.replaceAll(e[i],'{Potree.resourcePath}',Potree.resourcePath);
  76090. }
  76091. });
  76092. this.domElements = viewers.map(e=>e.renderArea);
  76093. viewer.addEventListener("CursorChange",(e)=>{
  76094. if(e.action == 'add'){
  76095. this.add(e.name);
  76096. }else {
  76097. this.remove(e.name);
  76098. }
  76099. });
  76100. },
  76101. add : function(name){
  76102. var priorityItem = this.priorityEvent.find(e=>e[name]);
  76103. if(!priorityItem){
  76104. console.error('CursorDeal 未定义优先级 name:'+ name);
  76105. return
  76106. }
  76107. if(!this.list.includes(name)){
  76108. this.judge({addItem: priorityItem, name});
  76109. this.list.push(name);
  76110. }
  76111. },
  76112. remove : function(name){
  76113. var index = this.list.indexOf(name);
  76114. if(index > -1){
  76115. this.list.splice(index, 1);
  76116. this.judge();
  76117. }
  76118. },
  76119. judge:function(o={}){
  76120. //console.log(o,this.list)
  76121. if(o.addItem){
  76122. var addIndex = this.priorityEvent.indexOf(o.addItem);
  76123. if(addIndex < this.currentCursorIndex || this.currentCursorIndex == void 0){
  76124. this.domElements.forEach(e=>e.style.cursor = o.addItem[o.name] );
  76125. this.currentCursorIndex = addIndex;
  76126. }
  76127. }else {
  76128. var levelMax = {index:Infinity, cursor:null };
  76129. this.list.forEach(name=>{
  76130. var priorityItem = this.priorityEvent.find(e=>e[name]);
  76131. var index = this.priorityEvent.indexOf(priorityItem);
  76132. if(index < levelMax.index){
  76133. levelMax.index = index;
  76134. levelMax.cursor = priorityItem[name];
  76135. }
  76136. });
  76137. this.currentCursorIndex = levelMax.index;
  76138. this.domElements.forEach(e=>e.style.cursor = levelMax.cursor || '');
  76139. }
  76140. }
  76141. };
  76142. class SplitScreen extends EventDispatcher{
  76143. constructor (args = {}) {
  76144. super();
  76145. }
  76146. /*
  76147. viewport.targetPlane // bound中心点处的plane,方向和view一致
  76148. viewport.shiftTarget // camera的位置project在targetPlane上的位置
  76149. 这两个参数的主要目的是为了getPosOutOfModel,以及rotateSideCamera时保持相对位置
  76150. */
  76151. splitStart(cameraProps){
  76152. let viewports = [];
  76153. let subViewports = [viewer.mainViewport];
  76154. if(viewer.mapViewer){
  76155. subViewports.push(viewer.mapViewer.viewports[0]);
  76156. }
  76157. let length = cameraProps.length;
  76158. for(let i=0;i<length;i++){
  76159. let prop = cameraProps[i];
  76160. let viewport;
  76161. let v = subViewports.find(e=>e.name == (prop.name2||prop.name));
  76162. if(v){
  76163. viewport = v;
  76164. viewport.left = prop.left; viewport.bottom = prop.bottom; viewport.width = prop.width; viewport.height = prop.height;
  76165. }
  76166. if(!viewport){
  76167. let view = new ExtendView();
  76168. if(prop.limitBound)view.limitBound = prop.limitBound;
  76169. prop.direction && (view.direction = prop.direction);
  76170. viewport = new Viewport(view , this.getOrthoCamera(), prop );
  76171. if(prop.viewContainsPoints)viewport.viewContainsPoints = prop.viewContainsPoints;
  76172. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  76173. }
  76174. if(viewport.camera.type == 'OrthographicCamera' ){
  76175. viewport.targetPlane = new Plane();
  76176. viewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  76177. }
  76178. viewport.fitMargin = prop.margin;
  76179. viewports.push(viewport);
  76180. }
  76181. viewer.viewports = viewports;
  76182. viewer.updateScreenSize({forceUpdateSize:true});
  76183. viewports.forEach(viewport=>{
  76184. if(viewport.name == 'MainView')return
  76185. this.viewportFitBound(viewport, viewer.bound.boundingBox , viewer.bound.center , 0, viewport.fitMargin);
  76186. });
  76187. return viewports
  76188. }
  76189. unSplit(){
  76190. this.unfocusViewport();
  76191. viewer.inputHandler.hoverViewport = null; //清空
  76192. viewer.viewports = [viewer.mainViewport];
  76193. viewer.mainViewport.width = 1;
  76194. viewer.mainViewport.height = 1;
  76195. viewer.mainViewport.left = 0;
  76196. viewer.mainViewport.bottom = 0;
  76197. viewer.updateScreenSize({forceUpdateSize:true});
  76198. }
  76199. viewportFitBound(viewport, bound, center, duration=0, margin){
  76200. let view = viewport.view;
  76201. let info = {bound};
  76202. let {boundSize, boundCenter} = this.getViewBound(viewport, bound );
  76203. //this.setShiftTarget(viewport, boundCenter)
  76204. viewport.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), boundCenter );
  76205. viewport.targetPlane.projectPoint(center, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  76206. info.endPosition = this.getPosOutOfModel(viewport, boundSize);
  76207. //if(viewport.name == 'mapViewport')info.endPosition.z = Math.max(Potree.config.map.cameraHeight, info.endPosition.z)
  76208. info.margin = margin || {x:30, y:30};
  76209. view.moveOrthoCamera(viewport, info , duration );
  76210. }
  76211. getViewBound(viewport, boundingBox){
  76212. if(boundingBox){
  76213. boundSize = boundingBox.getSize(new Vector3);
  76214. center = boundingBox.getCenter(new Vector3);
  76215. }else {
  76216. var {boundSize, center, boundingBox} = viewer.bound;
  76217. }
  76218. if(viewport.viewContainsPoints){//视野范围内必须要包含的点,直接算入模型区域。这时候得到的boundCenter和模型中心不重合
  76219. boundingBox = boundingBox.clone();
  76220. viewport.viewContainsPoints.forEach(point=>{
  76221. boundingBox.expandByPoint(point);
  76222. });
  76223. boundSize = boundingBox.getSize(new Vector3);
  76224. center = boundingBox.getCenter(new Vector3);
  76225. }
  76226. return {boundSize, boundCenter:center }
  76227. }
  76228. getPosOutOfModel(viewport, boundSize){
  76229. //let {boundSize, center} = viewer.bound
  76230. boundSize = boundSize || this.getViewBound(viewport).boundSize;
  76231. let expand = 10;
  76232. let radius = boundSize.length(); // / 2
  76233. let position = viewport.shiftTarget.clone().sub(viewport.view.direction.clone().multiplyScalar(radius + expand));
  76234. return position
  76235. }
  76236. updateCameraOutOfModel(){//因为移动模型导致模型超出相机外,所以更新位置
  76237. viewer.viewports.forEach((viewport, i )=>{
  76238. if(viewport != viewer.mainViewport){
  76239. let {boundSize, boundCenter} = this.getViewBound(viewport);
  76240. /* viewport.targetPlane.setFromNormalAndCoplanarPoint( viewport.view.direction.clone(), boundCenter)
  76241. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget) //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  76242. */
  76243. this.setShiftTarget(viewport, boundCenter);
  76244. let endPosition = this.getPosOutOfModel(viewport, boundSize);
  76245. //if(viewport.name == 'mapViewport')endPosition.z = Math.max(Potree.config.map.cameraHeight, endPosition.z)
  76246. viewport.view.position.copy(endPosition);
  76247. }
  76248. });
  76249. }
  76250. setShiftTarget(viewport, center){
  76251. if(!viewport.targetPlane ){
  76252. viewport.targetPlane = new Plane();
  76253. viewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  76254. }
  76255. viewport.targetPlane.setFromNormalAndCoplanarPoint(viewport.view.direction, center );
  76256. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  76257. }
  76258. rotateSideCamera(viewport, angle){//侧视图绕模型中心水平旋转
  76259. //let {boundSize, center} = viewer.bound
  76260. let {boundSize, boundCenter } = this.getViewBound(viewport);
  76261. let center = this.focusCenter || boundCenter; //旋转中心,一般是所有模型的中心,除非想指定中心点
  76262. this.setShiftTarget(viewport, center);
  76263. //找到平移向量
  76264. let vec = new Vector3().subVectors(center, viewport.shiftTarget);//相对于中心的偏移值,旋转后偏移值也旋转
  76265. //旋转
  76266. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);
  76267. viewport.view.direction = viewport.view.direction.applyMatrix4(rotMatrix);
  76268. vec.applyMatrix4(rotMatrix);
  76269. viewport.shiftTarget.subVectors(center,vec); //新的
  76270. viewport.view.position = this.getPosOutOfModel(viewport, boundSize);
  76271. }
  76272. getOrthoCamera(){
  76273. let camera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  76274. camera.up.set(0,0,1);
  76275. return camera
  76276. }
  76277. focusOnViewport(name){//全屏
  76278. viewer.viewports.forEach((viewport, i )=>{
  76279. if(viewport.name == name){
  76280. this.focusInfo = {
  76281. name,
  76282. left : viewport.left, bottom : viewport.bottom, height : viewport.height, width : viewport.width
  76283. };
  76284. viewport.left = 0; viewport.bottom = 0; viewport.height = 1; viewport.width = 1;
  76285. }else {
  76286. viewport.active = false;
  76287. }
  76288. });
  76289. viewer.updateScreenSize({forceUpdateSize:true});
  76290. }
  76291. unfocusViewport(){
  76292. if(!this.focusInfo)return
  76293. viewer.viewports.forEach((viewport, i )=>{
  76294. if(this.focusInfo.name == viewport.name){//全屏的恢复
  76295. viewport.left = this.focusInfo.left;
  76296. viewport.bottom = this.focusInfo.bottom;
  76297. viewport.height = this.focusInfo.height;
  76298. viewport.width = this.focusInfo.width;
  76299. }
  76300. viewport.active = true;
  76301. });
  76302. viewer.updateScreenSize({forceUpdateSize:true});
  76303. this.focusInfo = null;
  76304. }
  76305. }
  76306. const FEET_TO_INCHES_FACTOR = 12;
  76307. const EIGHTHS_SYMBOLS = ["", "⅛", "¼", "⅜", "½", "⅝", "¾", "⅞"];//eighths 八分之……
  76308. class UnitOfMeasurement{//转化单位工具
  76309. constructor(t, e, n, i){
  76310. this.name = t,
  76311. this.symbol = e,
  76312. this.base = n,
  76313. this.factor = i;
  76314. }
  76315. toBase(t) {//换算到base
  76316. return t * this.factor
  76317. }
  76318. fromBase(t) {//换算到当前
  76319. return t / this.factor
  76320. }
  76321. }
  76322. /* var o = function t(e) {
  76323. this.gettext = e,
  76324. t.METRIC = this.gettext("metric", void 0, "measurement system"),
  76325. t.IMPERIAL = this.gettext("imperial", void 0, "measurement system")
  76326. };
  76327. e.UoMSystem = o;
  76328. let UoMSystem = {
  76329. } */
  76330. /* var MeasurementDomain = {
  76331. DISTANCE : "DISTANCE",
  76332. t.AREA = "AREA",
  76333. t.VOLUME = "VOLUME",
  76334. t.DATA = "DATA",
  76335. t
  76336. }
  76337. */
  76338. var UnitsOfMeasurement = {
  76339. MILLIMETER : ["Millimeter", "mm"],
  76340. CENTIMETER : ["Centimeter", "cm"],
  76341. METER : ["Meter", "m"],
  76342. KILOMETER : ["Kilometer", "km"],
  76343. INCH : ["Inch", "in"],
  76344. FOOT : ["Foot", "ft"],
  76345. MILE : ["Mile", "mi"],
  76346. SQUAREMETER : ["SquareMeter", "m²"],
  76347. SQUAREFOOT : ["SquareFoot", "ft²"],
  76348. CUBICMETER : ["CubicMeter", "m³"],
  76349. CUBICFOOT : ["CubicFoot", "ft³"],
  76350. BYTE : ["Byte", "B"],
  76351. KILOBYTE : ["Kilobyte", "kB"],
  76352. MEGABYTE : ["Megabyte", "MB"],
  76353. GIGABYTE : ["Gigabyte", "GB"],
  76354. TERABYTE : ["Terabyte", "TB"],
  76355. PETABYTE : ["Petabyte", "PB"],
  76356. init : function() {
  76357. var e, n, i, a, s, c, l, u, d, p, h,
  76358. f = new UnitOfMeasurement(UnitsOfMeasurement.METER[0],UnitsOfMeasurement.METER[1],void 0,1),
  76359. g = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREMETER[0],UnitsOfMeasurement.SQUAREMETER[1],void 0,1),
  76360. m = new UnitOfMeasurement(UnitsOfMeasurement.CUBICMETER[0],UnitsOfMeasurement.CUBICMETER[1],void 0,1),
  76361. v = new UnitOfMeasurement(UnitsOfMeasurement.BYTE[0],UnitsOfMeasurement.BYTE[1],void 0,1);
  76362. UnitsOfMeasurement.DISTANCE = (
  76363. (e = {})['metric'] = ((n = {})[UnitsOfMeasurement.MILLIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILLIMETER[0],UnitsOfMeasurement.MILLIMETER[1],f,.001),
  76364. n[UnitsOfMeasurement.CENTIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CENTIMETER[0],UnitsOfMeasurement.CENTIMETER[1],f,.01),
  76365. n[UnitsOfMeasurement.METER[0]] = f,
  76366. n[UnitsOfMeasurement.KILOMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOMETER[0],UnitsOfMeasurement.KILOMETER[1],f,1e3),
  76367. n),
  76368. e['imperial'] = ((i = {})[UnitsOfMeasurement.INCH[0]] = new UnitOfMeasurement(UnitsOfMeasurement.INCH[0],UnitsOfMeasurement.INCH[1],f,.0254),
  76369. i[UnitsOfMeasurement.FOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.FOOT[0],UnitsOfMeasurement.FOOT[1],f,.3048),
  76370. i[UnitsOfMeasurement.MILE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILE[0],UnitsOfMeasurement.MILE[1],f,1609.344),
  76371. i),
  76372. e);
  76373. UnitsOfMeasurement.AREA = ((a = {})['metric'] = ((s = {})[UnitsOfMeasurement.SQUAREMETER[0]] = g,
  76374. s),
  76375. a['imperial'] = ((c = {})[UnitsOfMeasurement.SQUAREFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREFOOT[0],UnitsOfMeasurement.SQUAREFOOT[1],g,.092903),
  76376. c),
  76377. a);
  76378. UnitsOfMeasurement.VOLUME = ((l = {})['metric'] = ((u = {})[UnitsOfMeasurement.CUBICMETER[0]] = m,
  76379. u),
  76380. l['imperial'] = ((d = {})[UnitsOfMeasurement.CUBICFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CUBICFOOT[0],UnitsOfMeasurement.CUBICFOOT[1],m,.0283168),
  76381. d),
  76382. l);
  76383. //数据大小
  76384. var y = ((p = {})[UnitsOfMeasurement.BYTE[0]] = v,
  76385. p[UnitsOfMeasurement.KILOBYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOBYTE[0],UnitsOfMeasurement.KILOBYTE[1],v,1e3),
  76386. p[UnitsOfMeasurement.MEGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MEGABYTE[0],UnitsOfMeasurement.MEGABYTE[1],v,1e6),
  76387. p[UnitsOfMeasurement.GIGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.GIGABYTE[0],UnitsOfMeasurement.GIGABYTE[1],v,1e9),
  76388. p[UnitsOfMeasurement.TERABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.TERABYTE[0],UnitsOfMeasurement.TERABYTE[1],v,1e12),
  76389. p[UnitsOfMeasurement.PETABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.PETABYTE[0],UnitsOfMeasurement.PETABYTE[1],v,1e15),
  76390. p);
  76391. UnitsOfMeasurement.DATA = ((h = {})['metric'] = y,
  76392. h['imperial'] = y,
  76393. h);
  76394. }
  76395. ,
  76396. getUnitsOfMeasurementByDomain : function(e) {
  76397. return this[e.toUpperCase()]
  76398. /* switch (e.toUpperCase()) {
  76399. case a.DISTANCE:
  76400. return t.DISTANCE;
  76401. case a.AREA:
  76402. return t.AREA;
  76403. case a.VOLUME:
  76404. return t.VOLUME;
  76405. case a.DATA:
  76406. return t.DATA;
  76407. default:
  76408. console.error(e + " measurement domain is not supported.")
  76409. } */
  76410. }
  76411. ,
  76412. getUnitsOfMeasurementByDomainAndSystem : function(domain, system) {
  76413. var r = this.getUnitsOfMeasurementByDomain(domain);
  76414. if (r.hasOwnProperty(system.toLowerCase()))
  76415. return r[system.toLowerCase()];
  76416. console.error(n + " measurement system is not supported.");
  76417. }
  76418. ,
  76419. getDefaultUnitByDomainAndSystem : function(e, n) {
  76420. switch (e.toUpperCase()) {
  76421. case 'DISTANCE':
  76422. switch (n.toLowerCase()) {
  76423. case 'metric':
  76424. return this.DISTANCE['metric'][this.METER[0]];
  76425. case 'imperial':
  76426. return this.DISTANCE['imperial'][this.FOOT[0]];
  76427. default:
  76428. console.error(n + " measurement system is not supported.");
  76429. }
  76430. case 'AREA':
  76431. switch (n.toLowerCase()) {
  76432. case 'metric':
  76433. return this.AREA['metric'][this.SQUAREMETER[0]];
  76434. case 'imperial':
  76435. return this.AREA['imperial'][this.SQUAREFOOT[0]];
  76436. default:
  76437. console.error(n + " measurement system is not supported.");
  76438. }
  76439. case 'VOLUME':
  76440. switch (n.toLowerCase()) {
  76441. case 'metric':
  76442. return this.VOLUME['metric'][this.CUBICMETER[0]];
  76443. case 'imperial':
  76444. return this.VOLUME['imperial'][this.CUBICFOOT[0]];
  76445. default:
  76446. console.error(n + " measurement system is not supported.");
  76447. }
  76448. case 'DATA':
  76449. switch (n.toLowerCase()) {
  76450. case 'metric':
  76451. return this.DATA['metric'][this.BYTE[0]];
  76452. case 'imperial':
  76453. return this.DATA['imperial'][this.BYTE[0]];
  76454. default:
  76455. console.error(n + " measurement system is not supported.");
  76456. }
  76457. default:
  76458. console.error(e + " measurement domain is not supported.");
  76459. }
  76460. }
  76461. };
  76462. class UnitService{
  76463. constructor(/* e, n, i */){
  76464. //this.LanguageService = e,
  76465. //this.localStorageService = n,
  76466. //this.gettext = i,
  76467. //this.unitChanged = new r.Signal,
  76468. this.LOCAL_STORAGE_KEY = "iv_unit_key";//?
  76469. UnitsOfMeasurement.init();
  76470. this.unitSystems = ['metric', 'imperial'];//[o.UoMSystem.METRIC, o.UoMSystem.IMPERIAL],
  76471. this.defaultSystem = 'metric';//'imperial'
  76472. //var a = this.LanguageService.getBrowserLocaleString().toLowerCase();
  76473. //this.defaultSystem = t.isLocaleImperial(a) ? o.UoMSystem.IMPERIAL : o.UoMSystem.METRIC,
  76474. //this.initUnit()
  76475. }
  76476. /* initUnit() {
  76477. var t = this.localStorageService.get(this.LOCAL_STORAGE_KEY);
  76478. if (t)
  76479. for (var e = 0, n = this.unitSystems; e < n.length; e++) {
  76480. var i = n[e];
  76481. if (i === t)
  76482. return void this.setUnit(i, !0)
  76483. }
  76484. this.setUnit(this.defaultSystem, !1)
  76485. }
  76486. setUnit(t, e) {
  76487. this.currentSystem !== t && (this.currentSystem = t,
  76488. this.unitChanged.emit()),
  76489. e && this.localStorageService.set(this.LOCAL_STORAGE_KEY, t)
  76490. } */
  76491. /*isLocaleImperial(e) {
  76492. return t.IMPERIAL_LOCALES.indexOf(e.toLowerCase()) >= 0
  76493. }
  76494. ,
  76495. t.IMPERIAL_LOCALES = ["en_us"],
  76496. t.ɵfac(e) {
  76497. return new (e || t)(c.ɵɵinject(l.LanguageService),
  76498. c.ɵɵinject("localStorageService"),c.ɵɵinject("gettext"))
  76499. }
  76500. ,
  76501. t.ɵprov = c.ɵɵdefineInjectable({
  76502. token: t,
  76503. factory: t.ɵfac,
  76504. providedIn: "root"
  76505. }), */
  76506. }
  76507. class UoMService{
  76508. constructor(/* UnitService */){
  76509. this.UnitService = new UnitService();/* UnitService */
  76510. }
  76511. scopedConvert (t, n, precision = 2, r, minFactor) {
  76512. return this.convert(t, n, precision, r, minFactor)
  76513. }
  76514. convert(number, domain, precision = 2, system, minFactor, ifEighths = !1, ifRestrictFactor) {
  76515. if (!number) return "";
  76516. var s = this.getMostRelevantMeasurement(domain, system || this.UnitService.currentSystem, number, minFactor, ifRestrictFactor);
  76517. return this.getFormattedMeasurementString(s[0], s[1], precision, ifEighths)
  76518. }
  76519. convertBack(number, domain, precision = 2, fromSystem, minFactor ) { //从英制转到'metric'
  76520. if (!number) return "";
  76521. var d = UnitsOfMeasurement.getDefaultUnitByDomainAndSystem(domain,'metric');
  76522. var s = this.getMostRelevantMeasurement2(domain, fromSystem, number, minFactor);
  76523. return this.getFormattedMeasurementString(s[0], d, precision )
  76524. /* 栗子:
  76525. viewer.unitConvert.convertBack(1, 'area', 5, 'imperial')
  76526. '0.09290 m²'
  76527. viewer.unitConvert.convertBack(1, 'Distance', 2, 'imperial')
  76528. '0.03 m'
  76529. */
  76530. }
  76531. getFormattedMeasurementString(number, unit, precision, ifEighths) {
  76532. var result;
  76533. if(ifEighths && unit.name === UnitsOfMeasurement.FOOT[0]){
  76534. result = this.formatImperialDistance(number * FEET_TO_INCHES_FACTOR);
  76535. }else if(ifEighths && unit.name === UnitsOfMeasurement.INCH[0]){
  76536. result = this.formatImperialDistance(number);
  76537. }else {
  76538. result = number.toLocaleString(void 0, {
  76539. minimumFractionDigits: precision,
  76540. maximumFractionDigits: precision
  76541. }) + " " + unit.symbol;
  76542. }
  76543. return result
  76544. }
  76545. formatImperialDistance(e) {
  76546. var n = Math.round(8 * e)
  76547. , i = Math.floor(n / 8)
  76548. , r = Math.floor(i / FEET_TO_INCHES_FACTOR)
  76549. , o = i - r * FEET_TO_INCHES_FACTOR
  76550. , a = EIGHTHS_SYMBOLS[n % 8]
  76551. , s = 0 === o && "" !== a ? "" : o;
  76552. "" !== s && "" !== a && (a = " " + a);
  76553. return 0 !== r ? r + "' " + s + a + '"' : "" + s + a + '"'
  76554. }
  76555. getMostRelevantMeasurement(domain, system, number, minFactor=0, ifRestrictFactor) {
  76556. /* var a = r.values(UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system))
  76557. , s = r.filter(a, function(t) {
  76558. return t.factor >= i
  76559. })
  76560. , c = r.reduce(s, function(t, e) {
  76561. return e.fromBase(number) < t.fromBase(number) && e.fromBase(number) >= 1 ? e : t
  76562. }); */
  76563. let a = [];
  76564. let u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  76565. for(let i in u){a.push(u[i]);}
  76566. let s;
  76567. if(ifRestrictFactor){//是否只用这一单位,如只用mm。如果不是,就会寻找最大的接近的单位,如设置最小为mmminFactor=0.001),则1.2米时是'1.2m'、0.2米时是'20cm'、0.002米时是'2mm'
  76568. s = a.filter(m=>m.factor == minFactor);
  76569. }else {
  76570. s = a.filter(m=>m.factor >= minFactor);
  76571. }
  76572. let c = s.reduce(function(prev, currentValue) {//reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  76573. return currentValue.fromBase(number) < prev.fromBase(number) && currentValue.fromBase(number) >= 1 ? currentValue : prev
  76574. });
  76575. return c ? [c.fromBase(number), c] : void 0
  76576. }
  76577. getMostRelevantMeasurement2(domain, system, number, minFactor=0) {//add
  76578. let a = [];
  76579. let u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  76580. for(let i in u){a.push(u[i]);}
  76581. let s = a.filter(m=>m.factor >= minFactor);
  76582. let c = s.reduce(function(prev, currentValue) {//reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  76583. return currentValue.toBase(number) < prev.toBase(number) && currentValue.toBase(number) >= 1 ? currentValue : prev
  76584. });
  76585. return c ? [c.toBase(number), c] : void 0
  76586. }
  76587. /* ɵfac(e){
  76588. return new (e || t)(c.ɵɵinject(l.UnitService))
  76589. }
  76590. ɵprov = c.ɵɵdefineInjectable({
  76591. token: t,
  76592. factory: t.ɵfac,
  76593. providedIn: "root"
  76594. }) */
  76595. }
  76596. let texLoader$8 = new TextureLoader();
  76597. let color$1 = new Color(config$1.clip.color);
  76598. let markerMats$1;
  76599. let markerSizeInfo$1 = {width2d: 40};
  76600. const pickOrders = {
  76601. marker:1,
  76602. area: 0,
  76603. };
  76604. class mapClipBox extends ctrlPolygon {
  76605. constructor (center, scale) {
  76606. center = center.clone().setZ(0);//所有Z都为0
  76607. let prop = {
  76608. points : getPoints(center, scale, 0),
  76609. closed : true,
  76610. atPlane: true,
  76611. isRect : true,
  76612. dimension : '2d'
  76613. };
  76614. super('mapClipBox', prop);
  76615. this.angle = 0;
  76616. this.createRotateBar();
  76617. this.edgeMarkers = [];
  76618. //addMarkers:
  76619. this.initData(prop);
  76620. {//areaPlane event 能拖动
  76621. this.areaPlane.addEventListener('mouseover',()=>{
  76622. viewer.dispatchEvent({
  76623. type : "CursorChange", action : "add", name:"mapClipMove"
  76624. });
  76625. });
  76626. this.areaPlane.addEventListener('mouseleave',()=>{
  76627. viewer.dispatchEvent({
  76628. type : "CursorChange", action : "remove", name:"mapClipMove"
  76629. });
  76630. });
  76631. let lastPos;
  76632. let drag = (e)=>{
  76633. let intersect = e.intersect.orthoIntersect;
  76634. if(lastPos){
  76635. let moveVec = new Vector3().subVectors(intersect, lastPos).setZ(0);
  76636. this.center.add(moveVec);
  76637. this.updatePoints();
  76638. this.dispatchEvent({type:'repos'});
  76639. }
  76640. lastPos = intersect.clone();
  76641. };
  76642. let drop = (e)=>{
  76643. lastPos = null;
  76644. };
  76645. this.areaPlane.addEventListener('drag', drag);
  76646. this.areaPlane.addEventListener('drop', drop);
  76647. }
  76648. /* this.addEventListener('dragChange',()=>{
  76649. this.updateTwoMidMarker(index+1)
  76650. }) */
  76651. Potree.Utils.setObjectLayers(this, 'mapObjects' );
  76652. }
  76653. getScale(){
  76654. return new Vector3(this.points[0].distanceTo(this.points[1]), this.points[1].distanceTo(this.points[2]) ,1)
  76655. }
  76656. addMarker(o={} ){
  76657. let marker = new Sprite$2({mat:this.getMarkerMaterial('default'), pickOrder:pickOrders.marker, sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports:viewer.mapViewer.viewports, name:"mapClipBox_marker", } );
  76658. marker.renderOrder = 3;
  76659. //marker.markerSelectStates = {}
  76660. let edge = LineDraw.createLine([new Vector3,new Vector3],{color: color$1 });
  76661. let edgeMarker = new Sprite$2({mat:this.getMarkerMaterial('default'), pickOrder:pickOrders.marker, sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports:viewer.mapViewer.viewports, name:"mapClipBox_edgePoint"} );
  76662. let mouseover = (e) => {
  76663. this.setMarkerSelected(e.object, true, 'single');
  76664. viewer.dispatchEvent({
  76665. type : "CursorChange", action : "add", name:"markerMove"
  76666. });
  76667. };
  76668. let mouseleave = (e) => {
  76669. this.setMarkerSelected(e.object, false, 'single');
  76670. viewer.dispatchEvent({
  76671. type : "CursorChange", action : "remove", name:"markerMove"
  76672. });
  76673. };
  76674. edgeMarker.addEventListener('mouseover', mouseover);
  76675. edgeMarker.addEventListener('mouseleave', mouseleave);
  76676. let dragInfo = {lastPos:null};
  76677. edgeMarker.addEventListener('drag', this.dragEdge.bind(this,dragInfo));
  76678. edgeMarker.addEventListener('drop', this.dropEdge.bind(this,dragInfo));
  76679. this.edgeMarkers.push(edgeMarker);
  76680. this.add(edgeMarker);
  76681. marker.dispatchEvent('addHoverEvent');
  76682. super.addMarker({point:o.point, marker:marker, edge});
  76683. }
  76684. dragEdge(dragInfo, e){//拖拽一个边(或一个边类型的marker),带动它的两个端点。 可以转化为拖拽marker往法线方向
  76685. var I, atMap;
  76686. atMap = e.dragViewport.name == 'mapViewport';
  76687. I = e.intersect.orthoIntersect;
  76688. if (I && dragInfo.lastPos) {
  76689. let i = this.edgeMarkers.indexOf(e.drag.object);
  76690. if (i !== -1) {
  76691. let lineNormal = math.getNormal2d({p1:this.points[i], p2:this.points[(i+1)%4]});
  76692. let moveVec = new Vector3().subVectors(I, dragInfo.lastPos).setZ(0);//移动的向量
  76693. let dragVec = moveVec.projectOnVector(lineNormal).setZ(0);//在法线上移动的向量
  76694. let newPos = new Vector3().addVectors(this.points[i], dragVec); //marker应到的位置
  76695. this.dragChange(newPos, i, atMap); //转化为这个marker的拖拽
  76696. }
  76697. }
  76698. dragInfo.lastPos = I.clone();
  76699. }
  76700. dropEdge(dragInfo, e){
  76701. dragInfo.lastPos = null;
  76702. this.setMarkerSelected(e.drag.object, false, 'single'); //拖拽时似乎没有触发mouseout
  76703. }
  76704. createAreaPlane(){
  76705. var planeMat = new MeshBasicMaterial({
  76706. color: color$1,//"#00eeff",
  76707. side:DoubleSide,
  76708. opacity:0.3,
  76709. transparent:true,
  76710. depthTest:false
  76711. });
  76712. return super.createAreaPlane(planeMat)
  76713. }
  76714. getMarkerMaterial(type) {
  76715. if(!markerMats$1){
  76716. markerMats$1 = {
  76717. default: new MeshBasicMaterial({
  76718. transparent: !0,
  76719. color: color$1,
  76720. opacity: 0.8,
  76721. map: texLoader$8.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  76722. }),
  76723. select: new MeshBasicMaterial({
  76724. transparent: !0,
  76725. color: color$1,
  76726. opacity: 1,
  76727. map: texLoader$8.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  76728. }),
  76729. };
  76730. mapClipBox.markerMats = markerMats$1;
  76731. }
  76732. return markerMats$1[type]
  76733. }
  76734. setMarkerSelected(marker, state, hoverObject){
  76735. //console.warn(marker.id , state, hoverObject)
  76736. if(state == 'hover'){
  76737. marker.material = this.getMarkerMaterial('select');
  76738. }else {
  76739. marker.material = this.getMarkerMaterial('default');
  76740. }
  76741. /* marker.markerSelectStates[hoverObject] = state
  76742. let absoluteState = false
  76743. for(var i in marker.markerSelectStates){
  76744. if(marker.markerSelectStates[i]){
  76745. absoluteState = true; break;
  76746. }
  76747. }
  76748. if(absoluteState){
  76749. marker.material = this.getMarkerMaterial('select')
  76750. }else{
  76751. marker.material = this.getMarkerMaterial('default')
  76752. }
  76753. marker.selected = absoluteState */
  76754. viewer.mapViewer.dispatchEvent('content_changed');
  76755. }
  76756. createRotateBar(){
  76757. //中心点在线的一端,整体初始在box上方
  76758. const lineLen = 1.5, circleWidth = 2, barOpacity = 0.7;
  76759. let object = new Object3D;
  76760. let bar = new Sprite$2({mat:new MeshBasicMaterial({
  76761. side:DoubleSide,
  76762. opacity: barOpacity,
  76763. transparent:true,
  76764. depthTest:false,
  76765. map: texLoader$8.load(Potree.resourcePath+'/textures/rotation_circle.png' ),
  76766. }) ,
  76767. root:object,
  76768. sizeInfo: markerSizeInfo$1,
  76769. dontFixOrient: true,
  76770. viewports:viewer.mapViewer.viewports,
  76771. name:"mapClipRotateBar"
  76772. });
  76773. bar.position.set(0,lineLen+circleWidth/2,0);
  76774. bar.scale.set(circleWidth,circleWidth,circleWidth);
  76775. bar.addEventListener('mouseover',()=>{
  76776. bar.material.opacity = 1;
  76777. viewer.dispatchEvent({
  76778. type : "CursorChange", action : "add", name:"mapClipRotate"
  76779. });
  76780. viewer.mapViewer.dispatchEvent('content_changed');
  76781. });
  76782. let leave = ()=>{
  76783. bar.material.opacity = barOpacity;
  76784. viewer.dispatchEvent({
  76785. type : "CursorChange", action : "remove", name:"mapClipRotate"
  76786. });
  76787. viewer.mapViewer.dispatchEvent('content_changed');
  76788. };
  76789. bar.addEventListener('mouseleave',leave);
  76790. this.addEventListener('dispose', leave);
  76791. let lastPos;
  76792. bar.addEventListener('drag',(e)=>{
  76793. var intersect = e.intersect.orthoIntersect;
  76794. if(lastPos){
  76795. let vec1 = new Vector3().subVectors(lastPos, this.center).setZ(0);
  76796. let vec2 = new Vector3().subVectors(intersect, this.center).setZ(0);
  76797. let angle = math.getAngle(vec1,vec2,'z');
  76798. this.angle += angle;
  76799. this.rotateBar.rotation.z = this.angle;
  76800. this.updatePoints();
  76801. this.dispatchEvent({type:'rotate', angle: this.angle});
  76802. }
  76803. lastPos = intersect.clone();
  76804. });
  76805. bar.addEventListener('drop',()=>{
  76806. lastPos = null;
  76807. viewer.dispatchEvent({
  76808. type : "CursorChange", action : "remove", name:"mapClipRotate"
  76809. });
  76810. });
  76811. let line = LineDraw.createLine([new Vector3, new Vector3(0,lineLen,0)],{color: color$1});
  76812. object.add(bar);
  76813. object.add(line);
  76814. this.add(object);
  76815. this.rotateBar = object;
  76816. this.rotateBar.bar = bar;
  76817. }
  76818. updatePoints(scale){
  76819. this.points = getPoints(this.center, scale || this.getScale(), this.angle);
  76820. this.getPoint2dInfo(this.points);
  76821. this.update({ifUpdateMarkers:true});
  76822. }
  76823. update(options={}){
  76824. super.update(options);
  76825. {//update rotateBar
  76826. let center = new Vector3().addVectors(this.points[0], this.points[1]).multiplyScalar(0.5);
  76827. this.rotateBar.position.copy(center);
  76828. this.rotateBar.bar.waitUpdate();//更新sprite matrix
  76829. }
  76830. {
  76831. for(let i=0;i<4;i++){
  76832. let current = this.points[i];
  76833. let next = this.points[(i+1)%4];
  76834. let mid = new Vector3().addVectors(current, next).multiplyScalar(0.5);
  76835. this.updateMarker(this.edgeMarkers[i], mid);
  76836. }
  76837. }
  76838. }
  76839. dispose(){
  76840. super.dispose();
  76841. this.dispatchEvent('dispose');
  76842. this.rotateBar.bar.dispose();
  76843. }
  76844. }
  76845. function getPoints(center, scale, angle=0){
  76846. let points = [
  76847. new Vector3(-scale.x/2, +scale.y/2, 0),
  76848. new Vector3(+scale.x/2, +scale.y/2, 0),
  76849. new Vector3(+scale.x/2, -scale.y/2, 0),
  76850. new Vector3(-scale.x/2, -scale.y/2, 0),
  76851. ];
  76852. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);//再旋转
  76853. points.forEach(e=>{
  76854. e.applyMatrix4(rotMatrix);
  76855. e.add(center);
  76856. });
  76857. return points
  76858. }
  76859. const defaultBoxWidth = 16; //navvis: 10
  76860. //navvis position: si {x: 0, y: 0, z: 0}
  76861. var Clip = {
  76862. bus : new EventDispatcher,
  76863. selectedDatasets : [],
  76864. changeCallback(force){
  76865. viewer.controls.setTarget(this.box.position);//绕其旋转
  76866. if(Potree.settings.isOfficial){
  76867. let fun = ()=>{
  76868. let pointclouds = this.getIntersectPointcloud();
  76869. if( Common$1.getDifferenceSet(pointclouds,this.selectedDatasets).length){
  76870. this.selectedDatasets = pointclouds;
  76871. //console.error('clipSelectedDatasets',selectedDatasets)
  76872. this.bus.dispatchEvent({type:'updateSelectedDatasets', selectedDatasets:pointclouds.map(e=>e.dataset_id) });
  76873. }
  76874. };
  76875. if(force)fun();
  76876. else Common$1.intervalTool.isWaiting('clipSelectedDatasets', fun , 300);
  76877. }
  76878. },
  76879. enter:function(){
  76880. this.previousView = {
  76881. position: viewer.images360.position,
  76882. target: viewer.scene.view.getPivot(),
  76883. displayMode : Potree.settings.displayMode,
  76884. //---
  76885. ifShowMarker : Potree.settings.ifShowMarker,
  76886. };
  76887. let pointcloud = this.getPointcloud();
  76888. let bound = pointcloud.bound; //只选取其中一个数据集的bound,而非整体,是因为担心两个数据集中间有空隙,于是刚好落在没有点云的地方。
  76889. let boundSize = bound.getSize(new Vector3());
  76890. let target = this.getTarget(bound.getCenter(new Vector3())); //navvis的位置xy是用相机位置 this.ViewService.mainView.getCamera().position 我觉得也可以用第一个漫游点的,或者最接近bound中心的漫游点
  76891. let scale = new Vector3(defaultBoxWidth,defaultBoxWidth, boundSize.z);//z和navvis一样
  76892. let eyeDir = viewer.scene.view.direction.clone().setZ(0/* -boundSize.z/3 */).multiplyScalar(-defaultBoxWidth); //为了使所在楼层不变,不修改z
  76893. //let eyeDir = scale.clone().setZ(boundSize.z/3).multiplyScalar(1.3)
  76894. let position = new Vector3().addVectors(target, eyeDir);
  76895. Potree.settings.displayMode = 'showPointCloud';
  76896. viewer.setView({
  76897. position ,
  76898. target,
  76899. duration:300,
  76900. callback:function(){
  76901. }
  76902. });
  76903. //viewer.setControls(viewer.orbitControls);
  76904. viewer.setLimitFar(false);
  76905. //viewer.setClipState(false) //暂时关闭旧的clipping
  76906. {
  76907. this.box = new BoxVolume$1({
  76908. clip:true
  76909. });
  76910. this.box.clipTask = ClipTask['SHOW_INSIDE_Big' /* "SHOW_INSIDE" */];
  76911. this.box.showBox = false;
  76912. this.box.name = "ClipBox";
  76913. this.box.position.copy(target);
  76914. this.box.scale.copy(scale);
  76915. //带动mapBox
  76916. this.box.addEventListener('position_changed',e=>{
  76917. this.mapBox.center.setX(this.box.position.x);
  76918. this.mapBox.center.setY(this.box.position.y);
  76919. this.mapBox.updatePoints();
  76920. this.changeCallback();
  76921. });
  76922. this.box.addEventListener('scale_changed',e=>{
  76923. var scale = this.box.scale;
  76924. this.mapBox.updatePoints(scale);
  76925. this.changeCallback();
  76926. });
  76927. this.box.addEventListener('orientation_changed',e=>{
  76928. this.mapBox.angle = this.box.rotation.z;
  76929. this.mapBox.rotateBar.rotation.z = this.mapBox.angle;
  76930. this.mapBox.updatePoints();
  76931. this.changeCallback();
  76932. });
  76933. viewer.scene.addVolume(this.box);
  76934. }
  76935. {//map
  76936. let boxRotateBack = ()=>{//不知道是不是这么写。 因为可能z的旋转不一定都在z
  76937. this.box.rotation.x = 0;
  76938. this.box.rotation.y = 0;
  76939. };
  76940. this.mapBox = new mapClipBox(target, scale);
  76941. viewer.mapViewer.scene.add(this.mapBox);
  76942. //带动box
  76943. this.mapBox.addEventListener('repos',e=>{
  76944. this.box.position.setX(this.mapBox.center.x);
  76945. this.box.position.setY(this.mapBox.center.y);
  76946. boxRotateBack();
  76947. this.changeCallback();
  76948. });
  76949. this.mapBox.addEventListener('dragChange',e=>{
  76950. var scale = this.mapBox.getScale();
  76951. this.box.scale.setX(scale.x);
  76952. this.box.scale.setY(scale.y);
  76953. this.box.position.setX(this.mapBox.center.x);
  76954. this.box.position.setY(this.mapBox.center.y);
  76955. boxRotateBack();
  76956. this.changeCallback();
  76957. });
  76958. this.mapBox.addEventListener('rotate',e=>{
  76959. this.box.rotation.z = this.mapBox.angle;
  76960. boxRotateBack();
  76961. this.changeCallback();
  76962. });
  76963. }
  76964. {
  76965. //viewer.setClipTask(ClipTask["SHOW_INSIDE"])
  76966. }
  76967. Potree.settings.unableNavigate = true;
  76968. Potree.settings.ifShowMarker = false;
  76969. Potree.Utils.updateVisible(viewer.measuringTool.scene, 'clipModel', false);
  76970. //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'clipModel', false)//隐藏地图游标
  76971. viewer.inputHandler.toggleSelection(this.box);
  76972. viewer.inputHandler.fixSelection = true;
  76973. viewer.transformationTool.frame.material.color.set(Potree.config.clip.color);//navvis 15899953
  76974. viewer.setPointStandardMat(true);
  76975. {
  76976. let mapVisi = false;
  76977. this.events = {
  76978. flyToPos : (e)=>{
  76979. let dis = 2;
  76980. let target = e.position;
  76981. //position = new THREE.Vector3().subVectors(target, this.scene.view.direction)
  76982. //永远朝向框的中心
  76983. /* let dir = new THREE.Vector3().subVectors(this.box.position, e.position).normalize()
  76984. position = new THREE.Vector3().subVectors(target, dir) */
  76985. target = this.box.position;
  76986. position = e.position;
  76987. //为了方便缩放操作,直接使用box中心作为target
  76988. let duration = e.duration == void 0 ? 1000 : e.duration;
  76989. viewer.scene.view.setView({position, duration, target});
  76990. },
  76991. mapVisiChange(e){
  76992. mapVisi = e.visible;
  76993. let delay = 100; //因resize了camera需要时间更新projectionMatrix
  76994. setTimeout(()=>{
  76995. let boundingBox = Clip.box.boundingBox.clone().applyMatrix4(Clip.box.matrixWorld);
  76996. if(mapVisi){//切换地图
  76997. if(viewer.fpVisiDatasets.length == 0){//不会显示任何一个floorplan图,就要就近移动到一个可见数据集里
  76998. let clouds = viewer.scene.pointclouds.filter(e=>e.visible);
  76999. if(clouds.length == 0)clouds = viewer.scene.pointclouds;
  77000. let scores = clouds.map((e,i)=>{
  77001. return [ -viewer.scene.view.position.distanceToSquared(e.bound2) , i]
  77002. });
  77003. scores = scores.sort((a,b)=> a[0] - b[0]);
  77004. let neareast = clouds[scores[0][1]];
  77005. viewer.flyToDataset({ pointcloud : neareast, duration:0});
  77006. }
  77007. if(Clip.switchMapCount == 0 || !Potree.Utils.getPos2d(viewer.scene.view.position, viewer.mapViewer.viewports[0], viewer.mapViewer.renderArea).inSight
  77008. || !Potree.Utils.isInsideFrustum(boundingBox, viewer.mapViewer.camera)){ //要使box框和游标都在屏幕内。因为游标是3d的当前位置,很可能是准备去框住的位置
  77009. let bound = boundingBox.clone();
  77010. bound.expandByPoint(viewer.scene.view.position);
  77011. let size = bound.getSize(new Vector3);
  77012. let center = bound.getCenter(new Vector3);
  77013. let margin = viewer.mainViewport.resolution.clone().multiplyScalar(0.3);
  77014. viewer.mapViewer.moveTo(center, size, 100, margin);
  77015. }
  77016. Clip.switchMapCount++;
  77017. //关于究竟是focus box还是dataset有点纠结,又或是两个的union。box和数据集可能离得很远,且无法确定当前想选择的数据集,且数据集可能无floorplan, 即使有可能也不展示……
  77018. }else {//切换3d
  77019. if(!Potree.Utils.isInsideFrustum(boundingBox, viewer.scene.getActiveCamera())){//屏幕上没有box的话
  77020. viewer.focusOnObject({boundingBox}, 'boundingBox', 100 );
  77021. }
  77022. }
  77023. },delay);
  77024. }
  77025. };
  77026. this.switchMapCount = 0;
  77027. this.bus.addEventListener('flyToPos',this.events.flyToPos);
  77028. viewer.mapViewer.addEventListener('forceVisible',this.events.mapVisiChange);
  77029. }
  77030. this.editing = true;
  77031. setTimeout(()=>{this.changeCallback(true);},1);
  77032. },
  77033. leave:function(){
  77034. viewer.inputHandler.fixSelection = false;
  77035. viewer.scene.removeVolume(this.box);
  77036. this.mapBox.dispose();
  77037. //viewer.setControls(viewer.fpControls);
  77038. Potree.settings.unableNavigate = false;
  77039. Potree.settings.ifShowMarker = this.previousView.ifShowMarker;
  77040. Potree.Utils.updateVisible(viewer.measuringTool.scene, 'clipModel', true);
  77041. //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'clipModel', true)
  77042. viewer.setView(this.previousView);
  77043. viewer.setLimitFar(true);
  77044. viewer.setPointStandardMat(false);
  77045. //viewer.setClipState(true)
  77046. viewer.controls.setTarget(null);
  77047. {
  77048. this.bus.removeEventListener('flyToPos',this.events.flyToPos);
  77049. viewer.mapViewer.removeEventListener('forceVisible',this.events.mapVisiChange);
  77050. this.events = null;
  77051. }
  77052. this.editing = false;
  77053. },
  77054. getPointcloud:function(){ //找一个离当前最近的点云,且最好有漫游点
  77055. let pointclouds = viewer.scene.pointclouds.filter(e=>e.panos.length>0);
  77056. if(pointclouds.length == 0)pointclouds = viewer.scene.pointclouds;
  77057. let result = Common$1.sortByScore(pointclouds,[],[e=>{
  77058. let center = e.bound.getCenter(new Vector3);
  77059. let size = e.bound.getSize(new Vector3).length() / 2;
  77060. let posToCenter = viewer.images360.position.distanceTo(center);
  77061. return size / posToCenter
  77062. }]);
  77063. return result[0].item
  77064. },
  77065. getTarget:function(boundCenter){//box位置。要找一个有点云的地方。方案1相机位置, 方案2接近相机的漫游点, 方案3接近中心的漫游点。选择方案2,因最大概率有点云
  77066. var target = new Vector3();
  77067. var cameraPos = viewer.images360.position;
  77068. var pano = Common$1.find(viewer.images360.panos , [], [Images360.sortFunctions.floorDisSquaredToPoint(cameraPos)]);
  77069. if(pano){
  77070. target.copy(pano.position);
  77071. target.setZ(boundCenter.z);
  77072. }else {
  77073. target.copy(boundCenter);
  77074. }
  77075. return target
  77076. },
  77077. /* switchMap:function(state){
  77078. }, */
  77079. download:function( ){
  77080. if(this.getIntersectPointcloud().length == 0){
  77081. return null
  77082. }
  77083. var visiPointclouds = viewer.scene.pointclouds.filter(e=> Potree.Utils.getObjVisiByReason(e, 'datasetSelection'));
  77084. let data = {
  77085. transformation_matrix: visiPointclouds.map((cloud)=>{
  77086. let data = {
  77087. id: cloud.dataset_id,
  77088. matrix : this.getTransformationMatrix(cloud).elements, //剪裁大框
  77089. visiMatrixes: cloud.material.clipBoxes_in.map(e=>this.getTransformationMatrix(cloud, e.inverse).elements), //若干个可见型小框(虽然现在用不到了,因为普通界面不展示这些剪裁区域)
  77090. unVisiMatrixes: cloud.material.clipBoxes_out.map(e=>this.getTransformationMatrix(cloud, e.inverse).elements), //若干个不可见型小框
  77091. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements
  77092. };
  77093. return data
  77094. }) ,
  77095. aabb: "b-0.5 -0.5 -0.5 0.5 0.5 0.5" //剪裁空间( 所有点在乘上这个矩阵后, 还能落在 1 * 1 * 1的box内的点就是所裁剪的
  77096. };
  77097. return data
  77098. //https://testlaser.4dkankan.com/indoor/t-ia44BhY/api/pointcloud/crop
  77099. },
  77100. downloadNoCrop(){//不剪裁 下载整个点云
  77101. var visiPointclouds = viewer.scene.pointclouds.filter(e=> Potree.Utils.getObjVisiByReason(e, 'datasetSelection'));
  77102. let data = {
  77103. transformation_matrix: visiPointclouds.map((cloud)=>{
  77104. let data = {
  77105. id: cloud.dataset_id,
  77106. matrix : new Matrix4().elements, //固定值
  77107. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements
  77108. };
  77109. return data
  77110. }) ,
  77111. aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //固定剪裁空间
  77112. };
  77113. console.log(data);
  77114. return data
  77115. },
  77116. getTransformationMatrix:function(pointcloud, invMatrix) {//剪裁矩阵
  77117. var invMatrix = invMatrix || this.box.matrixWorld.clone().invert();
  77118. return (new Matrix4).multiplyMatrices(invMatrix, pointcloud.transformMatrix).transpose()
  77119. },
  77120. /* getIntersectPointcloud(){
  77121. var boxBound = new THREE.Box3(
  77122. new THREE.Vector3(-0.5,-0.5,-0.5), new THREE.Vector3(0.5,0.5,0.5),
  77123. ).applyMatrix4(this.box.matrixWorld) //large boundingbox
  77124. let boxMatrixInverse = new THREE.Matrix4().copy(this.box.matrixWorld).invert();
  77125. let boxPoints = [
  77126. new THREE.Vector3(boxBound.min.x, boxBound.min.y,0),
  77127. new THREE.Vector3(boxBound.max.x, boxBound.min.y,0),
  77128. new THREE.Vector3(boxBound.max.x, boxBound.max.y,0),
  77129. new THREE.Vector3(boxBound.min.x, boxBound.max.y,0)
  77130. ]
  77131. var intersect = (pointcloud)=>{
  77132. if(!pointcloud.bound.intersectsBox(boxBound))return false
  77133. //判断box和点云的tight bound是否相交(因为box可以任意旋转,且实在找不到三维中的立方体相交的函数,所以直接用boxBound)
  77134. var points = pointcloud.getUnrotBoundPoint('all')
  77135. let rings = math.getPolygonsMixedRings([points.slice(0,4), boxPoints] , true)
  77136. //console.log(pointcloud.dataset_id, pointcloud.name, rings.length)
  77137. if(rings.length > 1 )return false
  77138. {//再用frustum和数据集的sphere相交试试,能排除一些错误
  77139. let a = Potree.Utils.isIntersectBox(points, this.box.matrixWorld)
  77140. if(!a){
  77141. console.log('没能经过isInsideBox测试')
  77142. }
  77143. return a
  77144. }
  77145. return true
  77146. }
  77147. return viewer.scene.pointclouds.filter(e=>intersect(e))
  77148. } */
  77149. getIntersectPointcloud(){
  77150. var intersect = (pointcloud)=>{
  77151. if(pointcloud.intersectBox(this.box.matrixWorld))return true
  77152. };
  77153. return viewer.scene.pointclouds.filter(e=>intersect(e))
  77154. }
  77155. };
  77156. /*
  77157. 裁剪点云时,2D界面显示全部平面图,按楼层切换显示。
  77158. 所有点云下载后点云所带的本地坐标都是场景显示的local坐标,这样才能看起来一样。
  77159. 且为了使之和坐标页面对应,坐标页面的本地坐标也是local,而非mesh_local.
  77160. */
  77161. const viewportProps = [
  77162. {
  77163. left:0.5,
  77164. bottom:0.5,
  77165. width: 0.5,height:0.5,
  77166. name : 'MainView',
  77167. //view: viewer.scene.view,
  77168. active: true,
  77169. },
  77170. {
  77171. left:0,
  77172. bottom:0.5,
  77173. width: 0.5,height:0.5,
  77174. name : 'top',
  77175. name2 : 'mapViewport',
  77176. axis:["x","y"],
  77177. direction : new Vector3(0,0,-1), //镜头朝向
  77178. //axisSign:[1,1],
  77179. active: true,
  77180. //相机位置在z轴正向
  77181. },
  77182. {
  77183. left:0.5,
  77184. bottom:0,
  77185. width: 0.5,height:0.5,
  77186. name : 'right',
  77187. axis:["y","z"],
  77188. direction : new Vector3(1,0,0),
  77189. //axisSign:[1,1],
  77190. active: true,
  77191. //相机位置在x轴负向 右下角屏
  77192. },
  77193. {
  77194. left:0,
  77195. bottom:0,
  77196. width: 0.5,height:0.5,
  77197. name : 'back',
  77198. axis:["x","z"],
  77199. direction : new Vector3(0,-1,0),
  77200. //axisSign:[-1,1], // 从镜头方向看 x向左 所以取负
  77201. active: true,
  77202. //相机位置在y轴正向 左下角屏
  77203. },
  77204. ];
  77205. var SplitScreen4Views = new SplitScreen();
  77206. SplitScreen4Views.split = function(o={}){
  77207. var defaultCamera = viewer.scene.getActiveCamera();
  77208. let {boundSize, center} = viewer.bound;
  77209. viewer.setLimitFar(false);
  77210. viewer.mapViewer.attachToMainViewer(true,'split4Screens','dontSet');
  77211. viewer.renderer.clear(); //clear back的viewport左边的1px宽的部分,因setScissor的bug
  77212. let viewports = this.splitStart(viewportProps);
  77213. //覆盖在map上、点云等其他物体之下的一层背景
  77214. let mapViewport = viewer.mapViewer.viewports[0];
  77215. mapViewport.noPointcloud = false;
  77216. //隐藏地图游标
  77217. //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'split4Screens', false)
  77218. /* viewer.images360.panos.forEach(pano=>{
  77219. Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', false) //希望这时候mapMarker已经建好了吧
  77220. }) */
  77221. /* viewer.images360.panos.forEach(pano=>{
  77222. pano.addLabel2()
  77223. Potree.Utils.updateVisible(pano.label2, 'notDisplay', true)
  77224. pano.dispatchEvent({type:'changeMarkerTex',name:'ring'})
  77225. }) */
  77226. //材质
  77227. this.statesBefore = {
  77228. pointDensity : Potree.settings.pointDensity,
  77229. displayMode : Potree.settings.displayMode,
  77230. position: viewer.images360.position,
  77231. target: viewer.scene.view.getPivot(),
  77232. currentPano: viewer.images360.currentPano,
  77233. //---
  77234. //ifShowMarker : Potree.settings.ifShowMarker,
  77235. };
  77236. viewer.setPointStandardMat(true,null,true); //切换到标准模式(主要为了mainViewport) 点云使用标准大小
  77237. var matBefore = {
  77238. opacity : new Map()
  77239. };
  77240. var newOpacityMap = new Map();
  77241. viewer.scene.pointclouds.forEach(e=>{
  77242. matBefore.opacity.set(e, e.temp.pointOpacity);
  77243. matBefore.colorType = e.material.activeAttributeName;
  77244. /* {
  77245. var map = new Map()
  77246. newOpacityMap.set(e, map )
  77247. var size = e.bound.getSize()
  77248. viewports.forEach(viewport=>{//根据bound设置opacity,越小的要靠越近,需要大的opacity。但似乎影响太大了
  77249. if(viewport.name == 'MainView')return;
  77250. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  77251. let axis = prop.axis
  77252. var width = size[axis[0]]
  77253. var height = size[axis[1]]
  77254. var area = width * height
  77255. map.set(viewport, 5000/area);
  77256. })
  77257. } */
  77258. });
  77259. let beforeRender = function(){
  77260. viewer.dealBeforeRender = true; //使不全部渲染
  77261. viewer.scene.pointclouds.forEach(e=>{
  77262. if(this.name == "MainView"){
  77263. e.material.activeAttributeName = matBefore.colorType; // 'rgba'
  77264. e.material.useFilterByNormal = false;
  77265. e.changePointOpacity(matBefore.opacity.get(e)); //1 //恢复下 e.temp.pointOpacity 其实就是1
  77266. Potree.settings.pointDensity = 'fourViewportsMain';/* 'fourViewports' */ //本来想比另外三屏高一点质量,结果发现会闪烁,因为点云加载需要时间 (navvis仿版也是一样,以后看看能否优化)
  77267. }else {
  77268. e.material.activeAttributeName = "color";
  77269. e.material.useFilterByNormal = true;
  77270. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  77271. //侧面重叠概率更大,所以透明度调小
  77272. e.changePointOpacity(this.name == "mapViewport" ? 0.5 : 0.1/* newOpacityMap.get(e).get(viewport), true */); //多数据集有的数据集很小,放大后显示特别淡
  77273. //console.log(e.name, viewport.name, e.temp.pointOpacity, e.material.opacity)
  77274. }
  77275. viewer.images360.panos.forEach(pano=>{
  77276. if(this.name == 'mapViewport'){
  77277. Potree.Utils.updateVisible(pano.marker, 'showOnMap', true, 1, 'add' );
  77278. }else {
  77279. Potree.Utils.updateVisible(pano.marker, 'showOnMap', false, 1, 'cancel' );
  77280. }
  77281. });
  77282. });
  77283. viewer.dealBeforeRender = false;
  77284. };
  77285. viewports.forEach(viewport=>{viewport.beforeRender = beforeRender;});
  77286. this.enableMap(false);
  77287. this.enableFloorplan(false);
  77288. viewer.mapViewer.setViewLimit('expand'); //多数据集距离远时可以任意远,所以不限制了。但是这样就会看到地图边界了怎么办?
  77289. //viewer.dispatchEvent({'type': 'beginSplitView' })
  77290. //viewer.updateScreenSize({forceUpdateSize:true})
  77291. //this.viewportFitBound(mapViewport, boundSize, center)
  77292. //Potree.settings.ifShowMarker = false
  77293. Potree.settings.displayMode = 'showPointCloud';
  77294. };
  77295. SplitScreen4Views.recover = function(){
  77296. this.unSplit();
  77297. viewer.mapViewer.viewports[0].beforeRender = null;
  77298. /* const {width, height} = viewer.renderer.getSize(new THREE.Vector2());
  77299. viewer.renderer.setViewport(0,0,width,height)
  77300. viewer.renderer.setScissorTest( false ); */
  77301. viewer.setView({
  77302. position: this.statesBefore.position,
  77303. target: this.statesBefore.target,
  77304. currentPano: this.statesBefore.currentPano,
  77305. duration:300,
  77306. callback:function(){
  77307. }
  77308. });
  77309. viewer.mainViewport.beforeRender = null;
  77310. viewer.setLimitFar(true);
  77311. let mapViewport = viewer.mapViewer.viewports[0];
  77312. viewer.mapViewer.attachToMainViewer(false);
  77313. //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'split4Screens', true)
  77314. /* viewer.images360.panos.forEach(pano=>{
  77315. Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', true)
  77316. }) */
  77317. /* viewer.images360.panos.forEach(pano=>{
  77318. Potree.Utils.updateVisible(pano.label2, 'notDisplay', false )
  77319. pano.dispatchEvent({type:'changeMarkerTex',name:'default'})
  77320. }) */
  77321. mapViewport.noPointcloud = true;
  77322. {
  77323. this.enableMap(Potree.settings.mapEnable);
  77324. this.enableFloorplan(Potree.settings.floorplanEnable);
  77325. if(this.floorplanListener){
  77326. viewer.mapViewer.mapLayer.removeEventListener( 'floorplanLoaded', this.floorplanListener );
  77327. this.floorplanListener = null;
  77328. }
  77329. }
  77330. Potree.settings.pointDensity = this.statesBefore.pointDensity;
  77331. if(!Potree.settings.isOfficial){
  77332. Potree.settings.displayMode = this.statesBefore.displayMode;
  77333. }
  77334. viewer.scene.pointclouds.forEach(e=>{
  77335. //e.material.color.set(this.statesBefore.mat.color)
  77336. //e.material.activeAttributeName = this.statesBefore.mat.colorType
  77337. e.material.useFilterByNormal = false;
  77338. //e.material.opacity = this.statesBefore.mat.opacity
  77339. });
  77340. viewer.setPointStandardMat(false);
  77341. viewer.mapViewer.setViewLimit('standard');
  77342. viewer.images360.panos.forEach(pano=>{
  77343. Potree.Utils.updateVisible(pano.marker, 'showOnMap', false, 1, 'cancel' );
  77344. });
  77345. //Potree.settings.ifShowMarker = this.statesBefore.ifShowMarker
  77346. //viewer.dispatchEvent({'type': 'finishSplitView' })
  77347. //viewer.updateScreenSize({forceUpdateSize:true})
  77348. };
  77349. SplitScreen4Views.updateMapViewerBG = function(){
  77350. let mapViewport = viewer.mapViewer.viewports[0];
  77351. if( this.floorplanEnabled || this.mapEnabled){
  77352. mapViewport.background = 'overlayColor';
  77353. mapViewport.backgroundColor = new Color(0,0,0);
  77354. mapViewport.backgroundOpacity = 0.5;
  77355. }else {
  77356. mapViewport.background = null;
  77357. mapViewport.backgroundColor = null;
  77358. mapViewport.backgroundOpacity = null;
  77359. }
  77360. viewer.mapViewer.mapChanged = true;
  77361. viewer.mapViewer.needUpdate = true;
  77362. };
  77363. SplitScreen4Views.setFloorplanDisplay = function(e, show=false){
  77364. e.floorplan.setEnable(show);
  77365. };
  77366. SplitScreen4Views.enableMap = function(enable){
  77367. let map = viewer.mapViewer.mapLayer.maps.find(e=>e.name == 'map');
  77368. map.setEnable(!!enable);
  77369. //viewer.mapViewer.mapGradientBG = viewer.background == 'gradient' && !enable
  77370. this.mapEnabled = enable;
  77371. this.updateMapViewerBG();
  77372. },
  77373. //直接覆盖原设置
  77374. SplitScreen4Views.enableFloorplan = function(enable){ //是否让自定义的平面图显示
  77375. let floorplans = viewer.mapViewer.mapLayer.maps.filter(e=>e.name.includes('floorplan'));
  77376. if(this.floorplanListener){
  77377. viewer.mapViewer.mapLayer.removeEventListener( 'floorplanLoaded', this.floorplanListener );
  77378. }
  77379. this.floorplanListener = (e)=>{
  77380. this.setFloorplanDisplay(e, enable);
  77381. };
  77382. viewer.mapViewer.mapLayer.addEventListener( 'floorplanLoaded', this.floorplanListener ); //万一之后才加载
  77383. if(!enable){
  77384. //隐藏平面图
  77385. floorplans.forEach(floorplan=>this.setFloorplanDisplay({floorplan},false));
  77386. }else {
  77387. floorplans.forEach(floorplan=>this.setFloorplanDisplay({floorplan},true));
  77388. }
  77389. if (enable && floorplans.length == 0) Potree.loadMapEntity('all',true);
  77390. this.floorplanEnabled = enable;
  77391. this.updateMapViewerBG();
  77392. },
  77393. /* viewportFitBound:function(viewport, boundSize, center){ //使一个viewport聚焦在某个范围
  77394. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  77395. let axis = prop.axis
  77396. let expand = 10;
  77397. let position = center.clone()
  77398. var moveAtAxis = ['x','y','z'].find(e=>!(axis.includes(e)))
  77399. if(viewport.name == 'mapViewport'){
  77400. let ori = viewport.view.position[moveAtAxis]
  77401. position[moveAtAxis] = ori //不改变这个值,尤其是mapViewer中的z
  77402. }else{
  77403. position[moveAtAxis] += boundSize[moveAtAxis]/2+expand//移动到bounding边缘外
  77404. }
  77405. viewport.view.position.copy(position)
  77406. var width = Math.max(boundSize[axis[0]], boundSize[axis[1]] * viewport.camera.aspect)//视口宽度(米)
  77407. var margin = 50 //px
  77408. viewport.camera.zoom = (viewport.resolution.x - margin) / width
  77409. viewport.camera.updateProjectionMatrix()
  77410. },
  77411. */
  77412. SplitScreen4Views.focusOnPointCloud = function(pointcloud){//三个屏都聚焦在这个点云
  77413. var boundSize = pointcloud.bound.getSize(new Vector3);
  77414. var center = pointcloud.bound.getCenter(new Vector3);
  77415. let target = pointcloud.panosBound && pointcloud.panosBound.center; //看向pano集中的地方,也就是真正有点云的地方。(因为需要展示所有点云,所以没办法用这个做为center)
  77416. this.focusOnObject(pointcloud.bound, center,target);
  77417. viewer.flyToDataset({pointcloud, dontMoveMap:true, duration:0});
  77418. };
  77419. SplitScreen4Views.focusOnObject = function(bound, center, target, duration=0){
  77420. viewer.viewports.forEach(e=>{
  77421. if(e.name == 'MainView'){
  77422. /* let len = boundSize.length()
  77423. let distance = THREE.Math.clamp(e.view.position.distanceTo(center), len * 0.01, len*0.3 ) //距离限制
  77424. //viewer.focusOnObject({position:center}, 'point', duration, {distance, direction: e.view.direction,dontMoveMap:true} )//平移镜头
  77425. //为了方便定位,直接飞到中心位置:
  77426. e.view.setView({
  77427. position:center, duration, target
  77428. }) */
  77429. }else {
  77430. this.viewportFitBound(e, bound, center);
  77431. }
  77432. });
  77433. };
  77434. var Alignment = {
  77435. SplitScreen: SplitScreen4Views,
  77436. handleState:null, //操作状态 'translate'|'rotate'
  77437. bus: new EventDispatcher(),
  77438. history : new History({
  77439. applyData: (data)=>{
  77440. data.forEach(item=>{
  77441. Alignment.applyTemp(item);
  77442. });
  77443. },
  77444. getData:(pointclouds)=>{
  77445. return Alignment.getTemp(pointclouds)
  77446. }
  77447. }),
  77448. /* prepareRecord : true,
  77449. writeToHistory(pointclouds){
  77450. if(!this.prepareRecord)return;
  77451. this.prepareRecord = false
  77452. let content = this.getTemp(pointclouds)
  77453. this.history.writeIn(content)
  77454. },
  77455. undo(){//撤销一步
  77456. let last = this.history.pop();
  77457. last && last.forEach(item=>{
  77458. this.applyTemp(item)
  77459. })
  77460. }, */
  77461. applyTemp(item){
  77462. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id+p.name == item.sid);
  77463. pointcloud.orientationUser = item.orientationUser;
  77464. pointcloud.translateUser = item.translateUser;
  77465. this.setMatrix( pointcloud );
  77466. },
  77467. getTemp(pointclouds){//记录最近一次保存后的状态,便于恢复
  77468. pointclouds = pointclouds || viewer.scene.pointclouds;
  77469. return pointclouds.map(e=>{
  77470. return {
  77471. sid : e.dataset_id+e.name,
  77472. orientationUser : e.orientationUser,
  77473. translateUser : e.translateUser.clone(),
  77474. }
  77475. } )
  77476. },
  77477. init:function(){
  77478. let transfromInfo;
  77479. viewer.fpControls.addEventListener("transformPointcloud",(e)=>{
  77480. if(e.pointclouds[0].dataset_id == Potree.settings.originDatasetId){//禁止手动移动初始数据集
  77481. return this.bus.dispatchEvent('forbitMoveOriginDataset')
  77482. }
  77483. this.history.beforeChange(e.pointclouds);
  77484. //this.writeToHistory( e.pointclouds )
  77485. if(!transfromInfo){
  77486. transfromInfo = {pointclouds:e.pointclouds};
  77487. }
  77488. if(this.handleState == 'translate'){
  77489. e.pointclouds.forEach(cloud=>Alignment.translate(cloud, e.moveVec));
  77490. }else if(this.handleState == 'rotate'){
  77491. if(Potree.settings.editType == 'pano'){
  77492. //旋转中心是intersectStart的版本
  77493. /* let center = e.intersectStart //旋转中心是mousedown的位置
  77494. if(e.intersect.equals(center))return
  77495. if(!transfromInfo){
  77496. transfromInfo = {
  77497. orientationUser : e.pointclouds[0].orientationUser,
  77498. //vecStart : e.moveVec, // 首次移动向量 只有八个方向,精度太小,所以延迟
  77499. pointclouds: e.pointclouds
  77500. }
  77501. this.bus.dispatchEvent({type:'rotateStart', startPoint:center})
  77502. return
  77503. }else if(!transfromInfo.vecStart){
  77504. let vec = new THREE.Vector3().subVectors(e.intersect, center).setZ(0)
  77505. if(vec.length() * e.camera.zoom > 30){ //在屏幕上距离初始点有一定距离后开始算
  77506. //console.log('moveVec',vec)
  77507. transfromInfo.vecStart = vec
  77508. } */
  77509. let center = e.pointclouds[0].translateUser; //旋转中心是第一个点云的位置
  77510. if(e.intersect.equals(center))return
  77511. if(!transfromInfo.vecStart){
  77512. transfromInfo.orientationUser = e.pointclouds[0].orientationUser;
  77513. transfromInfo.vecStart = new Vector3().subVectors(e.intersectStart, center).setZ(0);
  77514. }else {
  77515. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77516. let angle = math.getAngle(transfromInfo.vecStart,vec,'z');
  77517. let diffAngle = transfromInfo.orientationUser + angle - transfromInfo.pointclouds[0].orientationUser;
  77518. transfromInfo.pointclouds.forEach(cloud=>{
  77519. /* let centerNoTranfrom = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:cloud, position: center }) //中心点在数据集中的位置
  77520. Alignment.rotate(cloud, null, diffAngle)
  77521. let centerNow = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:cloud, position: centerNoTranfrom }) //中心点的现在位置
  77522. let shift = new THREE.Vector3().subVectors( center, centerNow); //偏移量
  77523. Alignment.translate(cloud,shift) //使center还保留在原位
  77524. //let centerNow1 = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:transfromInfo.pointcloud, position: centerNoTranfrom }) //中心点的现在位置
  77525. */
  77526. Alignment.rotateAround(center, cloud, null, diffAngle);
  77527. });
  77528. }
  77529. //this.bus.dispatchEvent({type:'rotate', endPoint: e.intersect})
  77530. }else {
  77531. let center = e.pointclouds[0].translateUser; //移动到的位置就是中心
  77532. if(e.intersect.equals(center))return
  77533. if(!transfromInfo.vecStart){
  77534. transfromInfo.orientationUser = e.pointclouds[0].orientationUser;
  77535. transfromInfo.vecStart = new Vector3().subVectors(e.intersectStart, center).setZ(0);
  77536. }else {
  77537. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77538. let angle = math.getAngle(transfromInfo.vecStart,vec,'z');
  77539. let diffAngle = transfromInfo.orientationUser + angle - transfromInfo.pointclouds[0].orientationUser;
  77540. Alignment.rotate(transfromInfo.pointclouds[0], null, diffAngle);
  77541. }
  77542. }
  77543. }
  77544. });
  77545. viewer.fpControls.addEventListener("end",(e)=>{
  77546. transfromInfo && this.history.afterChange(transfromInfo.pointclouds );
  77547. transfromInfo = null;
  77548. });
  77549. viewer.inputHandler.addEventListener('keydown',e=>{
  77550. if(e.keyCode == 90 && e.event.ctrlKey){//Z
  77551. this.history.undo();
  77552. }else if(e.keyCode == 89 && e.event.ctrlKey){//Y
  77553. this.history.redo();
  77554. }
  77555. });
  77556. // cursor:
  77557. let updateCursor = (e)=>{
  77558. if(e.drag || !this.editing)return //仅在鼠标不按下时更新:
  77559. let handleState = Alignment.handleState;
  77560. if(e.hoverViewport.alignment && handleState && e.hoverViewport.alignment[handleState]){
  77561. if(handleState == 'translate'){
  77562. if( e.intersect && e.intersect.location ){
  77563. viewer.dispatchEvent({
  77564. type : "CursorChange", action : "add", name:"movePointcloud"
  77565. });
  77566. }else {
  77567. viewer.dispatchEvent({
  77568. type : "CursorChange", action : "remove", name:"movePointcloud"
  77569. });
  77570. }
  77571. }else if(handleState == 'rotate'){
  77572. if( e.intersect && e.intersect.location ){
  77573. viewer.dispatchEvent({
  77574. type : "CursorChange", action : "add", name:"rotatePointcloud"
  77575. });
  77576. }else {
  77577. viewer.dispatchEvent({
  77578. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77579. });
  77580. }
  77581. }
  77582. }else {
  77583. //清空:
  77584. viewer.dispatchEvent({
  77585. type : "CursorChange", action : "remove", name:"movePointcloud"
  77586. });
  77587. viewer.dispatchEvent({
  77588. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77589. });
  77590. }
  77591. };
  77592. viewer.addEventListener('global_mousemove',updateCursor);
  77593. viewer.addEventListener('global_drop',updateCursor);//拖拽结束
  77594. viewer.addEventListener('updateModelBound', (e)=>{
  77595. if(this.editing){
  77596. this.SplitScreen.updateCameraOutOfModel();
  77597. }
  77598. });
  77599. },
  77600. setMatrix : function(pointcloud){
  77601. var vec1 = pointcloud.position; //position为数据集内部的偏移,在navvis中对应的是dataset.pointCloudSceneNode的children[0].position
  77602. var vec2 = pointcloud.translateUser;
  77603. var angle = pointcloud.orientationUser;
  77604. var pos1Matrix = new Matrix4().setPosition(vec1);//先移动到点云本身应该在的初始位置(在4dkk里和其他应用中都是在这个位置的,也能和漫游点对应上)
  77605. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);//再旋转
  77606. var pos2Matrix = new Matrix4().setPosition(vec2);//最后是平移
  77607. var matrix = new Matrix4().multiplyMatrices(pos2Matrix, rotMatrix);
  77608. pointcloud.transformMatrix = matrix.clone();//为该数据集的变化矩阵。 对应navvis的m2w_
  77609. pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert();
  77610. pointcloud.rotateMatrix = rotMatrix;
  77611. pointcloud.rotateInvMatrix.copy(rotMatrix).invert();
  77612. pointcloud.panos.forEach(e=>e.transformByPointcloud());
  77613. matrix = new Matrix4().multiplyMatrices(matrix, pos1Matrix);
  77614. //matrix.premultiply(viewer.scene.scene.matrix);////////////////////////add
  77615. pointcloud.matrix = matrix;
  77616. //pointcloud.matrixWorldNeedsUpdate = true //更新matrixWorld (非计算,直接赋值)
  77617. pointcloud.updateMatrixWorld(true);
  77618. if(this.editing){
  77619. Alignment.changeCallBack && Alignment.changeCallBack();
  77620. }
  77621. if(pointcloud.spriteNodeRoot){
  77622. pointcloud.spriteNodeRoot.matrixWorld.copy(pointcloud.matrixWorld);//.multiplyMatrices(pointcloud.matrixWorld, pointcloud.matrixWorld);
  77623. }
  77624. viewer.boundNeedUpdate = true;
  77625. //pointcloud.updateBound()
  77626. pointcloud.getPanosBound();
  77627. viewer.dispatchEvent('content_changed');
  77628. },
  77629. rotateAround(center, pointcloud, deg, angle){//绕center点转动
  77630. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg);
  77631. let vec1 = new Vector3().subVectors(pointcloud.translateUser, center);
  77632. let rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);
  77633. let vec2 = vec1.clone().applyMatrix4(rotMatrix); //将到旋转中心的偏差也转动
  77634. let vec3 = new Vector3().subVectors(vec2,vec1); //这个就是多出来的一步translateUser
  77635. this.rotate(pointcloud, deg, angle);
  77636. this.translate(pointcloud, vec3);
  77637. //绕点转动就是比普通转动多一步移动到相对center的某个位置。 1 初始点云移动到自己的position; 2 移动一个vec1 3绕原点旋转 4再移动一个原本的translateUser。 绘制出来后发现移动量就是第二步vec旋转后的偏移
  77638. },
  77639. rotate:function(pointcloud, deg, angle){//绕各自中心转动(各自的position) 假设点云位移position后0,0,0就是它的中心了(根据navvis观察这样做是绕同一个点旋转的)
  77640. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg); //正逆负顺
  77641. pointcloud.orientationUser += angle;
  77642. Alignment.setMatrix(pointcloud);
  77643. },
  77644. translate:function(pointcloud, vec){
  77645. pointcloud.translateUser.add(vec);
  77646. Alignment.setMatrix(pointcloud);
  77647. },
  77648. enter:function(){
  77649. //this.saveTemp()
  77650. this.originData = this.getTemp();
  77651. this.SplitScreen.split({alignment:true});
  77652. /* viewer.images360.panos.forEach(pano=>{
  77653. Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', false)
  77654. }) */
  77655. viewer.viewports.find(e=>e.name == 'mapViewport').alignment = {rotate:true,translate:true};
  77656. viewer.viewports.find(e=>e.name == 'right').alignment = {translate:true, translateVec:new Vector3(0,0,1)}; //只能上下移动
  77657. viewer.viewports.find(e=>e.name == 'back').alignment = {translate:true, translateVec:new Vector3(0,0,1)}; //只能上下移动
  77658. this.editing = true;
  77659. viewer.updateFpVisiDatasets();
  77660. },
  77661. leave:function(){
  77662. this.switchHandle(null);
  77663. /* this.originData.forEach(e=>{//恢复
  77664. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id == e.id)
  77665. this.translate(pointcloud, new THREE.Vector3().subVectors(e.translateUser , pointcloud.translateUser))
  77666. this.rotate(pointcloud, null, e.orientationUser - pointcloud.orientationUser)
  77667. }) */
  77668. this.originData.forEach(e=>{//恢复
  77669. this.applyTemp(e);
  77670. });
  77671. this.SplitScreen.recover();
  77672. /* viewer.images360.panos.forEach(pano=>{
  77673. Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', true)
  77674. }) */
  77675. this.editing = false;
  77676. this.history.clear();
  77677. viewer.updateFpVisiDatasets();
  77678. viewer.dispatchEvent({
  77679. type : "CursorChange", action : "remove", name:"movePointcloud"
  77680. });
  77681. viewer.dispatchEvent({
  77682. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77683. });
  77684. }
  77685. ,
  77686. switchHandle:function(state){
  77687. this.handleState = state;
  77688. //清空:
  77689. viewer.dispatchEvent({
  77690. type : "CursorChange", action : "remove", name:"movePointcloud"
  77691. });
  77692. viewer.dispatchEvent({
  77693. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77694. });
  77695. this.bus.dispatchEvent({type:'switchHandle' , state });
  77696. },
  77697. save: function(){//保存所有数据集的位置和旋转
  77698. let callback = ()=>{//保存成功后
  77699. this.originData = this.getTemp(); //this.saveTemp();
  77700. //需要修改 测量线的position。漫游点已经实时修改了
  77701. viewer.scene.measurements.forEach(e=>e.transformByPointcloud());
  77702. viewer.images360.updateCube(viewer.bound);
  77703. };
  77704. var data = viewer.scene.pointclouds.map(e=>{
  77705. let pos = viewer.transform.lonlatToLocal.inverse(e.translateUser.clone());
  77706. return {
  77707. id: e.dataset_id,
  77708. orientation : e.orientationUser,
  77709. location:[pos.x, pos.y, pos.z],
  77710. //transformMatrix: e.transformMatrix.elements,
  77711. }
  77712. });
  77713. //data = JSON.stringify(data)
  77714. //test: 退出后保留结果
  77715. if(!Potree.settings.isOfficial){
  77716. callback();
  77717. }
  77718. return {data, callback}
  77719. }
  77720. };
  77721. let texLoader$9 = new TextureLoader();
  77722. let markerMats$2;
  77723. let markerSizeInfo$2 = {width2d:35};
  77724. let color$2 = new Color('#FFF');
  77725. let faceMats;
  77726. let getFaceMat = (name)=>{
  77727. if(!faceMats){ //navvis材质可以搜gridTexture
  77728. let gridTex = texLoader$9.load( Potree.resourcePath+'/textures/gridmap.png' );
  77729. gridTex.wrapS = gridTex.wrapT = RepeatWrapping;
  77730. //gridTex.repeat.set(0.5,0.5)//放大一些
  77731. faceMats = {
  77732. dataset: new MeshStandardMaterial({
  77733. color:812922,
  77734. side:DoubleSide,
  77735. opacity:0.2,
  77736. transparent:true,
  77737. depthTest:false,
  77738. wireframe:true
  77739. }),
  77740. building: new MeshStandardMaterial({
  77741. color:812922, metalness: 0.2, roughness:0.8,
  77742. side:DoubleSide,
  77743. opacity:0.1,
  77744. transparent:true,
  77745. depthTest:true
  77746. }),
  77747. buildingSelect: new MeshStandardMaterial({
  77748. color:36582, metalness: 0, roughness:1,
  77749. side:DoubleSide,
  77750. opacity:0.1,
  77751. transparent:true,
  77752. depthTest:true
  77753. }),
  77754. floor: new MeshStandardMaterial({
  77755. color:11708469, metalness: 0.1, roughness:1,
  77756. side:DoubleSide,//BackSide,
  77757. opacity:0.05,
  77758. transparent:true,
  77759. depthTest:true,
  77760. }),
  77761. floorSelect: new DepthBasicMaterial({
  77762. map: gridTex,
  77763. color:16707151,
  77764. side:DoubleSide,//BackSide,
  77765. opacity:1,
  77766. transparent:true,
  77767. useDepth : true,
  77768. clipDistance : 1, occlusionDistance:1, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  77769. maxClipFactor:0.9, backColor:'#efe' //backColor:"#669988" ,
  77770. }),
  77771. room: new MeshStandardMaterial({
  77772. color:"#ff44ee", metalness: 0, roughness:1,
  77773. side:DoubleSide,//BackSide,
  77774. opacity:0.08,
  77775. transparent:true,
  77776. depthTest:false,
  77777. }),
  77778. roomSelect: new DepthBasicMaterial({
  77779. map: gridTex,
  77780. color:"#ff44ee",
  77781. side:DoubleSide,//BackSide,
  77782. opacity:1,
  77783. transparent:true,
  77784. useDepth : true,
  77785. clipDistance : 1, occlusionDistance:0.5, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  77786. maxClipFactor:0.8, backColor:'#ff88dd'//"#cc99c2" ,
  77787. })
  77788. };
  77789. }
  77790. return faceMats[name]
  77791. };
  77792. class BuildingBox extends ctrlPolygon{//建筑实体,包括building, floor, room
  77793. constructor(prop) {
  77794. prop.dimension = '3d';
  77795. //prop.name = Potree.config.siteModel.names[prop.buildType] +
  77796. super('siteModel_'+prop.buildType, prop);
  77797. this.midMarkers = [];
  77798. this.buildChildren = [];//子实体
  77799. this.holes = []; //在这创建的hole
  77800. this.parentHoles = [];//floor从building那得到的当层holes
  77801. this.mats = {}; //材质
  77802. this.panos = this.panos || [];
  77803. this.center; //中心点
  77804. if(this.buildType=='floor'){
  77805. this.points = prop.points = this.buildParent.points;//完全等于建筑的点
  77806. this.buildParent.holes.forEach(hole=>{//从building获取holes
  77807. let floorHole = new BuildingBox({
  77808. buildType : 'hole',
  77809. buildParent:this,
  77810. originHole : hole, //整栋大楼在当层的hole
  77811. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77812. });
  77813. this.parentHoles.push(floorHole);
  77814. this.add(floorHole);
  77815. floorHole.points = hole.points;//完全等于建筑的点
  77816. });
  77817. }
  77818. if(this.buildType == 'room' || this.buildType == 'hole'){
  77819. this.restrictArea = this.buildParent; //不能超出的区域
  77820. }
  77821. if(this.buildParent)this.dontDragFloorHeight = this.buildParent.dontDragFloorHeight;
  77822. if(this.buildType != 'hole'){
  77823. this.box = this.createBox(); //无论是否edit都绘制的原因:为了将在外的点移到在内,需要用mesh来获取intersect
  77824. this.add(this.box);
  77825. this.box.visible = !!this.ifDraw;
  77826. }
  77827. if(this.ifDraw){ //只存储空间模型信息,不绘制
  77828. {
  77829. this.lineMesh = LineDraw.createLine([],{color: color$2});
  77830. this.lineMesh.name = 'buildingLines';
  77831. this.lineMesh.visible = false;
  77832. this.add(this.lineMesh);
  77833. Potree.Utils.setObjectLayers(this.lineMesh, 'bothMapAndScene' );
  77834. }
  77835. this.addEventListener('dragChange',(e)=>{ //修改中点
  77836. this.updateTwoMidMarker(e.index);
  77837. });
  77838. }
  77839. this.initData(prop);
  77840. }
  77841. initData(prop){
  77842. if(prop.ifDraw){
  77843. super.initData(prop);
  77844. }else {
  77845. if(prop.points){
  77846. this.points = prop.points;
  77847. }
  77848. }
  77849. }
  77850. intersectPointcloudVolume(pointcloud){//和pointcloud的重叠体积
  77851. return this.intersectPointcloudArea(pointcloud) * this.coverPointcloudHeight(pointcloud)
  77852. }
  77853. coverPointcloudHeight(pointcloud, getPercent){
  77854. let bound2 = pointcloud.bound;
  77855. let {zMin , zMax} = this.getRealZ();
  77856. let min = Math.min(zMin, bound2.min.z);
  77857. let max = Math.max(zMax, bound2.max.z);
  77858. let height1 = zMax - zMin;
  77859. let height2 = bound2.max.z-bound2.min.z;
  77860. let coverHeight = height1 + height2 - (max-min);//重叠高度 <=0是没重叠
  77861. if(getPercent){
  77862. return coverHeight / height1
  77863. }
  77864. return coverHeight
  77865. }
  77866. intersectPointcloudArea(pointcloud, getPercent){//和pointcloud的重叠面积
  77867. var bound = this.getBound();
  77868. let bound2 = pointcloud.bound;
  77869. if(!bound.intersectsBox(bound2)) return 0;
  77870. let boxPoints = pointcloud.getUnrotBoundPoint(); //获取tightBound的四个点。 如果是有旋转角度的点云,这个和pointcloud.bound的四个点是不一致的,覆盖面积小于pointcloud.bound
  77871. let areaWhole = 0;
  77872. let area1 = this.getArea();
  77873. let area2 = Math.abs(math.getArea(boxPoints));
  77874. {//计算points与点云总面积 (但是把hole也加入了面积)(并集,重叠部分只算一次)
  77875. let rings = math.getPolygonsMixedRings([this.points, boxPoints] );
  77876. rings.forEach(e=>{
  77877. areaWhole+=e.area;
  77878. });
  77879. }
  77880. let coverHoleArea = 0; //holes与数据集重叠的部分
  77881. let holes = this.holes.concat(this.parentHoles);
  77882. let holesArea = 0; //所有holes面积相加
  77883. let areaHoleWithPointcloud = 0; //hole和点云的面积并集
  77884. if(holes.length>0){//还要再扣除holes与数据集重叠的部分。其中holes为mix轮廓
  77885. let outHoles = [];//没有重合的holes的外轮廓
  77886. /* if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  77887. let holes_ = holes.map(e=>e.points)
  77888. outHoles = math.getPolygonsMixedRings(holes_, true )
  77889. outHoles.forEach(e=>{
  77890. holesArea+=e.area
  77891. })
  77892. outHoles = outHoles.map(e=>e.points)
  77893. }else{
  77894. outHoles = holes.map(e=>e.points)
  77895. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)))
  77896. } */
  77897. holesArea = this.getHolesArea();
  77898. //holes与数据集重叠的部分
  77899. {
  77900. let polygons = outHoles.concat([boxPoints]);
  77901. let rings = math.getPolygonsMixedRings(polygons);
  77902. rings.forEach(e=>{
  77903. areaHoleWithPointcloud+=e.area;
  77904. });
  77905. coverHoleArea = holesArea + area2 - areaHoleWithPointcloud;//hole和点云的交集
  77906. }
  77907. }
  77908. let coverArea = area1 + area2 - areaWhole - coverHoleArea; //重叠面积
  77909. if(getPercent){
  77910. return {
  77911. toEntity:coverArea / this.getArea(true), //占entity
  77912. toPointcloud:coverArea / area2 //占点云
  77913. }
  77914. }
  77915. return coverArea
  77916. }
  77917. addHole(points=[]){
  77918. let prop = {
  77919. buildType : 'hole',
  77920. zMin : this.zMin,
  77921. zMax : this.zMax,
  77922. points,
  77923. buildParent:this,
  77924. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77925. };
  77926. //hole的zMin zMax跟随buildParent
  77927. var hole = new BuildingBox(prop);
  77928. this.holes.push(hole);
  77929. if(this.buildType == 'building'){//为每一层添加对应的hole
  77930. this.buildChildren.forEach(floor=>{
  77931. let floorHole = new BuildingBox({
  77932. buildType : 'hole',
  77933. zMin : this.zMin,
  77934. zMax : this.zMax,
  77935. buildParent:floor,
  77936. originHole : hole, //整栋大楼在当层的hole
  77937. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77938. });
  77939. floor.parentHoles.push(floorHole);
  77940. floor.add(floorHole);
  77941. floorHole.points = hole.points;//完全等于建筑的点
  77942. });
  77943. }
  77944. this.add(hole);//直接加在这,不加meshGroup了
  77945. this.update(); //update box mesh
  77946. return hole
  77947. //hole不创建box,只有它的buildParent需要更新box。 但有线条和marker. hole不在buildChildren里,但有buildParent
  77948. }
  77949. removeHole(hole){// 这个hole不会是parentHoles里的。
  77950. hole.dispose();
  77951. if(this.buildType == 'building'){ //若是整栋大楼的hole,在每层去除它的对应hole
  77952. this.buildChildren.forEach(floor=>{
  77953. let holeAtFloor = floor.parentHoles.find(e=>e.originHole == this );
  77954. let index = floor.parentHoles.indexOf(holeAtFloor);
  77955. index > -1 && floor.parentHoles.splice(index, 1);
  77956. holeAtFloor.dispose();
  77957. });
  77958. }
  77959. let index = this.holes.indexOf(hole);
  77960. if(index>-1){
  77961. this.holes.splice(index, 1);
  77962. }
  77963. this.remove(hole);
  77964. this.update();
  77965. }
  77966. createBox(){
  77967. var geometry = new Geometry();
  77968. this.mats.boxDefault = getFaceMat(this.buildType);
  77969. this.mats.boxSelected = getFaceMat(this.buildType+'Select');
  77970. var mesh = new Mesh(geometry, this.mats.boxDefault);
  77971. mesh.name = 'buildingBox';
  77972. if(this.buildType == 'floor'){
  77973. Potree.Utils.setObjectLayers(mesh, 'siteModelMapUnvisi' ); //楼层默认在地图不显示,为了不会叠加透明度
  77974. //mesh.renderOrder = 1
  77975. }else {
  77976. /* if(this.buildType == 'room'){
  77977. mesh.renderOrder = 2
  77978. } */
  77979. Potree.Utils.setObjectLayers(mesh, 'bothMapAndScene' );
  77980. }
  77981. //mesh.frustumCulled = false;
  77982. return mesh
  77983. }
  77984. addMarker(o={} ){
  77985. if(this.buildType=='floor')return; //楼层不需要marker
  77986. let marker = new Sprite$2({mat:this.getMarkerMaterial('default'), renderOrder : 3, sizeInfo: markerSizeInfo$2, dontFixOrient: true, name:"building_marker"} );
  77987. Potree.Utils.setObjectLayers(marker, 'siteModeOnlyMapVisi' );
  77988. o.marker = marker;
  77989. super.addMarker(o);
  77990. if(!this.selected)Potree.Utils.updateVisible(marker,'select',false);
  77991. let addClickEvent = (e)=>{
  77992. let click = (e) => {
  77993. this.dispatchEvent({type:'clickMarker', marker } ); //由entity发送给sitemodel统一处理
  77994. };
  77995. marker.addEventListener('click', click);
  77996. marker.addEventListener('clickSelect', (e)=>{
  77997. this.setMarkerSelected(marker, e.state ? 'select' : 'unselect' );
  77998. });
  77999. marker.removeEventListener('addHoverEvent',addClickEvent);
  78000. };
  78001. marker.addEventListener('addHoverEvent',addClickEvent);//当非isNew时才添加事件
  78002. if(!this.isNew){
  78003. marker.dispatchEvent('addHoverEvent');
  78004. }
  78005. return marker
  78006. }
  78007. removeMarker(index){
  78008. super.removeMarker(index);
  78009. if(!this.isNew){
  78010. //重新添加midMarkers
  78011. this.midMarkers.forEach(e=>this.remove(e));
  78012. this.midMarkers = [];
  78013. this.addMidMarkers();
  78014. }
  78015. this.update();
  78016. if(this.points.length == 2 && this.box){//清除原先length>=3时候的
  78017. this.box.geometry = new Geometry();
  78018. }
  78019. }
  78020. addMidMarker(index, point){
  78021. if(this.buildType=='floor')return; //楼层不需要marker
  78022. let marker = new Sprite$2({mat:this.getMarkerMaterial('midPrepare'), sizeInfo: markerSizeInfo$2, dontFixOrient: true, name:"building_midMarker"} );
  78023. this.midMarkers = [...this.midMarkers.slice(0,index), marker, ...this.midMarkers.slice(index,this.midMarkers.length)];
  78024. marker.renderOrder = 3;
  78025. Potree.Utils.setObjectLayers(marker, 'siteModeOnlyMapVisi' );
  78026. { // Event Listeners
  78027. let mouseover = (e) => {
  78028. this.setMarkerSelected(e.object, 'hover', 'single');
  78029. viewer.dispatchEvent({
  78030. type : "CursorChange", action : "add", name:"markerMove"
  78031. });
  78032. };
  78033. let mouseleave = (e) => {
  78034. this.setMarkerSelected(e.object, 'unhover', 'single');
  78035. viewer.dispatchEvent({
  78036. type : "CursorChange", action : "remove", name:"markerMove"
  78037. });
  78038. };
  78039. let drag = (e) => {
  78040. let index = this.midMarkers.indexOf(marker);
  78041. let newMarker = this.addMarker({index:(index+1), point:marker.position.clone() });
  78042. this.addMidMarker(index+1, new Vector3 );
  78043. this.updateTwoMidMarker(index+1);
  78044. this.setMarkerSelected(marker, 'unhover');
  78045. viewer.inputHandler.startDragging(newMarker , {/* dragViewport:viewer.mapViewer.viewports[0], */ } ); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  78046. };
  78047. marker.addEventListener('drag', drag );
  78048. //marker.addEventListener('drop', drop);
  78049. marker.addEventListener('mouseover', mouseover);
  78050. marker.addEventListener('mouseleave', mouseleave);
  78051. }
  78052. this.add(marker);
  78053. this.updateMarker(marker, point);
  78054. if(!this.selected)Potree.Utils.updateVisible(marker,'select',false);
  78055. return marker
  78056. }
  78057. addMidMarkers(){//第一次画好所有marker后,一次性为线段增加中点marker
  78058. let length = this.points.length;
  78059. this.points.forEach((point,index)=>{
  78060. let nextPoint = this.points[(index+1)%length];
  78061. let midPoint = new Vector3().addVectors(point, nextPoint).multiplyScalar(0.5);
  78062. this.addMidMarker(index, midPoint );
  78063. });
  78064. }
  78065. updateTwoMidMarker(index){//更新第index个marker两边的midMarker
  78066. if(!this.midMarkers.length)return
  78067. let length = this.points.length;
  78068. let last = this.points[(index-1+length)%length]; //它之前的marker位置
  78069. let next = this.points[(index+1)%length];//它之后的marker位置
  78070. let current = this.points[index];//当前位置
  78071. let lastMid = new Vector3().addVectors(last, current).multiplyScalar(0.5);//上一个中点
  78072. let nextMid = new Vector3().addVectors(next, current).multiplyScalar(0.5);//下一个中点
  78073. let lastMidMarker = this.midMarkers[(index-1+length)%length];
  78074. let nextMidMarker = this.midMarkers[index];
  78075. this.updateMarker(lastMidMarker, lastMid);
  78076. this.updateMarker(nextMidMarker, nextMid);
  78077. }
  78078. dispose(){//销毁geo、remove from parent
  78079. super.dispose();
  78080. this.box && this.box.geometry.dispose();
  78081. this.lineMesh && this.lineMesh.geometry.dispose();
  78082. this.holes.forEach(e=>e.dispose());
  78083. this.parentHoles.forEach(e=>e.dispose());
  78084. //this.buildChildren.forEach(e=>e.dispose())
  78085. this.dispatchEvent('dispose');
  78086. }
  78087. updateBox(){
  78088. if(!this.box)return
  78089. this.box.geometry.dispose();
  78090. var shrink = this.buildType == 'room' ? 0.11 : this.buildType == 'floor' ? 0.082 : 0.2 ;//防止mesh重叠冲突(给一个不寻常的数字) 但离远了还是会有点闪烁
  78091. if(this.points.length >= 3){
  78092. let holes = this.holes.concat(this.parentHoles);
  78093. let holesPoints = holes.filter(e=>e.points.length>2).map(e=>e.points);
  78094. this.box.geometry = MeshDraw.getExtrudeGeo(this.points, holesPoints, {
  78095. depth:this.zMax-this.zMin-shrink,
  78096. UVGenerator: new MetricUVGenerator()
  78097. });
  78098. if(this.buildType == 'building' ){
  78099. this.box.position.z = this.zMin - shrink / 2;
  78100. }else {
  78101. this.box.position.z = this.zMin + shrink / 2;
  78102. }
  78103. }
  78104. }
  78105. update(options={}){
  78106. super.update(this.buildType != 'floor' && options.ifUpdateMarkers);
  78107. let length = this.points.length;
  78108. {//确保一下一样
  78109. if(this.originHole){
  78110. this.points = this.originHole.points; //完全等于building的hole
  78111. }
  78112. if(this.buildType == 'hole'){
  78113. this.zMin = this.buildParent.zMin;
  78114. this.zMax = this.buildParent.zMax;
  78115. }
  78116. }
  78117. if(!options.dontUpdateBox){
  78118. let boxOwner;
  78119. if(this.buildType == 'hole'){
  78120. if(this.buildParent.buildType == 'building'){ //若是整栋大楼的hole,在每层都要更新下它的对应hole
  78121. this.buildParent.buildChildren.forEach(floor=>{
  78122. let holeAtFloor = floor.parentHoles.find(e=>e.originHole == this );
  78123. holeAtFloor && holeAtFloor.update(); //刚开始创建时还没创建对应的 holeAtFloor会为null
  78124. });
  78125. }
  78126. boxOwner = this.buildParent;
  78127. }else {
  78128. boxOwner = this;
  78129. }
  78130. boxOwner.updateBox();
  78131. }
  78132. {//update lines
  78133. let positions = [];
  78134. this.points.forEach((point, index)=>{
  78135. //竖线:
  78136. positions.push(point.clone().setZ(this.zMin), point.clone().setZ(this.zMax));
  78137. //横线
  78138. let nextPoint = this.points[(index+1)%length];
  78139. if(!nextPoint)return;//when length==1
  78140. positions.push(point.clone().setZ(this.zMax), nextPoint.clone().setZ(this.zMax));//上横线
  78141. positions.push(point.clone().setZ(this.zMin), nextPoint.clone().setZ(this.zMin));//下横线
  78142. });
  78143. LineDraw.moveLine(this.lineMesh,positions);
  78144. }
  78145. if(!options.dontUpdateChildren){
  78146. if(this.buildType == 'building' ){
  78147. this.buildChildren.forEach(floor=>{
  78148. floor.points = this.points;
  78149. floor.update();
  78150. });
  78151. }
  78152. {
  78153. let holes = this.holes.concat(this.parentHoles);
  78154. holes.forEach(hole=> {
  78155. hole.update({dontUpdateBox:true});//父级更新了box,hole就不需要更新box了
  78156. });
  78157. }
  78158. }
  78159. }
  78160. getHolesArea(){
  78161. let holes = this.holes.concat(this.parentHoles);
  78162. let outHoles, holesArea = 0;
  78163. if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  78164. let holes_ = holes.map(e=>e.points);
  78165. outHoles = math.getPolygonsMixedRings(holes_, true );
  78166. outHoles.forEach(e=>{
  78167. holesArea+=e.area;
  78168. });
  78169. outHoles = outHoles.map(e=>e.points);
  78170. }else {
  78171. outHoles = holes.map(e=>e.points);
  78172. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)));
  78173. }
  78174. return holesArea
  78175. }
  78176. getArea(ifRidOfHoles){//面积
  78177. //不排除hole
  78178. return Math.abs(math.getArea(this.points)) - (ifRidOfHoles ? this.getHolesArea() : 0)
  78179. }
  78180. getVolume(ifRidOfHoles){//体积
  78181. let {zMin , zMax} = this.getRealZ();
  78182. let height = zMax - zMin;
  78183. if(isNaN(height))height = 0;
  78184. return this.getArea(ifRidOfHoles) * height
  78185. }
  78186. getRealZ(){//求真实高度时用到的
  78187. let zMin , zMax;
  78188. if (this.buildType == 'building') {
  78189. //因为building只有一个地基平面 所以自身的zMin == 自身的zMax 所以要算
  78190. let top = this.buildChildren[this.buildChildren.length - 1];
  78191. let btm = this.buildChildren[0];
  78192. zMin = btm ? btm.zMin : 0; //建好的建筑不加楼的话是0。
  78193. zMax = top ? top.zMax : 0;
  78194. }else if(this.buildType == 'hole'){
  78195. return this.buildParent.getRealZ()
  78196. }else {
  78197. zMin = this.zMin, zMax = this.zMax;
  78198. }
  78199. return {zMin,zMax}
  78200. }
  78201. //架站式多楼层SG-t-ihjV2cDVFlE 有初始的z, 但是总高度范围小于数据集。 不允许修改高度。
  78202. /* getDrawZ(){ //画线和box时用到的z
  78203. let zMin , zMax
  78204. if(this.buildType == 'hole'){
  78205. if(this.buildParent.buildType == 'building' && atFloor){
  78206. zMin = atFloor.zMin, zMax = atFloor.zMax
  78207. }else{
  78208. zMin = this.buildParent.zMin, zMax = this.buildParent.zMax
  78209. }
  78210. }else{
  78211. zMin = this.zMin, zMax = this.zMax
  78212. }
  78213. return {zMin, zMax}
  78214. } */
  78215. getBound(){
  78216. let bound = new Box3;
  78217. let {zMin , zMax} = this.getRealZ();
  78218. let points = this.buildType == 'floor' ? this.buildParent.points : this.points;
  78219. points.forEach(p=>{
  78220. bound.expandByPoint(p.clone().setZ(zMin));
  78221. bound.expandByPoint(p.clone().setZ(zMax));
  78222. });
  78223. return bound
  78224. }
  78225. getMarkerMaterial(type) {
  78226. if(!markerMats$2){
  78227. markerMats$2 = {
  78228. default: new MeshBasicMaterial({
  78229. transparent: !0,
  78230. color: color$2,
  78231. opacity: 0.8,
  78232. map: texLoader$9.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78233. depthTest:false,
  78234. }),
  78235. midPrepare: new MeshBasicMaterial({ //线中心的半透明点
  78236. transparent: !0,
  78237. color: color$2,
  78238. opacity: 0.4,
  78239. map: texLoader$9.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78240. depthTest:false,
  78241. }),
  78242. hover: new MeshBasicMaterial({
  78243. transparent: !0,
  78244. color: color$2,
  78245. opacity: 1,
  78246. map: texLoader$9.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78247. depthTest:false,
  78248. }),
  78249. select: new MeshBasicMaterial({
  78250. transparent: !0,
  78251. color:new Color('#00C8AF'),
  78252. opacity: 1,
  78253. map: texLoader$9.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78254. depthTest:false,
  78255. }),
  78256. };
  78257. }
  78258. return markerMats$2[type]
  78259. }
  78260. setMarkerSelected(marker, state, hoverObject){
  78261. //console.warn(marker.id , state, hoverObject)
  78262. if(state == 'select'){
  78263. marker.selected = true;
  78264. marker.material = this.getMarkerMaterial('select');
  78265. }else if(state == 'unselect'){
  78266. marker.selected = false;
  78267. marker.material = this.getMarkerMaterial('default');
  78268. }else {
  78269. if(marker.selected)return //选中时不允许修改为除了'unselect'以外的状态
  78270. if(state == 'hover'){
  78271. marker.material = this.getMarkerMaterial('hover');
  78272. }else if(state == 'unhover'){
  78273. if(marker.name.includes('mid')){
  78274. marker.material = this.getMarkerMaterial('midPrepare');
  78275. }else {
  78276. marker.material = this.getMarkerMaterial('default');
  78277. }
  78278. }
  78279. }
  78280. }
  78281. select(){
  78282. //最多再显示一层子级的线,如building不会显示room中的hole的线
  78283. //box是一直显示的,但会切换材质
  78284. /*
  78285. 选中 box 线
  78286. building 自己(底盘)选中 自己, floor不带hole
  78287. floor 自己选中 自己, room不带hole
  78288. room 自己选中 自己
  78289. */ //注:自己的就代表定包括hole,如果有parentHoles的也(building上的hole的对应)
  78290. //console.log('select '+this.name, this.selected)
  78291. if(this.selected)return
  78292. if(this.box){
  78293. this.box.material = this.mats.boxSelected;
  78294. }
  78295. if(this.buildType == 'building'|| this.buildType == 'floor'){
  78296. this.buildChildren.forEach(e=>{
  78297. e.lineMesh.visible = true;
  78298. });
  78299. if(this.buildType == 'floor'){
  78300. Potree.Utils.setObjectLayers(this.box, 'bothMapAndScene' );
  78301. Potree.Utils.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi' ); //当选中floor或room时,building在地图不可见
  78302. }
  78303. }else if(this.buildType == 'room'){
  78304. Potree.Utils.setObjectLayers(this.buildParent.box, 'bothMapAndScene' );
  78305. Potree.Utils.setObjectLayers(this.buildParent.buildParent.box, 'siteModelMapUnvisi' );
  78306. }
  78307. this.lineMesh.visible = true;
  78308. this.markers && this.markers.forEach(e=>Potree.Utils.updateVisible(e,'select',true) );
  78309. this.midMarkers && this.midMarkers.forEach(e=>e.visible = true);
  78310. let holes = this.holes.concat(this.parentHoles);
  78311. holes.forEach(e=>e.select());
  78312. this.selected = true;
  78313. this.dispatchEvent({type:'select'});
  78314. }
  78315. unselect(){
  78316. if(!this.selected)return
  78317. //console.log('unselect '+this.name )
  78318. if(this.box){
  78319. this.box.material = this.mats.boxDefault;
  78320. }
  78321. if(this.buildType == 'building' || this.buildType == 'floor'){
  78322. this.buildChildren.forEach(e=>{ //(这里要保证选中前要先取消选中,否则如选中房间后取消了楼层,房间线就隐藏了)
  78323. e.lineMesh.visible = false;
  78324. });
  78325. if(this.buildType == 'floor'){
  78326. Potree.Utils.setObjectLayers(this.box, 'siteModelMapUnvisi' );
  78327. Potree.Utils.setObjectLayers(this.buildParent.box, 'bothMapAndScene' );
  78328. }
  78329. }else if(this.buildType == 'room'){
  78330. Potree.Utils.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi' );
  78331. Potree.Utils.setObjectLayers(this.buildParent.buildParent.box, 'bothMapAndScene' );
  78332. }
  78333. this.lineMesh.visible = false;
  78334. this.markers && this.markers.forEach(e=>Potree.Utils.updateVisible(e,'select',false) );
  78335. this.midMarkers && this.midMarkers.forEach(e=>e.visible = false);
  78336. let holes = this.holes.concat(this.parentHoles);
  78337. holes.forEach(e=>e.unselect());
  78338. this.selected = false;
  78339. this.dispatchEvent({type:'unselect'});
  78340. }
  78341. ifContainsPoint(position){//看它所定义的空间是否包含某个坐标(要排除hole)
  78342. let {zMin , zMax} = this.getRealZ();
  78343. if(position.z < zMin || position.z > zMax ) return
  78344. let holes = this.holes.concat(this.parentHoles);
  78345. let holesPoints = holes.filter(e=>e!=this && e.points.length>2).map(e=>e.points);
  78346. let inShape = math.isPointInArea(this.points, holesPoints, position);
  78347. return !!inShape
  78348. }
  78349. }
  78350. class MetricUVGenerator{
  78351. constructor(){
  78352. this.a = new Vector3,
  78353. this.b = new Vector3,
  78354. this.c = new Vector3,
  78355. this.d = new Vector3;
  78356. }
  78357. generateTopUV(t, e, n, r, o) {
  78358. 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])]
  78359. }
  78360. generateSideWallUV(t, e, n, r, o, a) {
  78361. var s = e;
  78362. this.a.set(s[3 * n], s[3 * n + 1], s[3 * n + 2]),
  78363. this.b.set(s[3 * r], s[3 * r + 1], s[3 * r + 2]),
  78364. this.c.set(s[3 * o], s[3 * o + 1], s[3 * o + 2]),
  78365. this.d.set(s[3 * a], s[3 * a + 1], s[3 * a + 2]);
  78366. var c = this.a.x !== this.b.x
  78367. , l = c ? this.b : this.d
  78368. , u = this.a.distanceTo(l)
  78369. , d = l.distanceTo(this.c);
  78370. 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)]
  78371. }
  78372. }
  78373. const minFloorHeight = 0.5;
  78374. const ifDrawDatasetBound = true; //显示一下数据集的tightBound线框
  78375. const minMarkers = 3;
  78376. const Limit = {zMin:-config$1.map.cameraHeight, zMax:config$1.map.cameraHeight,}; //不能超过camera的高度,为了对称所以也限制了最低
  78377. var SiteModel = {
  78378. bus: new EventDispatcher(),
  78379. entities:[], //所有实体
  78380. buildings:[], //所有建筑父集
  78381. meshGroup: new Object3D,
  78382. inEntity : null,
  78383. lastPos: new Vector3(Infinity,Infinity,Infinity),
  78384. init: function(){
  78385. viewer.scene.scene.add(this.meshGroup);
  78386. this.meshGroup.name = 'siteModel';
  78387. this.SplitScreen = SplitScreen4Views;
  78388. if(Potree.settings.editType == 'pano'){
  78389. return
  78390. }
  78391. this.createHeightPull();
  78392. if(Potree.settings.isTest && ifDrawDatasetBound){
  78393. viewer.addEventListener('allLoaded',()=>{
  78394. viewer.scene.pointclouds.forEach(pointcloud=>{
  78395. let boxPoints = pointcloud.getUnrotBoundPoint();
  78396. let boundingBox = new BuildingBox({
  78397. name: '数据集tightBound_'+pointcloud.dataset_id,
  78398. points: boxPoints,
  78399. buildType : 'dataset',
  78400. zMax: pointcloud.bound.max.z,
  78401. zMin: pointcloud.bound.min.z,
  78402. ifDraw:true
  78403. });
  78404. this.meshGroup.add(boundingBox);
  78405. //boundingBox.markers.forEach(e=>e.visible = false)
  78406. });
  78407. });
  78408. }
  78409. if(Potree.settings.isOfficial){
  78410. viewer.addEventListener('camera_changed', e => {
  78411. if(e.changeInfo && e.changeInfo.positionChanged){
  78412. this.updateEntityAt();
  78413. }
  78414. });
  78415. }
  78416. {
  78417. let pressDelete = (e)=>{
  78418. if(e.keyCode == KeyCodes.BACKSPACE || e.keyCode == KeyCodes.DELETE){
  78419. if(this.selectedMarker){
  78420. let entity = this.selectedMarker.parent;
  78421. let index = entity.markers.indexOf(this.selectedMarker);
  78422. entity.removeMarker(index);
  78423. if(entity.points.length<2){//删到只剩一个点时重新画(如果是hole的点,直接删除hole吧?)
  78424. this.startInsertion('resume',entity);
  78425. }
  78426. }
  78427. }
  78428. };
  78429. viewer.inputHandler.addEventListener('keydown', pressDelete);
  78430. }
  78431. {
  78432. let updated = false;
  78433. this.bus.addEventListener('updated',()=>{
  78434. Common$1.intervalTool.isWaiting('siteModelUpdated', ()=>{
  78435. this.changedCallback();
  78436. },500);
  78437. });
  78438. }
  78439. },
  78440. changedCallback(){
  78441. this.findPanos();
  78442. this.findEntityForDataset();
  78443. this.updateEntityAt(true); //更新所在建筑,更新marker显示
  78444. //console.log('changedCallback')
  78445. },
  78446. updateEntityAt(force,{measure}={}){
  78447. //if(!this.entities.length || this.editing) return //编辑时也要根据位置显示不同楼层的漫游点与cad
  78448. let fun = ()=>{ //延时update,防止卡顿
  78449. let currPos = viewer.mainViewport.view.position;
  78450. if(this.pauseUpdateEntity)return // console.error('pauseUpdateEntity')
  78451. //if(force || !currPos.equals(this.lastPos) ){
  78452. //console.log('currPos ', currPos.toArray())
  78453. this.lastPos.copy(currPos);
  78454. let entity;
  78455. if(measure){//因为测量线的点可能在多个房间,所以干脆直接找在哪个楼层
  78456. let list = [];
  78457. measure.points.forEach(e=>{
  78458. let entity = this.pointInWhichEntity(e, 'floor' );//每个点都找到其所在楼层
  78459. let item = list.find(e=>e.entity == entity);
  78460. if(item){
  78461. item.count ++;
  78462. }else {
  78463. list.push({entity, count:1});
  78464. }
  78465. });
  78466. list.sort((a,b)=>{return b.count-a.count});//找出出现次数最多的楼层
  78467. if(list[0]){
  78468. entity = list[0].entity;
  78469. }
  78470. }else {
  78471. let searchPos = Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : currPos;
  78472. entity = this.pointInWhichEntity(searchPos, 'room');
  78473. }
  78474. if(force || this.inEntity != entity ){
  78475. let oldEntity = this.inEntity;
  78476. this.inEntity = entity;
  78477. //console.log('buildingChange', entity)
  78478. this.bus.dispatchEvent({type:'buildingChange',entity});
  78479. //this.updatePanosVisible(oldEntity, this.inEntity)
  78480. let lastFloor = this.currentFloor; //oldEntity ? oldEntity.buildType == 'floor' ? oldEntity : oldEntity.buildType == 'room' ? oldEntity.buildParent : null : null; //基本只会是floor或room
  78481. let currentFloor = entity ? entity.buildType == 'floor' ? entity : entity.buildType == 'room' ? entity.buildParent : null : null; //基本只会是floor或room
  78482. if(force || currentFloor != lastFloor){
  78483. //console.log('改变了floor',lastFloor,currentFloor)
  78484. this.currentFloor = currentFloor;
  78485. this.bus.dispatchEvent({type:'FloorChange',currentFloor});
  78486. }
  78487. }
  78488. force = false;
  78489. //}
  78490. };
  78491. if(force)fun();
  78492. else Common$1.intervalTool.isWaiting('sitemodelCameraInterval', fun , 500);
  78493. },
  78494. enter:function(){
  78495. Potree.Log('sitemodel enter');
  78496. this.clear(); //确保全部清空
  78497. this.editing = true;
  78498. //this.updatePanosVisible(null, null, true)//show all
  78499. viewer.updateFpVisiDatasets();
  78500. let mapViewport = viewer.mapViewer.viewports[0];
  78501. this.SplitScreen.split({siteModel:true/* , viewports:[{name:'Top',viewport : mapViewport }] */});
  78502. viewer.viewports.forEach(e=>{
  78503. if(e.name != 'mapViewport'){
  78504. e.layersAdd('siteModelMapUnvisi');
  78505. }
  78506. if(e.name == 'right' || e.name == 'back'){
  78507. e.layersAdd('siteModeSideVisi');
  78508. }
  78509. });
  78510. viewer.images360.panos.forEach(pano=>{
  78511. Potree.Utils.setObjectLayers(pano.marker, 'siteModelMapUnvisi' );
  78512. //Potree.Utils.setObjectLayers(pano.label2, 'bothMapAndScene')
  78513. });
  78514. mapViewport.layersAdd('siteModeOnlyMapVisi'); //只有mapViewport能看到marker
  78515. },
  78516. leave:function(){
  78517. Potree.Log('sitemodel leave');
  78518. let mapViewport = viewer.mapViewer.viewports[0];
  78519. this.SplitScreen.recover();
  78520. viewer.viewports.forEach(e=>{
  78521. if(e.name != 'mapViewport'){
  78522. e.layersRemove('siteModelMapUnvisi');
  78523. }
  78524. if(e.name == 'right' || e.name == 'back'){
  78525. e.layersRemove('siteModeSideVisi');
  78526. }
  78527. });
  78528. viewer.images360.panos.forEach(pano=>{
  78529. Potree.Utils.setObjectLayers(pano.marker, 'sceneObjects' );
  78530. //Potree.Utils.setObjectLayers(pano.label2, 'bothMapAndScene')
  78531. });
  78532. mapViewport.layersRemove('siteModeOnlyMapVisi');
  78533. this.clear();
  78534. this.editing = false;
  78535. this.updateEntityAt(true);
  78536. viewer.updateFpVisiDatasets();
  78537. } ,
  78538. addFloor:function(parent, dirType, sid, name){//dirType:'top'|'bottom'在上方建还是下方。如果建筑中没有楼层,默认在基底建一个
  78539. let buildType = 'floor';
  78540. let zMin, zMax;
  78541. if(parent.buildChildren.length == 0){
  78542. zMin = parent.zMin;
  78543. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  78544. }else {
  78545. if(dirType == 'bottom'){
  78546. //var btm = Common.find(parent.buildChildren,null,[e=>e.zMin])
  78547. var btm = parent.buildChildren[0];
  78548. zMax = btm.zMin;
  78549. zMin = zMax - Potree.config.siteModel.floorHeightDefault;
  78550. }else {
  78551. //var top = Common.find(parent.buildChildren,null,[e=>e.zMax])
  78552. var top = parent.buildChildren[parent.buildChildren.length - 1];
  78553. zMin = top.zMax;
  78554. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  78555. }
  78556. }
  78557. let prop = {
  78558. buildType,
  78559. //name : Potree.config.siteModel.names[buildType],
  78560. zMin,
  78561. zMax,
  78562. buildParent:parent,
  78563. sid, name,
  78564. ifDraw:true
  78565. };
  78566. var floor = new BuildingBox(prop);
  78567. /* parent.buildChildren.push(floor)
  78568. this.meshGroup.add(floor);
  78569. this.entities.push(floor) */
  78570. floor.update();
  78571. this.addEntity(floor,parent);
  78572. //this.selectEntity(floor)
  78573. if(this.selected == parent){//重新选择下,为了显示新楼层线框
  78574. parent.unselect();
  78575. parent.select();
  78576. }
  78577. this.bus.dispatchEvent('updated');
  78578. return floor
  78579. },
  78580. startInsertion:function(buildType, parent, sid, name, callback, cancelFun){
  78581. let zMin, zMax, entity, resume;
  78582. let mapViewport = viewer.mapViewer.viewports[0];
  78583. if(buildType == 'resume'){//继续画(使用最后一个点或者新加的点)
  78584. resume = true;
  78585. entity = parent;
  78586. buildType = parent.buildType;
  78587. //删除原先所有的点,因为它们已经添加了事件,会很麻烦:
  78588. entity.reDraw(0);
  78589. entity.isNew = true; //当作新的来画
  78590. }
  78591. if(!resume){
  78592. if(buildType == 'hole' || buildType == 'room'){
  78593. zMin = parent.zMin;
  78594. zMax = parent.zMax;
  78595. }else if(buildType == 'building'){
  78596. parent = null;
  78597. zMin = viewer.bound.boundingBox.min.z;
  78598. zMax = viewer.bound.boundingBox.min.z;
  78599. }
  78600. if(buildType == 'hole'){
  78601. entity = parent.addHole();
  78602. entity.isNew = true;
  78603. this.selectEntity(parent);
  78604. entity.select();
  78605. console.log('挖洞 ',entity.uuid);
  78606. }else {
  78607. let prop = {
  78608. buildType,
  78609. //name : Potree.config.siteModel.names[buildType],//'building',
  78610. zMin,
  78611. zMax,
  78612. buildParent:parent,
  78613. sid, name,
  78614. ifDraw:true
  78615. };
  78616. entity = new BuildingBox(prop);
  78617. entity.isNew = true;
  78618. this.selectEntity(entity);
  78619. }
  78620. this.addEntity(entity, parent);
  78621. }
  78622. let timer;
  78623. let endDragFun = (e) => {
  78624. if (e.button == MOUSE.LEFT ) {
  78625. var marker = entity.addMarker({point:entity.points[entity.points.length - 1].clone()});
  78626. //entity.editStateChange(true) //重新激活reticule状态
  78627. entity.continueDrag(marker, e);
  78628. } else if (e.button === MOUSE.RIGHT ) {
  78629. if(e.pressDistance < Potree.config.clickMaxDragDis )end(e);//非拖拽的话
  78630. else entity.continueDrag(null, e/* .drag.object */);
  78631. }
  78632. };
  78633. let finish = ()=>{//结束绘画
  78634. viewer.removeEventListener('cancel_insertions', Exit);
  78635. entity.removeEventListener('unselect', Exit);
  78636. clearTimeout(timer);
  78637. entity.editStateChange(false);
  78638. //pressExit && viewer.inputHandler.removeEventListener('keydown', pressExit);
  78639. callback && callback(entity);
  78640. };
  78641. let end = (e={}) => {//尝试结束
  78642. /* 退出的三种形式:
  78643. 1 普通:如果大于三个marker,结束且保留;否则重新画。()
  78644. 2 删除:直接结束且删除。(remove)
  78645. 3 结束:如果大于三个marker,结束且保留;否则结束且删除。 (finish)
  78646. 4 保留:无论几个marker,都保留着,结束。(remain)
  78647. */
  78648. if(e.remove){
  78649. finish();
  78650. return this.removeEntity(entity)
  78651. }
  78652. if(!e.remain && !e.finish && !e.remove && entity.markers.length<=minMarkers){//右键 当个数不够时取消
  78653. //重新开始画
  78654. entity.reDraw(1);
  78655. Potree.Utils.updateVisible(entity.markers[0],'unMove',false);
  78656. var f = ()=>{
  78657. Potree.Utils.updateVisible(entity.markers[0],'unMove',true);
  78658. entity.removeEventListener('dragChange',f);
  78659. };
  78660. entity.addEventListener('dragChange',f);
  78661. //console.log('waitcontinue')
  78662. entity.continueDrag(entity.markers[0], e);
  78663. return
  78664. }
  78665. finish();
  78666. if (e.remain || !e.remove && entity.markers.length > 3) {//保留
  78667. entity.removeMarker(entity.points.length - 1);
  78668. entity.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  78669. if(buildType == 'room'){
  78670. this.fitPullBox();
  78671. }
  78672. entity.isNew = false;
  78673. entity.addMidMarkers();
  78674. let boundingBox = entity.getBound();
  78675. let center = boundingBox.getCenter(new Vector3());
  78676. viewer.controls.setTarget(center,2);
  78677. }else {
  78678. this.removeEntity(entity); //直接删除没画好的,比较简单。这样就不用担心旧的continueDrag仍旧触发了
  78679. }
  78680. return entity
  78681. };
  78682. let Exit = (e)=>{ //强制结束
  78683. entity.removeEventListener('unselect', Exit);
  78684. if(viewer.inputHandler.drag){//还未触发drop的话
  78685. viewer.inputHandler.drag.object.dispatchEvent({
  78686. type: 'drop',
  78687. drag: viewer.inputHandler.drag,
  78688. viewer: viewer,
  78689. pressDistance:0,
  78690. button : MOUSE.RIGHT
  78691. });
  78692. viewer.inputHandler.drag = null;
  78693. }else {
  78694. end({remain:true});
  78695. }
  78696. viewer.inputHandler.drag = null;
  78697. };
  78698. viewer.dispatchEvent( 'cancel_insertions' );//取消之前的
  78699. viewer.addEventListener('cancel_insertions', Exit);
  78700. entity.addEventListener('unselect', Exit);
  78701. var marker = entity.addMarker({point:new Vector3(0, 0, 0)});
  78702. Potree.Utils.updateVisible(marker,'unMove',false);//这时候的位置是假的(0,0,0)所以先不可见
  78703. var f = ()=>{
  78704. Potree.Utils.updateVisible(marker,'unMove',true);
  78705. entity.removeEventListener('dragChange',f);
  78706. };
  78707. entity.addEventListener('dragChange',f);
  78708. marker.isDragging = true;
  78709. viewer.inputHandler.startDragging(marker , {dragViewport:mapViewport, endDragFun, notPressMouse:true} ); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  78710. return entity;
  78711. },
  78712. getPreDealData(points, zMin, zMax, initial, buildType, parent){
  78713. /* if( buildType == 'building' ){
  78714. zMax = zMin //强制变得一样,作为基底。如果有必要,保存时再算真实的zMax。目前zMin没有保存所以数据是错的,会直接根据floor计算
  78715. } */
  78716. var bound = viewer.bound.boundingBox;
  78717. if(buildType == 'building' && initial){//初始数据错的,要自己建(只有一个building和floor) 原posIsLonlat
  78718. console.log('空间模型未编辑过, 初始化了一个');
  78719. points = [
  78720. new Vector3(bound.min.x, bound.min.y,0),
  78721. new Vector3(bound.max.x, bound.min.y,0),
  78722. new Vector3(bound.max.x, bound.max.y,0),
  78723. new Vector3(bound.min.x, bound.max.y,0),
  78724. ];
  78725. zMin = bound.min.z;
  78726. zMax = bound.max.z;
  78727. /* points = points.map(e=>{
  78728. return viewer.transform.lonlatToLocal.forward(e)
  78729. }) */
  78730. }else {//相对于初始数据集的模型内坐标
  78731. points = points.map(e=> this.transform(e, 'fromDataset'));
  78732. if(buildType == 'floor' && initial){
  78733. zMin = bound.min.z;
  78734. zMax = bound.max.z;
  78735. }
  78736. }
  78737. return {points, zMax, zMin }
  78738. },
  78739. resetFromData:function(entity, points=[], holes=[], zMin, zMax ){
  78740. var {points, zMax, zMin} = this.getPreDealData(points, zMin, zMax , this.autoBuild , entity.buildType, entity.buildParent );
  78741. if(entity.buildType != 'floor' )entity.points = points;
  78742. if(entity.buildType == 'room'){
  78743. entity.zMin = zMin;
  78744. entity.zMax = zMax;
  78745. }else if(entity.buildType == 'floor'){//改楼高
  78746. let height = zMax - zMin;
  78747. let zMax2 = entity.zMin + height;
  78748. SiteModel.changeZ(entity, 'zMax', zMax2);
  78749. }
  78750. {
  78751. //删除旧的holes重新添加
  78752. let holesOld = entity.holes;
  78753. holesOld.forEach(e=>{
  78754. entity.removeHole(e);
  78755. });
  78756. holes.forEach(points =>{
  78757. let ps = points.map(e=> this.transform(e, 'fromDataset'));
  78758. let hole = entity.addHole(ps);
  78759. hole.addMidMarkers();
  78760. });
  78761. }
  78762. entity.update();
  78763. return entity
  78764. }
  78765. ,
  78766. createFromData:function( buildType, parent ,sid, name, points=[], holes=[], zMin, zMax, initial,panos_,flagPano){
  78767. if(buildType != 'building' && buildType != 'floor' && buildType != 'room' ) return
  78768. var {points, zMax, zMin} = this.getPreDealData(points, zMin, zMax , initial, buildType, parent );
  78769. let panos = [];
  78770. {
  78771. if(panos_){
  78772. panos_.forEach(sid=>{
  78773. let pano = viewer.images360.getPano(sid,'sid');
  78774. if(pano)panos.push(pano);
  78775. });
  78776. }
  78777. flagPano = flagPano != void 0 ? viewer.images360.getPano(flagPano,'sid') : null ; //最中心的pano 或者 最靠近该实体的pano(当panos为空时)
  78778. if(!this.editing && buildType == 'floor' && !flagPano){//没有的话可能是自动添加的floor,直接用parent的吧
  78779. panos = parent.panos;
  78780. flagPano = parent.flagPano;
  78781. }
  78782. }
  78783. let prop = {
  78784. buildType,
  78785. points,
  78786. name,
  78787. sid,
  78788. zMin,
  78789. zMax,
  78790. buildParent:parent,
  78791. ifDraw:this.editing || Potree.settings.drawEntityData,
  78792. panos, flagPano,
  78793. autoBuild : initial
  78794. };
  78795. let entity = new BuildingBox(prop);
  78796. SiteModel.addEntity(entity, parent );
  78797. if(this.editing){
  78798. if(buildType == 'building'|| buildType == 'room'){
  78799. entity.addMidMarkers();
  78800. }
  78801. }
  78802. holes.forEach(points =>{
  78803. let ps = points.map(e=> this.transform(e, 'fromDataset'));
  78804. let hole = entity.addHole(ps);
  78805. this.editing && hole.addMidMarkers();
  78806. });
  78807. /* if(buildType == 'floor'){
  78808. this.updateBuildingZ(parent)
  78809. } */
  78810. return entity
  78811. },
  78812. transform:function(pos, type){
  78813. if(Potree.settings.editType == 'pano'){ // 模型不经转换
  78814. return new Vector3().copy(pos).setZ(0);
  78815. }
  78816. if(type == 'toDataset'){
  78817. let point = Potree.Utils.datasetPosTransform({ toDataset: true, position: pos.clone(), datasetId: Potree.settings.originDatasetId });
  78818. return new Vector2().copy(point)
  78819. }else {
  78820. let position = new Vector3().copy(pos).setZ(0);
  78821. return Potree.Utils.datasetPosTransform({ fromDataset: true, position, datasetId: Potree.settings.originDatasetId })
  78822. }
  78823. },
  78824. addEntity:function(entity, parent){
  78825. if(entity.buildType != 'hole'){
  78826. this.meshGroup.add(entity);
  78827. this.entities.push(entity);
  78828. if(entity.buildType == 'building'){
  78829. this.buildings.push(entity);
  78830. }else {
  78831. parent.buildChildren.push(entity);
  78832. }
  78833. }
  78834. if(entity.buildType == 'room'){
  78835. entity.addEventListener('marker_dropped',()=>{
  78836. this.fitPullBox();
  78837. });
  78838. }else if(entity.buildType == 'floor'){
  78839. this.updateBuildingZ(parent);
  78840. parent.dispatchEvent({type:'addFloor'});
  78841. }
  78842. {//仅能存在一个marker被选中。选中的点可以被删除
  78843. entity.addEventListener('clickMarker', (e)=>{
  78844. if(this.selectedMarker == e.marker){
  78845. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78846. this.selectedMarker = null;
  78847. }else {
  78848. if(this.selectedMarker){
  78849. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78850. }
  78851. this.selectedMarker = e.marker;
  78852. this.selectedMarker.dispatchEvent({type:'clickSelect',state:true});
  78853. }
  78854. });
  78855. entity.addEventListener('removeMarker', (e)=>{
  78856. if(this.selectedMarker == e.marker){
  78857. this.selectedMarker = null;
  78858. }
  78859. });
  78860. let unselect = (e)=>{//取消选中实体或删除后
  78861. if(this.selectedMarker && entity.markers.includes(this.selectedMarker)){
  78862. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78863. this.selectedMarker = null;
  78864. }
  78865. };
  78866. entity.addEventListener('dispose', unselect);
  78867. entity.addEventListener('unselect', unselect);
  78868. }
  78869. //console.log('添加实体:', entity.buildType, entity.sid, entity.uuid)
  78870. this.bus.dispatchEvent('updated');
  78871. entity.addEventListener('marker_dropped',()=>{
  78872. this.bus.dispatchEvent('updated');
  78873. });
  78874. },
  78875. removeEntity : function(entity){
  78876. if(!this.entities.includes(entity))return
  78877. console.log('删除实体:', entity.buildType, entity.sid);
  78878. if(this.selected == entity){
  78879. this.height_pull_box && (this.height_pull_box.visible = false);
  78880. this.selectEntity(null);
  78881. }
  78882. if(entity.buildType == 'building'){
  78883. var index = this.buildings.indexOf(entity);
  78884. if(index>-1){
  78885. this.buildings.splice(index,1);
  78886. }
  78887. }else {
  78888. var index = entity.buildParent.buildChildren.indexOf(entity);
  78889. if(index>-1){
  78890. entity.buildParent.buildChildren.splice(index,1);
  78891. if(entity.buildType == 'floor' && index == 0){
  78892. this.updateBuildingZ(entity.buildParent);
  78893. }
  78894. }
  78895. }
  78896. var index = this.entities.indexOf(entity);
  78897. if(index>-1){
  78898. this.entities.splice(index,1);
  78899. }
  78900. entity.dispose();
  78901. let buildChildren = entity.buildChildren.slice();
  78902. buildChildren.forEach(e=>this.removeEntity(e));
  78903. this.bus.dispatchEvent('updated');
  78904. },
  78905. updateBuildingZ:function(building){
  78906. building.buildChildren = building.buildChildren.sort((e,a)=>e.zMin-a.zMin);//从低到高排序
  78907. building.buildChildren[0] && (building.zMin = building.zMax = building.buildChildren[0].zMin); //基底高度
  78908. //building.zMax = building.buildChildren[building.buildChildren.length-1].zMax
  78909. if(this.editing) building.update({dontUpdateChildren:true});
  78910. building.dispatchEvent('updateBuildingZ');
  78911. },
  78912. selectEntity : function(entity, state=true){
  78913. viewer.dispatchEvent('content_changed');
  78914. if(state === false){
  78915. entity.unselect();
  78916. if(this.selected == entity)this.selected = null;
  78917. viewer.controls.setTarget(null,2);
  78918. return
  78919. }
  78920. if(this.selected == entity || entity && entity.buildType == 'hole')return
  78921. //this.buildings.forEach(e=>e.unselect())
  78922. this.selected && this.selected.unselect();
  78923. this.height_pull_box && (this.height_pull_box.visible = false);
  78924. if(entity){
  78925. entity.select();
  78926. if(!entity.isNew){
  78927. let boundingBox = entity.getBound();
  78928. let center = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢)
  78929. viewer.controls.setTarget(center,2);
  78930. }
  78931. }else {
  78932. viewer.controls.setTarget(null,2);
  78933. }
  78934. this.selected = entity;
  78935. if(entity && !entity.dontDragFloorHeight && (entity.buildType == 'floor' || entity.buildType == 'room' )){
  78936. this.height_pull_box && (this.height_pull_box.visible = true);
  78937. this.fitPullBox();
  78938. }
  78939. if(entity && !entity.isNew && (entity.buildType == 'building' || entity.buildType == 'room' ) && entity.points.length<2){
  78940. this.startInsertion('resume',entity); //继续画
  78941. }
  78942. },
  78943. fitPullBox: function(){ //自适应拖拽楼层的pullMesh
  78944. if(!this.height_pull_box || !this.selected || this.selected.buildType!= 'floor' && this.selected.buildType!= 'room')return
  78945. let bound = new Box3();
  78946. bound.expandByObject(this.selected.box);
  78947. let center = bound.getCenter(new Vector3() );
  78948. let size = bound.getSize(new Vector3() );
  78949. this.height_pull_box.scale.copy(size);
  78950. this.height_pull_box.position.copy(center);
  78951. },
  78952. changeZ:function(entity, dirType, value){ // floor or room 修改zMin or zMax
  78953. let max, min; //limit
  78954. if(entity.buildType == 'floor'){//楼层
  78955. let index = entity.buildParent.buildChildren.indexOf(entity);
  78956. if(dirType == 'zMax'){
  78957. let upper = entity.buildParent.buildChildren[index+1];
  78958. entity.zMax = Math.min(Limit.zMax, value);
  78959. min = entity.zMin + minFloorHeight;
  78960. if(entity.zMax < min){
  78961. entity.zMax = min;
  78962. }else {
  78963. if(upper){
  78964. max = upper.zMax - minFloorHeight;
  78965. if(entity.zMax > max){
  78966. entity.zMax = max;
  78967. }
  78968. }
  78969. }
  78970. if(upper){
  78971. upper.zMin = entity.zMax;
  78972. upper.update();
  78973. upper.dispatchEvent({type:'changeHeight'});
  78974. }
  78975. }else {
  78976. let lower = entity.buildParent.buildChildren[index-1];
  78977. entity.zMin = Math.max(Limit.zMin, value);
  78978. max = entity.zMax - minFloorHeight;
  78979. if(entity.zMin > max){
  78980. entity.zMin = max;
  78981. }else {
  78982. if(lower){
  78983. min = lower.zMin + minFloorHeight;
  78984. if(entity.zMin < min){
  78985. entity.zMin = min;
  78986. }
  78987. }
  78988. }
  78989. if(lower){
  78990. lower.zMax = entity.zMin;
  78991. lower.update();
  78992. lower.dispatchEvent({type:'changeHeight'});
  78993. }
  78994. if(index == 0)this.updateBuildingZ(entity.buildParent);
  78995. }
  78996. }else if(entity.buildType == 'room'){//房间
  78997. //按照navvis的是不一定限制在当前楼层,只要高度不超过当前楼层即可。
  78998. let maxHeight = entity.buildParent.zMax - entity.buildParent.zMin;
  78999. if(dirType == 'zMax'){
  79000. min = entity.zMin + minFloorHeight;
  79001. max = entity.zMin + maxHeight;
  79002. entity.zMax = MathUtils.clamp(value, min, max);
  79003. }else {
  79004. min = entity.zMax - maxHeight;
  79005. max = entity.zMax - minFloorHeight;
  79006. entity.zMin = MathUtils.clamp(value, min, max);
  79007. }
  79008. }
  79009. entity.update();
  79010. entity.dispatchEvent({type:'changeHeight'});
  79011. //this.selected.emit('update')
  79012. this.fitPullBox();
  79013. this.bus.dispatchEvent('updated');
  79014. },
  79015. createHeightPull:function(){ //拖拽楼层的bounding box
  79016. let boxGeo = new BoxBufferGeometry( 1, 1, 1/4 );
  79017. let boxMat = new MeshBasicMaterial({
  79018. color:"#F00",
  79019. opacity:0,
  79020. transparent:true,
  79021. depthTest:false,
  79022. side:2
  79023. });
  79024. let height_pull_box_up = new Mesh(boxGeo,boxMat);
  79025. let height_pull_box_down = new Mesh(boxGeo,boxMat);
  79026. height_pull_box_up.name = 'height_pull_box_up';
  79027. height_pull_box_down.name = 'height_pull_box_down';
  79028. this.height_pull_box = new Object3D();
  79029. this.height_pull_box.name = 'height_pull_box';
  79030. this.height_pull_box.add(height_pull_box_up);
  79031. this.height_pull_box.add(height_pull_box_down);
  79032. this.height_pull_box.visible = false;
  79033. this.meshGroup.add(this.height_pull_box);
  79034. height_pull_box_up.position.set(0,0,1/2/* 3/8 */);
  79035. height_pull_box_down.position.set(0,0,-1/2/* -3/8 */);
  79036. Potree.Utils.setObjectLayers(this.height_pull_box, 'siteModeSideVisi' );
  79037. let mouseover = (e)=>{
  79038. viewer.dispatchEvent({
  79039. type : "CursorChange", action : "add", name:"siteModelFloorDrag"
  79040. });
  79041. };
  79042. let mouseleave = (e)=>{
  79043. viewer.dispatchEvent({
  79044. type : "CursorChange", action : "remove", name:"siteModelFloorDrag"
  79045. });
  79046. };
  79047. let firstZ, firstIntersect;
  79048. let drag = (e)=>{
  79049. var intersect = e.intersect.orthoIntersect; //不要点云的intersect,只要orthocamera算出的平面intersect
  79050. if(firstIntersect != void 0){
  79051. let moveZ = intersect.z - firstIntersect;
  79052. if(this.selected.buildType == 'floor'){//楼层
  79053. //限制高度不能超过上下
  79054. if(e.target == height_pull_box_up){
  79055. if(firstZ == void 0)firstZ = this.selected.zMax;
  79056. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  79057. }else {
  79058. if(firstZ == void 0)firstZ = this.selected.zMin;
  79059. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  79060. }
  79061. }else if(this.selected.buildType == 'room'){//房屋
  79062. if(e.target == height_pull_box_up){
  79063. if(firstZ == void 0)firstZ = this.selected.zMax;
  79064. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  79065. }else {
  79066. if(firstZ == void 0)firstZ = this.selected.zMin;
  79067. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  79068. }
  79069. }
  79070. }else {
  79071. firstIntersect = intersect.z;
  79072. }
  79073. };
  79074. let drop = (e)=>{
  79075. firstZ = firstIntersect = null;
  79076. };
  79077. height_pull_box_up.addEventListener('mousemove',mouseover);
  79078. height_pull_box_down.addEventListener('mousemove',mouseover);
  79079. height_pull_box_up.addEventListener('mouseleave',mouseleave);
  79080. height_pull_box_down.addEventListener('mouseleave',mouseleave);
  79081. height_pull_box_up.addEventListener('drag',drag);
  79082. height_pull_box_down.addEventListener('drag',drag);
  79083. height_pull_box_up.addEventListener('drop',drop);
  79084. height_pull_box_down.addEventListener('drop',drop);
  79085. },
  79086. pointInWhichEntity(location, buildType, ifIgnoreHole){//buildType是要找的建筑类型
  79087. //location 可以是pano或者坐标
  79088. //由于房间可能在building外,所以房间要另外单独识别。
  79089. let lastResult; //最接近的上一层结果,如果没有result返回这个
  79090. let result;
  79091. let level = {
  79092. building: 0, floor: 1, room: 2
  79093. };
  79094. let traverse = (parent, buildType)=>{//返回第一个符合标准的实体
  79095. let contains;
  79096. if(location instanceof Vector3){
  79097. contains = parent.ifContainsPoint(location);
  79098. }else {//is pano
  79099. contains = parent.panos.includes(location);
  79100. }
  79101. if(contains){
  79102. if(!lastResult || level[lastResult.buildType] < level[parent.buildType] )lastResult = parent;
  79103. if(parent.buildType == buildType){
  79104. return parent
  79105. }else {
  79106. for(let i=0,len=parent.buildChildren.length; i<len; i++){
  79107. let result1 = traverse(parent.buildChildren[i]);
  79108. if(result1) return result1
  79109. }
  79110. }
  79111. }
  79112. };
  79113. //因为建筑可能重叠,所以需要先找到最接近其中心的建筑物
  79114. result = Common$1.sortByScore(this.buildings, [(building)=>{
  79115. return traverse(building, 'building') //在building中
  79116. }], [(building)=>{ //写法类似pointInWhichPointcloud
  79117. let boundingBox = building.getBound();
  79118. let center = boundingBox.getCenter(new Vector3());
  79119. let position = location instanceof Vector3 ? location : location.position;
  79120. let dis = position.distanceTo(center);
  79121. let size = boundingBox.getSize(new Vector3());
  79122. let length = size.length() / 2;
  79123. return length / dis
  79124. }]);
  79125. let building = result && result[0] && result[0].score > 1 && result[0].item;
  79126. if(buildType == 'building' || !building)return building
  79127. result = traverse(building, buildType);
  79128. /* if(!result && buildType == 'room'){//如果要找的是room, 且按刚才的顺序找不到的话,就单独从所有rooms中找一遍。因为room可能不在floor和building内。
  79129. let rooms = this.entities.filter(e=>e.buildType == 'room');
  79130. result = rooms.find(e=>e.ifContainsPoint(position))
  79131. }*/
  79132. //虽然房间可以画到上级之外,但是为了方便起见,假定房间绝对在楼层之内。找不到的话要调整空间模型了。
  79133. return result || lastResult
  79134. }
  79135. ,
  79136. findPanos: function(){
  79137. {
  79138. this.entities.forEach(entity=>{
  79139. //清空:
  79140. entity.panos = [];
  79141. entity.flagPano = null;
  79142. viewer.images360.panos.forEach(pano=>{
  79143. if(entity.ifContainsPoint(pano.position)){
  79144. entity.panos.push(pano);
  79145. }
  79146. });
  79147. });
  79148. }
  79149. /* viewer.images360.panos.forEach(pano=>{ //一个漫游点只对应一个实体的话
  79150. let result = this.pointInWhichEntity(pano.position, 'room');
  79151. {//get panos for every entities
  79152. let entity = result
  79153. while(entity){
  79154. entity.panos.push(pano);
  79155. entity = entity.buildParent
  79156. }
  79157. }
  79158. }) */
  79159. {//search center pano
  79160. this.entities.forEach(entity=>{
  79161. let panos = entity.panos;
  79162. if(panos.length == 0)return
  79163. let bound = entity.getBound();
  79164. let center = bound.getCenter(new Vector3);
  79165. let request = [];
  79166. let rank = [
  79167. Images360.scoreFunctions.distanceSquared({position: center})
  79168. ];
  79169. //let panos = entity.panos && entity.panos.length ? entity.panos : viewer.images360.panos //entity没有panos的话,就扩大到所有panos
  79170. let r = Common$1.sortByScore(panos, request, rank);
  79171. if(r && r.length){
  79172. entity.flagPano = r[0].item;
  79173. }else {
  79174. console.error('no flagPano??');
  79175. }
  79176. });
  79177. }
  79178. }
  79179. ,
  79180. findEntityForDataset:function(){//为每一个数据集寻找它所属的最小实体
  79181. /* var entities = this.entities.filter(e=>e.buildType == 'room' || e.buildType == 'floor' && e.buildChildren.length == 0)
  79182. viewer.scene.pointclouds.forEach(pointcloud=>{
  79183. let cloudVolume = pointcloud.getVolume()
  79184. let scores = []
  79185. entities.forEach(entity=>{
  79186. let volume = entity.intersectPointcloudVolume(pointcloud)
  79187. //注:默认已经findPanos过
  79188. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  79189. let panoCount = panos.length
  79190. let score = volume / cloudVolume + panoCount / pointcloud.panos.length
  79191. scores.push({entity, volume, panoCount, score})
  79192. })
  79193. scores.sort((a,b)=>{ return b.score-a.score })
  79194. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  79195. pointcloud.belongToEntity = null
  79196. }else{
  79197. pointcloud.belongToEntity = scores[0].entity;
  79198. }
  79199. }) */
  79200. let getScores = (pointcloud, entities, cloudVolume)=>{
  79201. let scores = [];
  79202. entities.forEach(entity=>{
  79203. let volume = entity.intersectPointcloudVolume(pointcloud);
  79204. //注:默认已经findPanos过
  79205. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  79206. let panoCount = panos.length;
  79207. let score = volume / cloudVolume;
  79208. if(pointcloud.panos.length > 0){
  79209. score += panoCount / pointcloud.panos.length;
  79210. }else {
  79211. //score += 1
  79212. }
  79213. scores.push({entity, volume, panoCount, score});
  79214. });
  79215. scores.sort((a,b)=>{ return b.score-a.score });
  79216. return scores
  79217. };
  79218. viewer.scene.pointclouds.forEach(pointcloud=>{ //先判断父级,如果父集不通过就不判断子级。
  79219. let cloudVolume = pointcloud.getVolume();
  79220. let entities = this.buildings;
  79221. while(1){
  79222. let scores = getScores(pointcloud, entities, cloudVolume);
  79223. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  79224. if(scores[0] && scores[0].entity.buildType == 'room'){
  79225. pointcloud.belongToEntity = scores[0].entity; //当该数据集在楼层中,但不在楼层中的任意一个房间时,任意挂载在其中一个房间上。
  79226. break
  79227. }
  79228. pointcloud.belongToEntity = null;
  79229. break;
  79230. }else {
  79231. entities = scores[0].entity.buildChildren;
  79232. if(entities.length == 0){
  79233. pointcloud.belongToEntity = scores[0].entity;
  79234. break;
  79235. }
  79236. }
  79237. }
  79238. });
  79239. /*
  79240. 旧版:
  79241. 只需要考虑 floor 和 room, 因为building的只有一个基底没高度
  79242. floor 和 room 在空间中没有完全的从属关系,因为room可以超出floor之外。所以直接混在一起来查找,但要排除有房间的楼层。
  79243. (现在改为层层递进查找,否则数据集包含entity多的,会直接挂载到体积最大的房间里,即使看起来主体点云并不在该房间)
  79244. 有的数据集虽然很高,但只有近地面的部分才是主体,这部分一般含有全部漫游点。为了防止上层的实体因体积较大而分数高,就把包含漫游点的个数也加入考虑。
  79245. 重叠体积大、且包含漫游点最多的最小实体将会拥有该点云。
  79246. 期望: 最好不挂载到最小子级,因为现在有房间都到房间里了。
  79247. */
  79248. }
  79249. ,
  79250. clear:function(){//清空
  79251. /* entities:[], //所有实体
  79252. buildings:[], //所有建筑父集
  79253. meshGroup: new THREE.Object3D, */
  79254. this.selectEntity(null);
  79255. let length = this.entities.length;
  79256. for(let i=0;i<length;i++){
  79257. this.entities[i].dispose();
  79258. }
  79259. this.entities = [];
  79260. this.buildings = [];
  79261. this.inEntity = null;
  79262. }
  79263. ,
  79264. gotoEntity(id, isNearBy, duration=1000) {
  79265. var entity = this.entities.find(e => e.sid == id);
  79266. let aimPano;
  79267. if (!entity) {
  79268. return console.error('没找到entity ')
  79269. }
  79270. if(Potree.settings.displayMode == 'showPanos'){
  79271. if (isNearBy && entity.panos.length) {
  79272. if(entity.panos.includes(viewer.images360.currentPano)) return 'posNoChange' //已在当前实体中
  79273. let position = viewer.scene.getActiveCamera().position;
  79274. let request = [];
  79275. let rank = [Images360.scoreFunctions.distanceSquared({ position })];
  79276. let r = Common$1.sortByScore(entity.panos, request, rank);
  79277. aimPano = r[0].item;
  79278. } else {
  79279. if (!entity.flagPano) {
  79280. return console.log('没有flagPano')
  79281. }
  79282. aimPano = entity.flagPano;
  79283. }
  79284. if(aimPano == viewer.images360.currentPano) return 'posNoChange'
  79285. viewer.images360.flyToPano(aimPano);
  79286. }else {
  79287. if(isNearBy && entity.ifContainsPoint(viewer.images360.position) ){
  79288. return 'posNoChange' //已在当前实体中
  79289. }
  79290. let boundingBox = entity.getBound();
  79291. let position = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢)
  79292. let size = boundingBox.getSize(new Vector3());
  79293. if(viewer.modules.Clip && viewer.modules.Clip.editing){
  79294. viewer.modules.Clip.bus.dispatchEvent({type:'flyToPos', position});
  79295. }else {
  79296. if(math.closeTo(position, viewer.images360.position)) return 'posNoChange'
  79297. viewer.scene.view.setView({position, duration});
  79298. }
  79299. viewer.mapViewer.moveTo(position, size, duration);
  79300. }
  79301. return true
  79302. },
  79303. focusEntity(id){
  79304. var entity = this.entities.find(e => e.sid == id);
  79305. let boundingBox = entity.getBound();
  79306. //let boundSize = boundingBox.getSize(new THREE.Vector3())
  79307. let center = boundingBox.getCenter(new Vector3());
  79308. this.SplitScreen.focusOnObject(boundingBox, center);
  79309. this.gotoEntity(id, false, 0);
  79310. },
  79311. removeIlligalArchi(){//删除marker数量小于3个的建筑,当保存时
  79312. let needDelete = [];
  79313. this.entities.forEach(e=>{
  79314. if(e.points.length<3){
  79315. needDelete.push(e);
  79316. }
  79317. });
  79318. needDelete.forEach(e=>this.removeEntity(e));
  79319. },
  79320. };
  79321. // Author: Fyrestar https://mevedia.com (https://github.com/Fyrestar/THREE.InfiniteGridHelper)
  79322. class InfiniteGridHelper extends Mesh{
  79323. constructor(size1, size2, color, distance, opacity1=0.2, opacity2=1){
  79324. color = color || new Color('white');
  79325. size1 = size1 || 10;
  79326. size2 = size2 || 100;
  79327. distance = distance || 8000; //可视距离?越远越模糊
  79328. const geometry = new PlaneBufferGeometry(2, 2, 1, 1);
  79329. const material = new ShaderMaterial({
  79330. side: DoubleSide,
  79331. uniforms: {
  79332. uSize1: {
  79333. value: size1
  79334. },
  79335. uSize2: {
  79336. value: size2
  79337. },
  79338. opacity1:{//线条1的 小格子
  79339. value: opacity1
  79340. },
  79341. opacity2:{//线条2的
  79342. value: opacity2
  79343. },
  79344. uColor: {
  79345. value: color
  79346. },
  79347. uDistance: {
  79348. value: distance
  79349. }
  79350. },
  79351. transparent: true,
  79352. vertexShader: `
  79353. varying vec3 worldPosition;
  79354. uniform float uDistance;
  79355. void main() {
  79356. vec3 pos = position.xyz * uDistance;
  79357. pos.xy += cameraPosition.xy;
  79358. worldPosition = pos;
  79359. gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
  79360. }
  79361. `,
  79362. fragmentShader: `
  79363. varying vec3 worldPosition;
  79364. uniform float uSize1;
  79365. uniform float uSize2;
  79366. uniform float opacity1;
  79367. uniform float opacity2;
  79368. uniform vec3 uColor;
  79369. uniform float uDistance;
  79370. float getGrid(float size) {
  79371. vec2 r = worldPosition.xy / size;
  79372. vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
  79373. float line = min(grid.x, grid.y);
  79374. return 1.0 - min(line, 1.0);
  79375. }
  79376. //为何侧面看不到线,因为mesh的正侧面都看不到?
  79377. void main() {
  79378. float d = 1.0 - min(distance(cameraPosition.xy, worldPosition.xy) / uDistance, 1.0);
  79379. float g1 = getGrid(uSize1);
  79380. float g2 = getGrid(uSize2);
  79381. gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));
  79382. //gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);
  79383. gl_FragColor.a = mix(opacity1 * gl_FragColor.a, opacity2 * gl_FragColor.a, g2);
  79384. if ( gl_FragColor.a <= 0.0 ) discard;
  79385. }
  79386. `,
  79387. extensions: {
  79388. derivatives: true
  79389. }
  79390. });
  79391. super(geometry, material);
  79392. this.frustumCulled = false;
  79393. }
  79394. };
  79395. /*
  79396. THREE.InfiniteGridHelper.prototype = {
  79397. ...THREE.Mesh.prototype,
  79398. ...THREE.Object3D.prototype,
  79399. ...THREE.EventDispatcher.prototype
  79400. };
  79401. */
  79402. var TransformControls = function ( camera, domElement, options ) {
  79403. if ( domElement === undefined ) {
  79404. console.warn( 'THREE.TransformControls: The second parameter "domElement" is now mandatory.' );
  79405. domElement = document;
  79406. }
  79407. Object3D.call( this );
  79408. this.visible = false;
  79409. this.domElement = domElement;
  79410. var _gizmo = new TransformControlsGizmo(options);
  79411. this.add( _gizmo );
  79412. this._gizmo = _gizmo;
  79413. var _plane = new TransformControlsPlane(options);
  79414. this.add( _plane );
  79415. /* this.linesAssistance = new TransformControlsLines(options); //水平 垂直 辅助
  79416. this.add( this.linesAssistance ); */
  79417. var scope = this;
  79418. //this.player = options.player;//xzw add
  79419. this.options = options;//xzw add
  79420. // Define properties with getters/setter
  79421. // Setting the defined property will automatically trigger change event
  79422. // Defined properties are passed down to gizmo and plane
  79423. defineProperty( "camera", camera );
  79424. defineProperty( "object", undefined );
  79425. defineProperty( "enabled", true );
  79426. defineProperty( "axis", null );
  79427. defineProperty( "mode", "translate" );
  79428. defineProperty( "translationSnap", null );
  79429. defineProperty( "rotationSnap", null );
  79430. defineProperty( "scaleSnap", null );
  79431. defineProperty( "space", "world" );
  79432. defineProperty( "size", 1 );
  79433. defineProperty( "dragging", false );
  79434. defineProperty( "showX", true );
  79435. defineProperty( "showY", true );
  79436. defineProperty( "showZ", true );
  79437. var changeEvent = { type: "change" };
  79438. var mouseDownEvent = { type: "mouseDown" };
  79439. var mouseUpEvent = { type: "mouseUp", mode: scope.mode };
  79440. var objectChangeEvent = { type: "objectChange" };
  79441. // Reusable utility variables
  79442. var ray = new Raycaster();
  79443. var _tempVector = new Vector3();
  79444. var _tempVector2 = new Vector3();
  79445. var _tempQuaternion = new Quaternion();
  79446. var _unit = {
  79447. X: new Vector3( 1, 0, 0 ),
  79448. Y: new Vector3( 0, 1, 0 ),
  79449. Z: new Vector3( 0, 0, 1 )
  79450. };
  79451. var pointStart = new Vector3();
  79452. var pointEnd = new Vector3();
  79453. var offset = new Vector3();
  79454. var rotationAxis = new Vector3();
  79455. var startNorm = new Vector3();
  79456. var endNorm = new Vector3();
  79457. var rotationAngle = 0;
  79458. var cameraPosition = new Vector3();
  79459. var cameraQuaternion = new Quaternion();
  79460. var cameraScale = new Vector3();
  79461. var parentPosition = new Vector3();
  79462. var parentQuaternion = new Quaternion();
  79463. var parentQuaternionInv = new Quaternion();
  79464. var parentScale = new Vector3();
  79465. var worldPositionStart = new Vector3();
  79466. var worldQuaternionStart = new Quaternion();
  79467. var worldScaleStart = new Vector3();
  79468. var worldPosition = new Vector3();
  79469. var worldQuaternion = new Quaternion();
  79470. var worldQuaternionInv = new Quaternion();
  79471. var worldScale = new Vector3();
  79472. var eye = new Vector3();
  79473. var positionStart = new Vector3();
  79474. var quaternionStart = new Quaternion();
  79475. var scaleStart = new Vector3();
  79476. // TODO: remove properties unused in plane and gizmo
  79477. defineProperty( "worldPosition", worldPosition );
  79478. defineProperty( "worldPositionStart", worldPositionStart );
  79479. defineProperty( "worldQuaternion", worldQuaternion );
  79480. defineProperty( "worldQuaternionStart", worldQuaternionStart );
  79481. defineProperty( "cameraPosition", cameraPosition );
  79482. defineProperty( "cameraQuaternion", cameraQuaternion );
  79483. defineProperty( "pointStart", pointStart );
  79484. defineProperty( "pointEnd", pointEnd );
  79485. defineProperty( "rotationAxis", rotationAxis );
  79486. defineProperty( "rotationAngle", rotationAngle );
  79487. defineProperty( "eye", eye );
  79488. {
  79489. domElement.addEventListener( "mousedown", onPointerDown, false );
  79490. domElement.addEventListener( "touchstart", onPointerDown, false );
  79491. domElement.addEventListener( "mousemove", onPointerHover, false );
  79492. domElement.addEventListener( "touchmove", onPointerHover, false );
  79493. domElement.addEventListener( "touchmove", onPointerMove, false );
  79494. document.addEventListener( "mouseup", onPointerUp, false );
  79495. domElement.addEventListener( "touchend", onPointerUp, false );
  79496. domElement.addEventListener( "touchcancel", onPointerUp, false );
  79497. domElement.addEventListener( "touchleave", onPointerUp, false );
  79498. let drag = ()=>{
  79499. if(this.dragging){
  79500. this.pointerMove();
  79501. return {stopContinue:true}
  79502. }
  79503. };
  79504. this.addEventListener('dragging',drag,{importance:10});
  79505. viewer.addEventListener('global_drag',drag,{importance:10});
  79506. }
  79507. this.setRotateMethod = function(number){//add 注意为2时 旋转期间不能改变位置 space可能不能为local ._gizmo.hideAxis = { rotate:[这里必须包含'e' ] }
  79508. this.rotateMethod = number;
  79509. };
  79510. this.dispose = function () {
  79511. domElement.removeEventListener( "mousedown", onPointerDown );
  79512. domElement.removeEventListener( "touchstart", onPointerDown );
  79513. domElement.removeEventListener( "mousemove", onPointerHover );
  79514. domElement.removeEventListener( "mousemove", onPointerMove );
  79515. domElement.removeEventListener( "touchmove", onPointerHover );
  79516. domElement.removeEventListener( "touchmove", onPointerMove );
  79517. document.removeEventListener( "mouseup", onPointerUp );
  79518. domElement.removeEventListener( "touchend", onPointerUp );
  79519. domElement.removeEventListener( "touchcancel", onPointerUp );
  79520. domElement.removeEventListener( "touchleave", onPointerUp );
  79521. this.traverse( function ( child ) {
  79522. if ( child.geometry ) child.geometry.dispose();
  79523. if ( child.material ) child.material.dispose();
  79524. } );
  79525. };
  79526. // Set current object
  79527. this.attach = function ( object ) {
  79528. this.object = object;
  79529. this.visible = true;
  79530. //Config.keyCon = false;//add
  79531. //this.linesAssistance.setVisible(true)
  79532. viewer.dispatchEvent('content_changed');
  79533. return this;
  79534. };
  79535. // Detatch from object
  79536. this.detach = function () {
  79537. this.object = undefined;
  79538. this.visible = false;
  79539. this.axis = null;
  79540. //Config.keyCon = true;//add
  79541. //this.linesAssistance.setVisible(false)
  79542. viewer.dispatchEvent('content_changed');
  79543. return this;
  79544. };
  79545. //this.space = 'local'
  79546. /* this.hideAxis = function ( mode, axis=[] ) {//xzw add 设置不可见的axis
  79547. var handles = [];
  79548. handles = handles.concat( this._gizmo.picker[ mode ].children );
  79549. handles = handles.concat( this._gizmo.gizmo[ mode ].children );
  79550. handles = handles.concat( this._gizmo.helper[ mode ].children );
  79551. handles.forEach(e=>e.visible = false)
  79552. axis.forEach(name=>{
  79553. handles.filter(handle =>!handle.name.includes(name))
  79554. })
  79555. handles.forEach(e=>e.visible = true)
  79556. }; */
  79557. // Defined getter, setter and store for a property
  79558. function defineProperty( propName, defaultValue ) {
  79559. var propValue = defaultValue;
  79560. Object.defineProperty( scope, propName, {
  79561. get: function () {
  79562. return propValue !== undefined ? propValue : defaultValue;
  79563. },
  79564. set: function ( value ) {
  79565. if ( propValue !== value ) {
  79566. propValue = value;
  79567. _plane[ propName ] = value;
  79568. _gizmo[ propName ] = value;
  79569. scope.dispatchEvent( { type: propName + "-changed", value: value } );
  79570. scope.dispatchEvent( changeEvent );
  79571. }
  79572. }
  79573. } );
  79574. scope[ propName ] = defaultValue;
  79575. _plane[ propName ] = defaultValue;
  79576. _gizmo[ propName ] = defaultValue;
  79577. }
  79578. // updateMatrixWorld updates key transformation variables
  79579. this.updateMatrixWorld = function () {
  79580. if(!this.visible)return//add
  79581. if ( this.object !== undefined ) {
  79582. this.object.updateMatrixWorld();
  79583. this.object.parent.matrixWorld.decompose( parentPosition, parentQuaternion, parentScale );
  79584. this.object.matrixWorld.decompose( worldPosition, worldQuaternion, worldScale );
  79585. //add
  79586. if(this.object.boundingBox){
  79587. let boundingBox = this.object.boundingBox.clone().applyMatrix4(this.object.matrixWorld);
  79588. boundingBox.getCenter(worldPosition); //bound中心
  79589. if(this.pivotOnBottom){
  79590. worldPosition.setZ(boundingBox.min.z); //中心点居于模型bound底部,因固定离地高度,旋转时旋转中心在地面上就不会变位置
  79591. }
  79592. }
  79593. parentQuaternionInv.copy( parentQuaternion ).invert();
  79594. worldQuaternionInv.copy( worldQuaternion ).invert();
  79595. }
  79596. this.camera.updateMatrixWorld();
  79597. this.camera.matrixWorld.decompose( cameraPosition, cameraQuaternion, cameraScale );
  79598. if(this.camera.type == "OrthographicCamera"){//xzw add
  79599. eye.copy( this.view.direction);
  79600. }else {
  79601. eye.copy( cameraPosition ).sub( worldPosition ).normalize();
  79602. }
  79603. Object3D.prototype.updateMatrixWorld.call( this );
  79604. };
  79605. this.pointerHover = function () {
  79606. let pointer = viewer.inputHandler.pointer;
  79607. if ( this.object === undefined)return
  79608. //if(this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */) return;
  79609. if(!this.dragging){
  79610. let oldAxis = this.axis;
  79611. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79612. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79613. ray.set(origin, direction);
  79614. Potree.Utils.setCameraLayers(ray, //设置能识别到的layers
  79615. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79616. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79617. );
  79618. var intersect = ray.intersectObjects( _gizmo.picker[ this.mode ].children.filter(e=>e.visible), true )[ 0 ] || false;
  79619. if ( intersect ) {
  79620. this.axis = intersect.object.name;
  79621. } else {
  79622. this.axis = null;
  79623. }
  79624. if(oldAxis != this.axis){
  79625. viewer.dispatchEvent('content_changed');
  79626. }
  79627. }else {
  79628. //this.pointerMove()
  79629. }
  79630. };
  79631. this.pointerDown = function ( /* pointer */ ) {
  79632. let pointer = viewer.inputHandler.pointer;
  79633. if ( this.object === undefined || this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */ ) return;
  79634. if ( /* ( pointer.button === 0 || pointer.button === undefined ) && */ this.axis !== null ) {
  79635. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79636. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79637. ray.set(origin, direction);
  79638. Potree.Utils.setCameraLayers(ray, //设置能识别到的layers
  79639. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79640. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79641. );
  79642. var planeIntersect = ray.intersectObjects( [ _plane ], true )[ 0 ] || false;
  79643. if ( planeIntersect ) {
  79644. var space = this.space;
  79645. if ( this.mode === 'scale' ) {
  79646. space = 'local';
  79647. } else if ( this.axis === 'E' || this.axis === 'XYZE' || this.axis === 'XYZ' ) {
  79648. space = 'world';
  79649. }
  79650. if ( space === 'local' && this.mode === 'rotate' ) {
  79651. var snap = this.rotationSnap;
  79652. if ( this.axis === 'X' && snap ) this.object.rotation.x = Math.round( this.object.rotation.x / snap ) * snap;
  79653. if ( this.axis === 'Y' && snap ) this.object.rotation.y = Math.round( this.object.rotation.y / snap ) * snap;
  79654. if ( this.axis === 'Z' && snap ) this.object.rotation.z = Math.round( this.object.rotation.z / snap ) * snap;
  79655. }
  79656. this.object.updateMatrixWorld();
  79657. this.object.parent.updateMatrixWorld();
  79658. positionStart.copy( this.object.position );
  79659. quaternionStart.copy( this.object.quaternion );
  79660. scaleStart.copy( this.object.scale );
  79661. this.object.matrixWorld.decompose( worldPositionStart, worldQuaternionStart, worldScaleStart );
  79662. //add: 使坐标轴在boundingBox中心
  79663. this.object.boundingBox && this.object.boundingBox.getCenter(worldPositionStart).applyMatrix4(this.object.matrixWorld);
  79664. pointStart.copy( planeIntersect.point ).sub( worldPositionStart );
  79665. /* if(this.player.cameraControls.activeControl){
  79666. //this.player.cameraControls.activeControl.locked = true; //add
  79667. this.player.cameraControls.activeControl.enabled = false; //add
  79668. } */
  79669. }
  79670. this.dragging = true;
  79671. mouseDownEvent.mode = this.mode;
  79672. this.dispatchEvent( mouseDownEvent );
  79673. }
  79674. };
  79675. this.pointerMove = function ( /* pointer */ ) {
  79676. let pointer = viewer.inputHandler.pointer;
  79677. var axis = this.axis;
  79678. var mode = this.mode;
  79679. var object = this.object;
  79680. var space = this.space;
  79681. if ( mode === 'scale' ) {
  79682. space = 'local';
  79683. } else if ( axis === 'E' || axis === 'XYZE' || axis === 'XYZ' ) {
  79684. space = 'world';
  79685. }
  79686. if ( object === undefined || axis === null || this.dragging === false || ( pointer.button !== undefined && pointer.button !== 0 ) ) return;
  79687. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79688. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79689. ray.set(origin, direction);
  79690. Potree.Utils.setCameraLayers(ray, //设置能识别到的layers
  79691. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  79692. viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers
  79693. );
  79694. var planeIntersect = ray.intersectObjects( [ _plane ], true )[ 0 ] || false;
  79695. if ( planeIntersect === false ) return;
  79696. pointEnd.copy( planeIntersect.point ).sub( worldPositionStart );
  79697. if ( mode === 'translate' ) {
  79698. // Apply translate
  79699. offset.copy( pointEnd ).sub( pointStart );
  79700. if ( space === 'local' && axis !== 'XYZ' ) {
  79701. offset.applyQuaternion( worldQuaternionInv );
  79702. }
  79703. if ( axis.indexOf( 'X' ) === - 1 ) offset.x = 0;
  79704. if ( axis.indexOf( 'Y' ) === - 1 ) offset.y = 0;
  79705. if ( axis.indexOf( 'Z' ) === - 1 ) offset.z = 0;
  79706. if ( space === 'local' && axis !== 'XYZ' ) {
  79707. //xzw 加,否则会反向---------------
  79708. object.scale.x < 0 && (offset.x *= -1);
  79709. object.scale.y < 0 && (offset.y *= -1);
  79710. object.scale.z < 0 && (offset.z *= -1);
  79711. //---------------------------------
  79712. offset.applyQuaternion( quaternionStart ).divide( parentScale );
  79713. } else {
  79714. offset.applyQuaternion( parentQuaternionInv ).divide( parentScale );
  79715. }
  79716. object.position.copy( offset ).add( positionStart );
  79717. // Apply translation snap
  79718. if ( this.translationSnap ) {
  79719. if ( space === 'local' ) {
  79720. object.position.applyQuaternion( _tempQuaternion.copy( quaternionStart ).invert() );
  79721. if ( axis.search( 'X' ) !== - 1 ) {
  79722. object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap;
  79723. }
  79724. if ( axis.search( 'Y' ) !== - 1 ) {
  79725. object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap;
  79726. }
  79727. if ( axis.search( 'Z' ) !== - 1 ) {
  79728. object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap;
  79729. }
  79730. object.position.applyQuaternion( quaternionStart );
  79731. }
  79732. if ( space === 'world' ) {
  79733. if ( object.parent ) {
  79734. object.position.add( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) );
  79735. }
  79736. if ( axis.search( 'X' ) !== - 1 ) {
  79737. object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap;
  79738. }
  79739. if ( axis.search( 'Y' ) !== - 1 ) {
  79740. object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap;
  79741. }
  79742. if ( axis.search( 'Z' ) !== - 1 ) {
  79743. object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap;
  79744. }
  79745. if ( object.parent ) {
  79746. object.position.sub( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) );
  79747. }
  79748. }
  79749. }
  79750. //add:
  79751. object.dispatchEvent({
  79752. type: "position_changed"
  79753. });
  79754. } else if ( mode === 'scale' ) {
  79755. if ( axis.search( 'XYZ' ) !== - 1 ) {
  79756. var d = pointEnd.length() / pointStart.length();
  79757. if ( pointEnd.dot( pointStart ) < 0 ) d *= - 1;
  79758. if(options.NoScaleZ){//xzw add
  79759. _tempVector2.set( d, d, 1 );
  79760. }else {
  79761. _tempVector2.set( d, d, d );
  79762. }
  79763. }else if ( axis.search( 'XY' ) !== - 1 ) { //add 等比例for plane
  79764. var d = pointEnd.length() / pointStart.length();
  79765. if ( pointEnd.dot( pointStart ) < 0 ) d *= - 1;
  79766. _tempVector2.set( d, d, 1 );
  79767. }else {
  79768. _tempVector.copy( pointStart );
  79769. _tempVector2.copy( pointEnd );
  79770. _tempVector.applyQuaternion( worldQuaternionInv );
  79771. _tempVector2.applyQuaternion( worldQuaternionInv );
  79772. _tempVector2.divide( _tempVector );
  79773. if ( axis.search( 'X' ) === - 1 ) {
  79774. _tempVector2.x = 1;
  79775. }
  79776. if ( axis.search( 'Y' ) === - 1 ) {
  79777. _tempVector2.y = 1;
  79778. }
  79779. if ( axis.search( 'Z' ) === - 1 ) {
  79780. _tempVector2.z = 1;
  79781. }
  79782. }
  79783. // Apply scale
  79784. object.scale.copy( scaleStart ).multiply( _tempVector2 );
  79785. if ( this.scaleSnap ) {
  79786. if ( axis.search( 'X' ) !== - 1 ) {
  79787. object.scale.x = Math.round( object.scale.x / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79788. }
  79789. if ( axis.search( 'Y' ) !== - 1 ) {
  79790. object.scale.y = Math.round( object.scale.y / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79791. }
  79792. if ( axis.search( 'Z' ) !== - 1 ) {
  79793. object.scale.z = Math.round( object.scale.z / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79794. }
  79795. }
  79796. //add:
  79797. object.dispatchEvent({
  79798. type: "scale_changed"
  79799. });
  79800. } else if ( mode === 'rotate' ) {
  79801. if(this.rotateMethod == 2){//新版参照transfromTool的写法,更跟手,但是有bug,在同时移动位置时或e轴上有问题
  79802. if ( axis === 'E' ) {//绕着视线转
  79803. rotationAxis.copy( eye );//旋转轴
  79804. rotationAngle = pointEnd.angleTo( pointStart );
  79805. startNorm.copy( pointStart ).normalize();
  79806. endNorm.copy( pointEnd ).normalize();
  79807. rotationAngle *= ( endNorm.cross( startNorm ).dot( eye ) < 0 ? 1 : - 1 ); //角度
  79808. }else {
  79809. if ( axis === 'XYZE' ) {//像滚球一样拨动,鼠标滑动方向为拨动方向,在plane面上滚动
  79810. offset.copy( pointEnd ).sub( pointStart );
  79811. rotationAxis.copy( offset ).cross( eye ).normalize();
  79812. }else {
  79813. rotationAxis.copy( _unit[ axis ] );
  79814. }
  79815. let center = new Vector3;//坐标轴位置
  79816. /* if(this.object.boundingBox){
  79817. center.copy(worldPosition) //center设置为boundingbox的中心。但center一直更改会导致虽然在按某个时针旋转,但v2相对v1可能会时不时逆向,导致闪烁。所以固定住center,虽然这样计算的角度和绕模型中心的感觉偏颇
  79818. }else{ */
  79819. center.copy(worldPositionStart);
  79820. //}
  79821. let rotationAxis_ = space === 'local' ? rotationAxis.clone().applyQuaternion(worldQuaternion) : rotationAxis;
  79822. let plane = new Plane().setFromNormalAndCoplanarPoint(rotationAxis_, center);//旋转过程中rotationAxis不会变化,但center可能会
  79823. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79824. ray.set(origin, direction);
  79825. let I = ray.ray.intersectPlane(plane, new Vector3());
  79826. if (I) {
  79827. let v2 = I.clone().sub(center);//.normalize();
  79828. if(!this.rotateStart){
  79829. this.rotateStart = {
  79830. v1: v2
  79831. };
  79832. return
  79833. }
  79834. let v1 = this.rotateStart.v1;
  79835. rotationAngle = math.getAngle( v1, v2, rotationAxis_);
  79836. //console.log('rot', rotationAngle, center.toArray())
  79837. if (Number.isNaN(rotationAngle)) {
  79838. return;
  79839. }
  79840. this.rotateStart.v1 = v2;
  79841. }
  79842. }
  79843. }else {
  79844. //pointStart 是起始intersect - object中心的向量
  79845. //pointEnd 是当前intersect - object中心的向量
  79846. offset.copy( pointEnd ).sub( pointStart );
  79847. var ROTATION_SPEED = 2 / worldPosition.distanceTo( _tempVector.setFromMatrixPosition( this.camera.matrixWorld ) );
  79848. if ( axis === 'E' ) {//绕着视线转
  79849. rotationAxis.copy( eye );//旋转轴
  79850. rotationAngle = pointEnd.angleTo( pointStart );
  79851. startNorm.copy( pointStart ).normalize();
  79852. endNorm.copy( pointEnd ).normalize();
  79853. rotationAngle *= ( endNorm.cross( startNorm ).dot( eye ) < 0 ? 1 : - 1 ); //角度
  79854. } else if ( axis === 'XYZE' ) {//像滚球一样拨动,鼠标滑动方向为拨动方向,在plane面上滚动
  79855. rotationAxis.copy( offset ).cross( eye ).normalize();
  79856. rotationAngle = offset.dot( _tempVector.copy( rotationAxis ).cross( this.eye ) ) * ROTATION_SPEED;
  79857. } else if ( axis === 'X' || axis === 'Y' || axis === 'Z' ) {
  79858. rotationAxis.copy( _unit[ axis ] );
  79859. _tempVector.copy( _unit[ axis ] );
  79860. if ( space === 'local' ) {
  79861. _tempVector.applyQuaternion( worldQuaternion );
  79862. }
  79863. rotationAngle = offset.dot( _tempVector.cross( eye ).normalize() ) * ROTATION_SPEED;
  79864. }
  79865. // Apply rotation snap
  79866. if ( this.rotationSnap ) rotationAngle = Math.round( rotationAngle / this.rotationSnap ) * this.rotationSnap;
  79867. this.rotationAngle = rotationAngle;
  79868. }
  79869. // Apply rotate
  79870. if ( space === 'local' && axis !== 'E' && axis !== 'XYZE' ) {
  79871. object.scale[axis.toLowerCase()] < 0 && (rotationAngle *= -1); //xzw 加,否则会反向
  79872. object.quaternion.copy( quaternionStart );
  79873. object.quaternion.multiply( _tempQuaternion.setFromAxisAngle( rotationAxis, rotationAngle ) ).normalize();
  79874. } else {
  79875. rotationAxis.applyQuaternion( parentQuaternionInv );
  79876. object.quaternion.copy( _tempQuaternion.setFromAxisAngle( rotationAxis, rotationAngle ) );
  79877. object.quaternion.multiply( quaternionStart ).normalize();
  79878. }
  79879. if ( this.rotateMethod == 2 && axis != 'E' ) {
  79880. quaternionStart.copy(object.quaternion);
  79881. }
  79882. //add:
  79883. object.dispatchEvent({
  79884. type: "rotation_changed"
  79885. });
  79886. }
  79887. this.dispatchEvent( changeEvent );
  79888. this.dispatchEvent( objectChangeEvent );
  79889. viewer.dispatchEvent('content_changed');
  79890. };
  79891. this.pointerUp = function ( pointer ) {
  79892. //if ( pointer.button !== undefined && pointer.button !== 0 ) return;
  79893. if ( this.dragging && ( this.axis !== null ) ) {
  79894. mouseUpEvent.mode = this.mode;
  79895. this.dispatchEvent( mouseUpEvent );
  79896. /* if(this.player.cameraControls.activeControl){
  79897. //this.player.cameraControls.activeControl.locked = false; //add
  79898. this.player.cameraControls.activeControl.pointerDragOn = false //add
  79899. this.player.cameraControls.activeControl.enabled = true
  79900. } */
  79901. this.rotateStart = null;//add
  79902. this.dispatchEvent({type:'transform_end'});
  79903. }
  79904. this.dragging = false;
  79905. //if ( pointer.button === undefined ) this.axis = null;
  79906. /* if(this.player.cameraControls.activeControl){
  79907. //this.player.cameraControls.activeControl.locked = false; //add
  79908. this.player.cameraControls.activeControl.pointerDragOn = false //add
  79909. this.player.cameraControls.activeControl.enabled = true
  79910. } */
  79911. };
  79912. // normalize mouse / touch pointer and remap {x,y} to view space.
  79913. function getPointer( event ) {
  79914. if(!event){
  79915. console.log('hhahhhahah');
  79916. return;
  79917. }
  79918. if ( document.pointerLockElement ) {
  79919. return {
  79920. x: 0,
  79921. y: 0,
  79922. button: event.button
  79923. };
  79924. } else {
  79925. var pointer = event.changedTouches ? event.changedTouches[ 0 ] : event;
  79926. var rect = domElement.getBoundingClientRect();
  79927. return {
  79928. x: ( pointer.clientX - rect.left ) / rect.width * 2 - 1,
  79929. y: - ( pointer.clientY - rect.top ) / rect.height * 2 + 1,
  79930. button: event.button
  79931. };
  79932. }
  79933. }
  79934. // mouse / touch event handlers
  79935. function onPointerHover( event ) {
  79936. if ( ! scope.enabled ) return;
  79937. //scope.pointerHover( getPointer( event ) );
  79938. scope.pointerHover( );
  79939. }
  79940. function onPointerDown( event ) {
  79941. if ( ! scope.enabled ) return;
  79942. //document.addEventListener( "mousemove", onPointerMove, false );
  79943. /* scope.pointerHover( getPointer( event ) );
  79944. scope.pointerDown( getPointer( event ) ); */
  79945. scope.pointerHover( );
  79946. scope.pointerDown();
  79947. }
  79948. this.onPointerDown = onPointerDown;
  79949. function onPointerMove( event ) {
  79950. if ( ! scope.enabled || !this.dragging) return; //xzw change
  79951. //scope.pointerMove( getPointer( event ) );
  79952. scope.pointerMove( );
  79953. }
  79954. this.onPointerMove = onPointerMove;
  79955. function onPointerUp( event ) {
  79956. if ( ! scope.enabled ) return;
  79957. //document.removeEventListener( "mousemove", onPointerMove, false );
  79958. //scope.pointerUp( getPointer( event ) );
  79959. scope.pointerUp( );
  79960. }
  79961. this.onPointerUp = onPointerUp;
  79962. // TODO: deprecate
  79963. this.getMode = function () {
  79964. return scope.mode;
  79965. };
  79966. this.setMode = function ( mode ) {
  79967. scope.mode = mode;
  79968. };
  79969. this.setTranslationSnap = function ( translationSnap ) {
  79970. scope.translationSnap = translationSnap;
  79971. };
  79972. this.setRotationSnap = function ( rotationSnap ) {
  79973. scope.rotationSnap = rotationSnap;
  79974. };
  79975. this.setScaleSnap = function ( scaleSnap ) {
  79976. scope.scaleSnap = scaleSnap;
  79977. };
  79978. this.setSize = function ( size ) {
  79979. scope.size = size;
  79980. };
  79981. this.setSpace = function ( space ) {
  79982. scope.space = space;
  79983. };
  79984. this.update = function () {
  79985. console.warn( 'THREE.TransformControls: update function has no more functionality and therefore has been deprecated.' );
  79986. };
  79987. };
  79988. var TransformControlsGizmo = function (options) {
  79989. 'use strict';
  79990. Object3D.call( this );
  79991. this.type = 'TransformControlsGizmo';
  79992. // shared materials
  79993. this.hideAxis = {};
  79994. var gizmoMaterial = new MeshBasicMaterial( {
  79995. depthTest: false,
  79996. depthWrite: false,
  79997. transparent: true,
  79998. side: DoubleSide,
  79999. fog: false
  80000. } );
  80001. var gizmoLineMaterial = new LineBasicMaterial( {
  80002. depthTest: false,
  80003. depthWrite: false,
  80004. transparent: true,
  80005. fog: false
  80006. } );
  80007. // Make unique material for each axis/color
  80008. var matInvisible = gizmoMaterial.clone();
  80009. matInvisible.opacity = 0.15;
  80010. var matHelper = gizmoMaterial.clone();
  80011. matHelper.opacity = 0.1;
  80012. var matRed = gizmoMaterial.clone();
  80013. matRed.color.set( 0xff0000 );
  80014. var matGreen = gizmoMaterial.clone();
  80015. matGreen.color.set( 0x00ff00 );
  80016. var matBlue = gizmoMaterial.clone();
  80017. matBlue.color.set( 0x0000ff );
  80018. var matWhiteTransparent = gizmoMaterial.clone();
  80019. matWhiteTransparent.opacity = 0.35;
  80020. matWhiteTransparent.color.set( 0x00d0fd );//xzw add
  80021. var matYellowTransparent = matWhiteTransparent.clone();
  80022. matYellowTransparent.color.set( 0xffff00 );
  80023. var matCyanTransparent = matWhiteTransparent.clone();
  80024. matCyanTransparent.color.set( 0x00ffff );
  80025. var matMagentaTransparent = matWhiteTransparent.clone();
  80026. matMagentaTransparent.color.set( 0xff00ff );
  80027. var matYellow = gizmoMaterial.clone();
  80028. matYellow.color.set( 0xffff00 );
  80029. var matLineRed = gizmoLineMaterial.clone();
  80030. matLineRed.color.set( 0xff0000 );
  80031. var matLineGreen = gizmoLineMaterial.clone();
  80032. matLineGreen.color.set( 0x00ff00 );
  80033. var matLineBlue = gizmoLineMaterial.clone();
  80034. matLineBlue.color.set( 0x0000ff );
  80035. var matLineCyan = gizmoLineMaterial.clone();
  80036. matLineCyan.color.set( 0x00ffff );
  80037. var matLineMagenta = gizmoLineMaterial.clone();
  80038. matLineMagenta.color.set( 0xff00ff );
  80039. var matLineYellow = gizmoLineMaterial.clone();
  80040. matLineYellow.color.set( 0xffff00 );
  80041. var matLineGray = gizmoLineMaterial.clone();
  80042. matLineGray.color.set( 0x787878 );
  80043. var matLineYellowTransparent = matLineYellow.clone();
  80044. matLineYellowTransparent.opacity = 0.25;
  80045. // reusable geometry
  80046. var arrowGeometry = new CylinderBufferGeometry( 0, 0.05, 0.2, 12, 1, false );
  80047. var scaleHandleGeometry = new BoxBufferGeometry( 0.125, 0.125, 0.125 );
  80048. var lineGeometry = new BufferGeometry( );
  80049. //lineGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) );
  80050. lineGeometry.setAttribute("position", new BufferAttribute(new Float32Array([ 0, 0, 0, 1, 0, 0]), 3 ));
  80051. var CircleGeometry = function ( radius, arc ) {
  80052. var geometry = new BufferGeometry( );
  80053. var vertices = [];
  80054. for ( var i = 0; i <= 64 * arc; ++ i ) {
  80055. vertices.push( 0, Math.cos( i / 32 * Math.PI ) * radius, Math.sin( i / 32 * Math.PI ) * radius );
  80056. }
  80057. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  80058. geometry.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3 ));
  80059. return geometry;
  80060. };
  80061. // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position
  80062. var TranslateHelperGeometry = function () {
  80063. var geometry = new BufferGeometry();
  80064. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 1, 1 ], 3 ) );
  80065. geometry.setAttribute("position", new BufferAttribute(new Float32Array([ 0, 0, 0, 1, 1, 1 ]), 3 ));
  80066. return geometry;
  80067. };
  80068. // Gizmo definitions - custom hierarchy definitions for setupGizmo() function
  80069. var gizmoTranslate = {
  80070. X: [
  80071. [ new Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, - Math.PI / 2 ], null, 'fwd' ],
  80072. //[ new THREE.Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, Math.PI / 2 ], null, 'bwd' ],
  80073. [ new Line( lineGeometry, matLineRed ) ]
  80074. ],
  80075. Y: [
  80076. [ new Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], null, null, 'fwd' ],
  80077. //[ new THREE.Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], [ Math.PI, 0, 0 ], null, 'bwd' ],
  80078. [ new Line( lineGeometry, matLineGreen ), null, [ 0, 0, Math.PI / 2 ]]
  80079. ],
  80080. Z: [
  80081. [ new Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ Math.PI / 2, 0, 0 ], null, 'fwd' ],
  80082. //[ new THREE.Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ - Math.PI / 2, 0, 0 ], null, 'bwd' ],
  80083. [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ]]
  80084. ],
  80085. /* XYZ: [
  80086. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransparent.clone() ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
  80087. ], */
  80088. XY: [
  80089. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matYellowTransparent.clone() ), [ 0.15, 0.15, 0 ]],
  80090. [ new Line( lineGeometry, matLineYellow ), [ 0.18, 0.3, 0 ], null, [ 0.125, 1, 1 ]],
  80091. [ new Line( lineGeometry, matLineYellow ), [ 0.3, 0.18, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
  80092. ],
  80093. YZ: [
  80094. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matCyanTransparent.clone() ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]],
  80095. [ new Line( lineGeometry, matLineCyan ), [ 0, 0.18, 0.3 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  80096. [ new Line( lineGeometry, matLineCyan ), [ 0, 0.3, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80097. ],
  80098. XZ: [
  80099. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matMagentaTransparent.clone() ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]],
  80100. [ new Line( lineGeometry, matLineMagenta ), [ 0.18, 0, 0.3 ], null, [ 0.125, 1, 1 ]],
  80101. [ new Line( lineGeometry, matLineMagenta ), [ 0.3, 0, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80102. ]
  80103. };
  80104. var pickerTranslate = {
  80105. X: [
  80106. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0.6, 0, 0 ], [ 0, 0, - Math.PI / 2 ]]
  80107. ],
  80108. Y: [
  80109. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0, 0.6, 0 ]]
  80110. ],
  80111. Z: [
  80112. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0, 0, 0.6 ], [ Math.PI / 2, 0, 0 ]]
  80113. ],
  80114. /* XYZ: [
  80115. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.2, 0 ), matInvisible ) ]
  80116. ], */
  80117. XY: [
  80118. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0.2, 0.2, 0 ]]
  80119. ],
  80120. YZ: [
  80121. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0, 0.2, 0.2 ], [ 0, Math.PI / 2, 0 ]]
  80122. ],
  80123. XZ: [
  80124. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0.2, 0, 0.2 ], [ - Math.PI / 2, 0, 0 ]]
  80125. ]
  80126. };
  80127. var helperTranslate = {
  80128. START: [
  80129. [ new Mesh( new OctahedronBufferGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ]
  80130. ],
  80131. END: [
  80132. [ new Mesh( new OctahedronBufferGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ]
  80133. ],
  80134. DELTA: [
  80135. [ new Line( TranslateHelperGeometry(), matHelper ), null, null, null, 'helper' ]
  80136. ],
  80137. X: [
  80138. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80139. ],
  80140. Y: [
  80141. [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ]
  80142. ],
  80143. Z: [
  80144. [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ]
  80145. ]
  80146. };
  80147. let arc = options.rotFullCircle ? 1 : 0.5;//add
  80148. var gizmoRotate = {
  80149. X: [
  80150. [ new Line( CircleGeometry( 1, arc ), matLineRed ) ],
  80151. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matRed ), [ 0, 0, 0.99 ], null, [ 1, 3, 1 ]],
  80152. ],
  80153. Y: [
  80154. [ new Line( CircleGeometry( 1, arc ), matLineGreen ), null, [ 0, 0, - Math.PI / 2 ]],
  80155. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matGreen ), [ 0, 0, 0.99 ], null, [ 3, 1, 1 ]],
  80156. ],
  80157. Z: [
  80158. [ new Line( CircleGeometry( 1, arc ), matLineBlue ), null, [ 0, Math.PI / 2, 0 ]],
  80159. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matBlue ), [ 0.99, 0, 0 ], null, [ 1, 3, 1 ]],
  80160. ],
  80161. E: [
  80162. [ new Line( CircleGeometry( 1.25, 1 ), matLineYellowTransparent ), null, [ 0, Math.PI / 2, 0 ]],
  80163. [ 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 ]],
  80164. [ 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 ]],
  80165. [ 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 ]],
  80166. [ new Mesh( new CylinderBufferGeometry( 0.03, 0, 0.15, 4, 1, false ), matLineYellowTransparent ), [ 0, 1.17, 0 ], [ 0, 0, 0 ], [ 1, 1, 0.001 ]],
  80167. ],
  80168. XYZE: [
  80169. [ new Line( CircleGeometry( 1, 1 ), matLineGray ), null, [ 0, Math.PI / 2, 0 ]]
  80170. ]
  80171. };
  80172. var helperRotate = {
  80173. AXIS: [
  80174. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80175. ]
  80176. };
  80177. var pickerRotate = {
  80178. X: [
  80179. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, - Math.PI / 2, - Math.PI / 2 ]],
  80180. ],
  80181. Y: [
  80182. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ Math.PI / 2, 0, 0 ]],
  80183. ],
  80184. Z: [
  80185. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, 0, - Math.PI / 2 ]],
  80186. ],
  80187. E: [
  80188. [ new Mesh( new TorusBufferGeometry( 1.25, 0.1, 2, 24 ), matInvisible ) ]
  80189. ],
  80190. XYZE: [
  80191. [ new Mesh( new SphereBufferGeometry( 0.7, 10, 8 ), matInvisible ) ]
  80192. ]
  80193. };
  80194. var gizmoScale = {
  80195. X: [
  80196. [ new Mesh( scaleHandleGeometry, matRed ), [ 0.8, 0, 0 ], [ 0, 0, - Math.PI / 2 ]],
  80197. [ new Line( lineGeometry, matLineRed ), null, null, [ 0.8, 1, 1 ]]
  80198. ],
  80199. Y: [
  80200. [ new Mesh( scaleHandleGeometry, matGreen ), [ 0, 0.8, 0 ]],
  80201. [ new Line( lineGeometry, matLineGreen ), null, [ 0, 0, Math.PI / 2 ], [ 0.8, 1, 1 ]]
  80202. ],
  80203. Z: [
  80204. [ new Mesh( scaleHandleGeometry, matBlue ), [ 0, 0, 0.8 ], [ Math.PI / 2, 0, 0 ]],
  80205. [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ], [ 0.8, 1, 1 ]]
  80206. ],
  80207. XY: [
  80208. [ new Mesh( scaleHandleGeometry, matYellowTransparent ), [ 0.85, 0.85, 0 ], null, [ 2, 2, 0.2 ]],
  80209. [ new Line( lineGeometry, matLineYellow ), [ 0.855, 0.98, 0 ], null, [ 0.125, 1, 1 ]],
  80210. [ new Line( lineGeometry, matLineYellow ), [ 0.98, 0.855, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
  80211. ],
  80212. /* YZ: [
  80213. [ new THREE.Mesh( scaleHandleGeometry, matCyanTransparent ), [ 0, 0.85, 0.85 ], null, [ 0.2, 2, 2 ]],
  80214. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.855, 0.98 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  80215. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.98, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80216. ],
  80217. XZ: [
  80218. [ new THREE.Mesh( scaleHandleGeometry, matMagentaTransparent ), [ 0.85, 0, 0.85 ], null, [ 2, 0.2, 2 ]],
  80219. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.855, 0, 0.98 ], null, [ 0.125, 1, 1 ]],
  80220. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.98, 0, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  80221. ],
  80222. XYZX: [
  80223. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 1.1, 0, 0 ]],
  80224. ],*/
  80225. XYZY: [
  80226. [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 1.1, 0 ]],
  80227. ]/* ,
  80228. XYZZ: [
  80229. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 0, 1.1 ]],
  80230. ] */
  80231. };
  80232. var pickerScale = {
  80233. X: [
  80234. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0.5, 0, 0 ], [ 0, 0, - Math.PI / 2 ]]
  80235. ],
  80236. Y: [
  80237. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0, 0.5, 0 ]]
  80238. ],
  80239. Z: [
  80240. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0, 0, 0.5 ], [ Math.PI / 2, 0, 0 ]]
  80241. ],
  80242. XY: [
  80243. [ new Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0.85, 0 ], null, [ 3, 3, 0.2 ]],
  80244. ],
  80245. /*YZ: [
  80246. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0, 0.85, 0.85 ], null, [ 0.2, 3, 3 ]],
  80247. ],
  80248. XZ: [
  80249. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0, 0.85 ], null, [ 3, 0.2, 3 ]],
  80250. ],
  80251. XYZX: [
  80252. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 1.1, 0, 0 ]],
  80253. ],*/
  80254. XYZY: [
  80255. [ new Mesh( new BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 1.1, 0 ]],
  80256. ]/* ,
  80257. XYZZ: [
  80258. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 0, 1.1 ]],
  80259. ] */
  80260. };
  80261. var helperScale = {
  80262. X: [
  80263. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  80264. ],
  80265. Y: [
  80266. [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ]
  80267. ],
  80268. Z: [
  80269. [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ]
  80270. ]
  80271. };
  80272. // Creates an THREE.Object3D with gizmos described in custom hierarchy definition.
  80273. var setupGizmo = function ( gizmoMap ) {
  80274. var gizmo = new Object3D();
  80275. for ( var name in gizmoMap ) {
  80276. for ( var i = gizmoMap[ name ].length; i --; ) {
  80277. var object = gizmoMap[ name ][ i ][ 0 ].clone();
  80278. var position = gizmoMap[ name ][ i ][ 1 ];
  80279. var rotation = gizmoMap[ name ][ i ][ 2 ];
  80280. var scale = gizmoMap[ name ][ i ][ 3 ];
  80281. var tag = gizmoMap[ name ][ i ][ 4 ];
  80282. // name and tag properties are essential for picking and updating logic.
  80283. object.name = name;
  80284. object.tag = tag;
  80285. if ( position ) {
  80286. object.position.set( position[ 0 ], position[ 1 ], position[ 2 ] );
  80287. }
  80288. if ( rotation ) {
  80289. object.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ] );
  80290. }
  80291. if ( scale ) {
  80292. object.scale.set( scale[ 0 ], scale[ 1 ], scale[ 2 ] );
  80293. }
  80294. object.updateMatrix();
  80295. var tempGeometry = object.geometry.clone();
  80296. tempGeometry.applyMatrix4( object.matrix );
  80297. object.geometry = tempGeometry;
  80298. object.renderOrder = Infinity;
  80299. object.position.set( 0, 0, 0 );
  80300. object.rotation.set( 0, 0, 0 );
  80301. object.scale.set( 1, 1, 1 );
  80302. gizmo.add( object );
  80303. }
  80304. }
  80305. return gizmo;
  80306. };
  80307. // Reusable utility variables
  80308. var tempVector = new Vector3( 0, 0, 0 );
  80309. var tempEuler = new Euler();
  80310. var alignVector = new Vector3( 0, 1, 0 );
  80311. var zeroVector = new Vector3( 0, 0, 0 );
  80312. var lookAtMatrix = new Matrix4();
  80313. var tempQuaternion = new Quaternion();
  80314. var tempQuaternion2 = new Quaternion();
  80315. var identityQuaternion = new Quaternion();
  80316. var unitX = new Vector3( 1, 0, 0 );
  80317. var unitY = new Vector3( 0, 1, 0 );
  80318. var unitZ = new Vector3( 0, 0, 1 );
  80319. // Gizmo creation
  80320. this.gizmo = {};
  80321. this.picker = {};
  80322. this.helper = {};
  80323. this.add( this.gizmo[ "translate" ] = setupGizmo( gizmoTranslate ) );
  80324. this.add( this.gizmo[ "rotate" ] = setupGizmo( gizmoRotate ) );
  80325. this.add( this.gizmo[ "scale" ] = setupGizmo( gizmoScale ) );
  80326. this.add( this.picker[ "translate" ] = setupGizmo( pickerTranslate ) );
  80327. this.add( this.picker[ "rotate" ] = setupGizmo( pickerRotate ) );
  80328. this.add( this.picker[ "scale" ] = setupGizmo( pickerScale ) );
  80329. this.add( this.helper[ "translate" ] = setupGizmo( helperTranslate ) );
  80330. this.add( this.helper[ "rotate" ] = setupGizmo( helperRotate ) );
  80331. this.add( this.helper[ "scale" ] = setupGizmo( helperScale ) );
  80332. // Pickers should be hidden always
  80333. this.picker[ "translate" ].visible = false;
  80334. this.picker[ "rotate" ].visible = false;
  80335. this.picker[ "scale" ].visible = false;
  80336. // updateMatrixWorld will update transformations and appearance of individual handles
  80337. this.updateMatrixWorld = function () {
  80338. if(!this.parent.visible)return //add
  80339. var space = this.space;
  80340. if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation
  80341. var quaternion = space === "local" ? this.worldQuaternion : identityQuaternion;
  80342. // Show only gizmos for current transform mode
  80343. this.gizmo[ "translate" ].visible = this.mode === "translate";
  80344. this.gizmo[ "rotate" ].visible = this.mode === "rotate";
  80345. this.gizmo[ "scale" ].visible = this.mode === "scale";
  80346. this.helper[ "translate" ].visible = this.mode === "translate";
  80347. this.helper[ "rotate" ].visible = this.mode === "rotate";
  80348. this.helper[ "scale" ].visible = this.mode === "scale";
  80349. var handles = [];
  80350. handles = handles.concat( this.picker[ this.mode ].children );
  80351. handles = handles.concat( this.gizmo[ this.mode ].children );
  80352. handles = handles.concat( this.helper[ this.mode ].children );
  80353. for ( var i = 0; i < handles.length; i ++ ) {
  80354. var handle = handles[ i ];
  80355. //add
  80356. if(this.hideAxis[this.mode] && this.hideAxis[this.mode].some(e=>handle.name.includes(e.toUpperCase()))){
  80357. Potree.Utils.updateVisible(handle, 'hidden', false);
  80358. continue
  80359. }
  80360. let visible = true;
  80361. // hide aligned to camera
  80362. handle.rotation.set( 0, 0, 0 );
  80363. handle.position.copy( this.worldPosition );
  80364. if(this.camera.type == "OrthographicCamera"){
  80365. var eyeDistance = 800 / this.camera.zoom;
  80366. }else {
  80367. var eyeDistance = this.worldPosition.distanceTo( this.cameraPosition );
  80368. }
  80369. handle.scale.set( 1, 1, 1 ).multiplyScalar( eyeDistance * this.size / 7 );
  80370. // TODO: simplify helpers and consider decoupling from gizmo
  80371. if ( handle.tag === 'helper' ) {
  80372. visible = false;
  80373. if ( handle.name === 'AXIS' ) {
  80374. handle.position.copy( this.worldPositionStart );
  80375. visible = !!this.axis;
  80376. if ( this.axis === 'X' ) {
  80377. tempQuaternion.setFromEuler( tempEuler.set( 0, 0, 0 ) );
  80378. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80379. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80380. visible = false;
  80381. }
  80382. }
  80383. if ( this.axis === 'Y' ) {
  80384. tempQuaternion.setFromEuler( tempEuler.set( 0, 0, Math.PI / 2 ) );
  80385. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80386. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80387. visible = false;
  80388. }
  80389. }
  80390. if ( this.axis === 'Z' ) {
  80391. tempQuaternion.setFromEuler( tempEuler.set( 0, Math.PI / 2, 0 ) );
  80392. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  80393. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  80394. visible = false;
  80395. }
  80396. }
  80397. if ( this.axis === 'XYZE' ) {
  80398. tempQuaternion.setFromEuler( tempEuler.set( 0, Math.PI / 2, 0 ) );
  80399. alignVector.copy( this.rotationAxis );
  80400. handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( zeroVector, alignVector, unitY ) );
  80401. handle.quaternion.multiply( tempQuaternion );
  80402. visible = this.dragging;
  80403. }
  80404. if ( this.axis === 'E' ) {
  80405. visible = false;
  80406. }
  80407. } else if ( handle.name === 'START' ) {
  80408. handle.position.copy( this.worldPositionStart );
  80409. visible = this.dragging;
  80410. } else if ( handle.name === 'END' ) {
  80411. handle.position.copy( this.worldPosition );
  80412. visible = this.dragging;
  80413. } else if ( handle.name === 'DELTA' ) {
  80414. handle.position.copy( this.worldPositionStart );
  80415. handle.quaternion.copy( this.worldQuaternionStart );
  80416. tempVector.set( 1e-10, 1e-10, 1e-10 ).add( this.worldPositionStart ).sub( this.worldPosition ).multiplyScalar( - 1 );
  80417. tempVector.applyQuaternion( this.worldQuaternionStart.clone().invert() );
  80418. handle.scale.copy( tempVector );
  80419. visible = this.dragging;
  80420. } else {
  80421. handle.quaternion.copy( quaternion );
  80422. if ( this.dragging ) {
  80423. handle.position.copy( this.worldPositionStart );
  80424. } else {
  80425. handle.position.copy( this.worldPosition );
  80426. }
  80427. if ( this.axis ) {
  80428. visible = this.axis.search( handle.name ) !== - 1;
  80429. }
  80430. }
  80431. // If updating helper, skip rest of the loop
  80432. Potree.Utils.updateVisible(handle, 'hidden', !!visible);
  80433. continue;
  80434. }
  80435. // Align handles to current local or world rotation
  80436. handle.quaternion.copy( quaternion );
  80437. if ( this.mode === 'translate' || this.mode === 'scale' ) {
  80438. // Hide translate and scale axis facing the camera
  80439. var AXIS_HIDE_TRESHOLD = 0.99;
  80440. var PLANE_HIDE_TRESHOLD = 0.2;
  80441. var AXIS_FLIP_TRESHOLD = 0.0;
  80442. if(options.dontHideWhenFaceCamera){//xzw add
  80443. //正对镜头时不隐藏箭头
  80444. }else {
  80445. if ( handle.name === 'X' || handle.name === 'XYZX' ) {
  80446. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80447. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80448. visible = false;
  80449. }
  80450. }
  80451. if ( handle.name === 'Y' || handle.name === 'XYZY' ) {
  80452. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80453. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80454. visible = false;
  80455. }
  80456. }
  80457. if ( handle.name === 'Z' || handle.name === 'XYZZ' ) {
  80458. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80459. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80460. visible = false;
  80461. }
  80462. }
  80463. if ( handle.name === 'XY' ) {
  80464. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80465. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80466. visible = false;
  80467. }
  80468. }
  80469. if ( handle.name === 'YZ' ) {
  80470. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80471. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80472. visible = false;
  80473. }
  80474. }
  80475. if ( handle.name === 'XZ' ) {
  80476. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80477. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80478. visible = false;
  80479. }
  80480. }
  80481. }
  80482. // Flip translate and scale axis ocluded behind another axis
  80483. //xzw 改 去掉反向箭头
  80484. if ( handle.name.search( 'X' ) !== - 1 ) {
  80485. if ( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80486. /* if ( handle.tag === 'fwd' ) {
  80487. handle.visible = false;
  80488. } else {
  80489. handle.scale.x *= - 1;
  80490. }
  80491. } else if ( handle.tag === 'bwd' ) {
  80492. handle.visible = false;*/
  80493. handle.scale.x *= - 1;
  80494. }
  80495. }
  80496. if ( handle.name.search( 'Y' ) !== - 1 ) {
  80497. if ( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80498. /* if ( handle.tag === 'fwd' ) {
  80499. handle.visible = false;
  80500. } else {
  80501. handle.scale.y *= - 1;
  80502. }
  80503. } else if ( handle.tag === 'bwd' ) {
  80504. handle.visible = false;
  80505. */
  80506. handle.scale.y *= - 1;
  80507. }
  80508. }
  80509. if ( handle.name.search( 'Z' ) !== - 1 ) {
  80510. if ( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80511. /* if ( handle.tag === 'fwd' ) {
  80512. handle.visible = false;
  80513. } else {
  80514. handle.scale.z *= - 1;
  80515. }
  80516. } else if ( handle.tag === 'bwd' ) {
  80517. handle.visible = false; */
  80518. handle.scale.z *= - 1;
  80519. }
  80520. }
  80521. } else if ( this.mode === 'rotate' ) {
  80522. // Align handles to current local or world rotation
  80523. tempQuaternion2.copy( quaternion );
  80524. alignVector.copy( this.eye ).applyQuaternion( tempQuaternion.copy( quaternion ).invert() );
  80525. if ( handle.name.search( "E" ) !== - 1 ) {
  80526. handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( this.eye, zeroVector, unitY ) );
  80527. }
  80528. if ( handle.name === 'X' ) {
  80529. tempQuaternion.setFromAxisAngle( unitX, Math.atan2( - alignVector.y, alignVector.z ) );
  80530. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80531. handle.quaternion.copy( tempQuaternion );
  80532. }
  80533. if ( handle.name === 'Y' ) {
  80534. tempQuaternion.setFromAxisAngle( unitY, Math.atan2( alignVector.x, alignVector.z ) );
  80535. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80536. handle.quaternion.copy( tempQuaternion );
  80537. }
  80538. if ( handle.name === 'Z' ) {
  80539. tempQuaternion.setFromAxisAngle( unitZ, Math.atan2( alignVector.y, alignVector.x ) );
  80540. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80541. handle.quaternion.copy( tempQuaternion );
  80542. }
  80543. }
  80544. // Hide disabled axes
  80545. visible = visible && ( handle.name.indexOf( "X" ) === - 1 || this.showX );
  80546. visible = visible && ( handle.name.indexOf( "Y" ) === - 1 || this.showY );
  80547. visible = visible && ( handle.name.indexOf( "Z" ) === - 1 || this.showZ );
  80548. visible = visible && ( handle.name.indexOf( "E" ) === - 1 || ( this.showX && this.showY && this.showZ ) );
  80549. Potree.Utils.updateVisible(handle, 'hidden', !!visible);
  80550. // highlight selected axis
  80551. handle.material._opacity = handle.material._opacity || handle.material.opacity;
  80552. handle.material._color = handle.material._color || handle.material.color.clone();
  80553. handle.material.color.copy( handle.material._color );
  80554. handle.material.opacity = handle.material._opacity;
  80555. if ( ! this.enabled ) {
  80556. handle.material.opacity *= 0.5;
  80557. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80558. } else if ( this.axis ) {
  80559. if ( handle.name === this.axis ) {
  80560. handle.material.opacity = 1.0;
  80561. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80562. } else if ( this.axis.split( '' ).some( function ( a ) {
  80563. return handle.name === a;
  80564. } ) ) {
  80565. handle.material.opacity = 1.0;
  80566. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80567. } else {
  80568. handle.material.opacity *= 0.25;
  80569. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80570. }
  80571. }
  80572. }
  80573. Object3D.prototype.updateMatrixWorld.call( this );
  80574. };
  80575. };
  80576. /* var TransformControlsLines = function (options) {
  80577. THREE.Object3D.call( this)
  80578. let label1 = new Label2D({ innerHTML:`<div>与相机水平距离</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  80579. let label2 = new Label2D({ innerHTML:`<div>与相机高度差</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  80580. let css = {'opacity': 0.7, 'color': '#07fceb', transform:'translate(-50%, -50%)'}
  80581. label1.elem.css(css);
  80582. label2.elem.css(css)
  80583. //for(let i=0;i<2;i++){
  80584. // let line = LineDraw.createLine([new THREE.THREE.Vector3, new THREE.THREE.Vector3],{color:'#07fceb', opacity:0.7 })
  80585. // this.add(line)
  80586. //}
  80587. this.updateTransform = function(object){
  80588. object = object || this.parent.object;
  80589. let A = player.position.clone(); //当前相机位置
  80590. let B = object.position //物体位置
  80591. let C = B.clone().setY(A.y); //物体在相机的高度的位置
  80592. let D = A.clone().setY(B.y); //相机在物体的高度的位置
  80593. //LineDraw.moveLine(this.children[0], [B, C]) // 垂直线
  80594. //LineDraw.moveLine(this.children[1], [D, B]) // 水平线
  80595. let dis1 = toPrecision(D.distanceTo(B),1)
  80596. let dis2 = C.y - B.y
  80597. label1.elem.text('与相机水平距离: '+dis1+'米')
  80598. label2.elem.text('在相机之'+ (dis2>0?'下' : '上') +' :'+ toPrecision(dis2 , 1) +'米')
  80599. label1.setPos(new THREE.THREE.Vector3().addVectors(D,B).multiplyScalar(0.5))
  80600. label2.setPos(new THREE.THREE.Vector3().addVectors(B,C).multiplyScalar(0.5))
  80601. }
  80602. this.setVisible = (v,reason)=>{
  80603. label1.setVisible(v, reason || 'unvisi')
  80604. label2.setVisible(v, reason || 'unvisi')
  80605. this.visible = label1.visible
  80606. if(this.visible){
  80607. this.updateTransform()
  80608. }
  80609. }
  80610. this.setVisible(false)
  80611. player.on("mode.changing",(currentMode, mode, pano, duration)=>{
  80612. if(mode != 'panorama'){
  80613. this.setVisible(false, 'isPanorama')
  80614. }else{
  80615. this.setVisible(true, 'isPanorama')
  80616. }
  80617. })
  80618. player.on("flying.started",( )=>{
  80619. this.setVisible(false, 'flying')
  80620. })
  80621. player.on("flying.ended",( )=>{
  80622. this.setVisible(true, 'flying')
  80623. })
  80624. }
  80625. */
  80626. var TransformControlsPlane = function (options) {
  80627. 'use strict';
  80628. Mesh.call( this,
  80629. new PlaneBufferGeometry( 100000, 100000, 2, 2 ),
  80630. new MeshBasicMaterial( { color: "#ff0000", visible: false, wireframe: false, side: DoubleSide, transparent: true, opacity: 0.2 } )
  80631. );
  80632. this.type = 'TransformControlsPlane';
  80633. var unitX = new Vector3( 1, 0, 0 );
  80634. var unitY = new Vector3( 0, 1, 0 );
  80635. var unitZ = new Vector3( 0, 0, 1 );
  80636. var tempVector = new Vector3();
  80637. var dirVector = new Vector3();
  80638. var alignVector = new Vector3();
  80639. var tempMatrix = new Matrix4();
  80640. var identityQuaternion = new Quaternion();
  80641. this.updateMatrixWorld = function () {
  80642. if(!this.visible)return//add
  80643. var space = this.space;
  80644. this.position.copy( this.worldPosition );
  80645. if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation
  80646. unitX.set( 1, 0, 0 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80647. unitY.set( 0, 1, 0 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80648. unitZ.set( 0, 0, 1 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80649. // Align the plane for current transform mode, axis and space.
  80650. alignVector.copy( unitY );
  80651. switch ( this.mode ) {
  80652. case 'translate':
  80653. case 'scale':
  80654. switch ( this.axis ) {
  80655. case 'X':
  80656. alignVector.copy( this.eye ).cross( unitX );
  80657. dirVector.copy( unitX ).cross( alignVector );
  80658. break;
  80659. case 'Y':
  80660. alignVector.copy( this.eye ).cross( unitY );
  80661. dirVector.copy( unitY ).cross( alignVector );
  80662. break;
  80663. case 'Z':
  80664. alignVector.copy( this.eye ).cross( unitZ );
  80665. dirVector.copy( unitZ ).cross( alignVector );
  80666. break;
  80667. case 'XY':
  80668. dirVector.copy( unitZ );
  80669. break;
  80670. case 'YZ':
  80671. dirVector.copy( unitX );
  80672. break;
  80673. case 'XZ':
  80674. alignVector.copy( unitZ );
  80675. dirVector.copy( unitY );
  80676. break;
  80677. case 'XYZ':
  80678. case 'E':
  80679. default: //xzw add for scale xyzz
  80680. dirVector.set( 0, 0, 0 );
  80681. break;
  80682. }
  80683. break;
  80684. case 'rotate':
  80685. default:
  80686. // special case for rotate
  80687. dirVector.set( 0, 0, 0 );
  80688. }
  80689. if ( dirVector.length() === 0 ) {
  80690. // If in rotate mode, make the plane parallel to camera
  80691. this.quaternion.copy( this.cameraQuaternion );
  80692. } else {
  80693. tempMatrix.lookAt( tempVector.set( 0, 0, 0 ), dirVector, alignVector );
  80694. this.quaternion.setFromRotationMatrix( tempMatrix );
  80695. }
  80696. Object3D.prototype.updateMatrixWorld.call( this );
  80697. };
  80698. };
  80699. TransformControls.prototype = Object.assign( Object.create( Object3D.prototype ), {
  80700. constructor: TransformControls,
  80701. isTransformControls: true
  80702. } );
  80703. TransformControlsGizmo.prototype = Object.assign( Object.create( Object3D.prototype ), {
  80704. constructor: TransformControlsGizmo,
  80705. isTransformControlsGizmo: true
  80706. } );
  80707. TransformControlsPlane.prototype = Object.assign( Object.create( Mesh.prototype ), {
  80708. constructor: TransformControlsPlane,
  80709. isTransformControlsPlane: true
  80710. } );
  80711. /*
  80712. 备注:
  80713. //这里虽然 使坐标轴在boundingBox中心
  80714. boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld);
  80715. 但是旋转中心并不是这个坐标轴显示的位置,需要再执行 MergeEditor.maintainBoundXY()才能维持在这个中心
  80716. */
  80717. const texLoader$a = new TextureLoader();
  80718. texLoader$a.crossOrigin = "anonymous";
  80719. const edgeStrengths = {
  80720. pointcloud: 4,
  80721. glb: 100
  80722. };
  80723. const viewportProps$1 = [{
  80724. left:0,
  80725. bottom:0,
  80726. width: 0.5,height:1,
  80727. name : 'top',
  80728. axis:["x","y"],
  80729. direction : new Vector3(0,0,-1), //镜头朝向
  80730. active: true,
  80731. //相机位置在z轴正向
  80732. limitBound: new Box3(new Vector3(-Infinity,-Infinity, 1),new Vector3(Infinity,Infinity,5000)), //在地面以上
  80733. margin:{x:50, y:150} ,
  80734. },
  80735. {
  80736. left:0.5,
  80737. bottom:0,
  80738. width: 0.5,height:1,
  80739. name : 'right',
  80740. axis:["y","z"],
  80741. direction : new Vector3(1,0,0),
  80742. active: true,
  80743. //相机位置在x轴负向 右下角屏
  80744. viewContainsPoints:[new Vector3(0,0,0)],
  80745. margin:{x:300, y:250} ,
  80746. } ];
  80747. let cylinderSkyGeo, oldSkyGeo;
  80748. let MergeEditor = {
  80749. bus:new EventDispatcher(),
  80750. SplitScreen : new SplitScreen(),
  80751. init(){
  80752. {
  80753. Potree.settings.notAdditiveBlending = true;
  80754. let ground = this.ground = new InfiniteGridHelper(1, 10000, new Color('#eee'), 10000, 0.2, 0.3);
  80755. viewer.scene.scene.add(ground);
  80756. //再加两条线否则在正侧边看不到
  80757. let line1 = LineDraw.createLine([new Vector3(-10000, 0, 0),new Vector3(10000, 0, 0) ], {color:'#aaa', });
  80758. let line2 = LineDraw.createLine([new Vector3(0, -10000, 0),new Vector3(0, 10000, 0) ], {mat:line1.material});
  80759. ground.renderOrder = Potree.config.renderOrders.model + 1;//line1.renderOrder + 1 //要比模型低,否则模型透明时效果不对
  80760. ground.add(line1);
  80761. ground.add(line2);
  80762. ground.material.opacity = 0.9; //为了滞后渲染,否则被rt遮住
  80763. ground.material.polygonOffset = true; //多边形偏移(视觉上没有移动模型位置),防止闪烁
  80764. ground.material.polygonOffsetFactor = 100; //多边形偏移因子
  80765. ground.material.polygonOffsetUnits = 10; //多边形偏移单位
  80766. ground.material.depthWrite = false;
  80767. //ground.material.depthTest = false
  80768. line1.material.polygonOffset = true;
  80769. line1.material.polygonOffsetFactor = 130;
  80770. line1.material.polygonOffsetUnits = 10;
  80771. line1.material.depthWrite = false;
  80772. //见笔记:透明物体的材质设置
  80773. }
  80774. let oriEdgeStrength = viewer.outlinePass.edgeStrength;
  80775. {
  80776. this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  80777. dontHideWhenFaceCamera: true,
  80778. });
  80779. //this.transformControls.space = 'local'//为了在当前方向上平移
  80780. this.transformControls.setSize(1.5);
  80781. viewer.scene.scene.add(this.transformControls);
  80782. this.transformControls._gizmo.hideAxis = {rotate:['e']};
  80783. this.transformControls.setRotateMethod(2);
  80784. //右屏
  80785. this.transformControls2 = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  80786. dontHideWhenFaceCamera: true,
  80787. });
  80788. this.transformControls.setSize(1.5);
  80789. viewer.scene.scene.add(this.transformControls2);
  80790. Potree.Utils.setObjectLayers(this.transformControls2, 'layer2' );
  80791. let mouseDown = (e)=>{
  80792. viewer.outlinePass.edgeStrength = 0;//暂时消失线
  80793. };
  80794. let mouseUp = (e)=>{
  80795. //this.updateEdgeStrength()
  80796. viewer.outlinePass.edgeStrength = oriEdgeStrength;
  80797. };
  80798. this.transformControls.addEventListener('mouseDown',mouseDown);
  80799. this.transformControls2.addEventListener('mouseDown',mouseDown);
  80800. this.transformControls.addEventListener('mouseUp',mouseUp);
  80801. this.transformControls2.addEventListener('mouseUp',mouseUp);
  80802. }
  80803. {
  80804. this.secondCompass = new Compass(null);
  80805. }
  80806. viewer.setControls(viewer.orbitControls);
  80807. //viewer.mainViewport.view.fixZWhenPan = true
  80808. viewer.orbitControls.constantlyForward = true;
  80809. viewer.addEventListener('global_single_click',(e)=>{
  80810. if(
  80811. this.noNeedSelection //如模型查看页
  80812. || viewer.scene.cameraAnimations.some(c=>c.onUpdate) //正在播放
  80813. || e.drag && e.drag.notPressMouse //在加测量线
  80814. || viewer.mainViewport.view.isFlying() //有其他校准
  80815. || this.split //分屏中
  80816. || e.clickElement //触发别的点击事件,如测量时click marker /* && e.clickElement != e.intersect.object */
  80817. ){
  80818. return
  80819. }
  80820. if(e.intersect){
  80821. let object = e.intersect.object || e.intersect.pointcloud;
  80822. let objects = this.getAllObjects();
  80823. if(objects.includes(object) && this.selected != object){
  80824. this.selectModel(object);
  80825. }else {
  80826. //if(!viewer.inputHandler.selection[0]){//正在平移和旋转,不允许取消
  80827. this.selectModel(null);
  80828. //}
  80829. }
  80830. }else {
  80831. //if(!viewer.inputHandler.selection[0]){
  80832. this.selectModel(null);
  80833. //}
  80834. }
  80835. });
  80836. viewer.inputHandler.addEventListener('keydown', (e)=>{
  80837. if((e.event.key).toLowerCase() == "h" ){
  80838. this.fadeOutlineAuto = !this.fadeOutlineAuto;
  80839. this.showModelOutline(this.selected,!!this.selected);
  80840. }
  80841. });
  80842. //viewer.fxaaPass.enabled = false//viewer.ssaaRenderPass.enabled = false
  80843. viewer.outlinePass.enabled = true;
  80844. //Potree.settings.intersectWhenHover = false
  80845. //Potree.Utils.updateVisible(viewer.reticule, 'force', false)
  80846. viewer.composer.scaleRatio = 1;
  80847. viewer.composer.readTarget = false;
  80848. viewer.mainViewport.camera.near = 0.05; // too small will result in z-fighting
  80849. viewer.addEventListener('updateModelBound', (e)=>{
  80850. if(this.split){
  80851. this.SplitScreen.updateCameraOutOfModel(/* this.selected && [this.selected] */);
  80852. }
  80853. });
  80854. {//校准页面拖拽
  80855. //左右屏都可以拖拽模型,旋转只能左屏
  80856. let dragInfo;
  80857. let drag = (e)=>{
  80858. if(this.split && this.selected && this.transformState && (e.dragViewport.name == 'top' || this.transformState == 'translate') ){
  80859. if(e.type == 'global_mousedown' ){ //开始
  80860. //if((e.intersect.object || e.intersect.pointcloud) == this.selected){
  80861. if(e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e=>e.object == this.selected)){
  80862. dragInfo = {};
  80863. //if(this.selected.isPointcloud){
  80864. viewer.outlinePass.edgeStrength = 0;//暂时消失线
  80865. //}
  80866. }
  80867. }
  80868. if(e.type == 'global_drag' && dragInfo ){
  80869. if(this.transformState == 'translate'){
  80870. let moveVec = Potree.Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, e.dragViewport.camera );//最近一次移动向量
  80871. this.selected.position.add(moveVec);
  80872. this.selected.dispatchEvent("position_changed");
  80873. }else if(this.transformState == 'rotate'){
  80874. let vec = new Vector3().subVectors(e.intersect.orthoIntersect || e.intersect.location, this.selected.boundCenter).setZ(0);
  80875. if(dragInfo.lastVec == void 0){//global_mousedown
  80876. dragInfo.lastVec = vec;
  80877. return
  80878. }
  80879. let angle = math.getAngle(dragInfo.lastVec, vec, 'z');
  80880. dragInfo.lastVec = vec;
  80881. //this.selected.rotation.z += angle //局部
  80882. /* object.quaternion.copy( .setFromAxisAngle( new THREE.Vector3(0,0,1), angle ) );
  80883. object.quaternion.multiply( quaternionStart ).normalize(); */
  80884. let diffQua = new Quaternion().setFromAxisAngle( new Vector3(0,0,1), angle );
  80885. this.selected.quaternion.premultiply(diffQua); //世界
  80886. this.selected.dispatchEvent("rotation_changed");
  80887. }
  80888. return {stopContinue:true}
  80889. }
  80890. }
  80891. };
  80892. viewer.addEventListener('global_mousedown', drag);
  80893. viewer.addEventListener('global_drag', drag, {importance:10});
  80894. viewer.addEventListener('global_mousemove', (e)=>{
  80895. if(this.split && this.transformState && !e.drag && (e.hoverViewport.name == 'top' || this.transformState == 'translate')){
  80896. /* if(this.lastHoverViewport != e.hoverViewport){
  80897. this.lastHoverViewport = e.hoverViewport
  80898. this.transformControls.view = e.hoverViewport.view
  80899. this.transformControls.camera = e.hoverViewport.camera
  80900. this.transformControls.hideAxis( this.transformState, e.hoverViewport.name == 'top' ? [z] : [x,y]);
  80901. } */
  80902. let mouseover = e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e=>e.object == this.selected);
  80903. //let mouseover = (e.intersect.object || e.intersect.pointcloud) == this.selected
  80904. if(mouseover){
  80905. if(this.transformState == 'translate'){
  80906. viewer.dispatchEvent({
  80907. type : "CursorChange", action : "add", name:"movePointcloud"
  80908. });
  80909. }else {
  80910. viewer.dispatchEvent({
  80911. type : "CursorChange", action : "add", name:"rotatePointcloud"
  80912. });
  80913. }
  80914. }else {
  80915. this.clearTranCursor();
  80916. }
  80917. }
  80918. });
  80919. viewer.addEventListener('global_drop', (e)=>{
  80920. dragInfo = null;
  80921. this.clearTranCursor();
  80922. //this.updateEdgeStrength()
  80923. viewer.outlinePass.edgeStrength = oriEdgeStrength;
  80924. });
  80925. }
  80926. /* viewer.addEventListener('background_changed',()=>{
  80927. }) */
  80928. viewer.addEventListener('camera_changed',()=>{
  80929. Common$1.intervalTool.isWaiting('updateMemoryUsage', ()=>{
  80930. this.updateMemoryUsage();
  80931. }, 1000);
  80932. });
  80933. viewer.addEventListener('setDisplay',this.updateMemoryUsage.bind(this));
  80934. },
  80935. clearTranCursor(){
  80936. viewer.dispatchEvent({
  80937. type : "CursorChange", action : "remove", name:"movePointcloud"
  80938. });
  80939. viewer.dispatchEvent({
  80940. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  80941. });
  80942. },
  80943. enterSplit(){
  80944. this.split = true;
  80945. if(this.selected) this.SplitScreen.focusCenter = this.selected.boundCenter; //旋转中心。注意 boundCenter不能直接赋值,否则改变后focusCenter也要改
  80946. else this.SplitScreen.focusCenter = null;
  80947. this.SplitScreen.splitStart(viewportProps$1);
  80948. this.beforeSplit = {
  80949. pointDensity: Potree.settings.pointDensity,
  80950. };
  80951. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  80952. viewer.setControls(viewer.fpControls);
  80953. let rightViewport = viewer.viewports.find(e=>e.name == 'right');
  80954. let topViewport = viewer.viewports.find(e=>e.name == 'top');
  80955. topViewport.alignment = true;
  80956. rightViewport.rotateSide = true;
  80957. rightViewport.skyboxFixPos = true;
  80958. rightViewport.skyboxMinZoom = 10;
  80959. rightViewport.skyboxRenderFun = ()=>{// 使cube的一面永远正向镜头。 因侧视图的camera是ortho类型,需要平视mesh才不会拉伸
  80960. viewer.skybox.scene.children[0].rotation.copy(rightViewport.camera.rotation);
  80961. };
  80962. topViewport.skyboxRenderFun = ()=>{
  80963. viewer.skybox.scene.children[0].rotation.set(0,0,0);
  80964. };
  80965. viewer.viewports[1].layersAdd('layer2');
  80966. viewer.viewports[0].layersAdd('layer1');
  80967. Potree.Utils.setObjectLayers(this.transformControls, 'layer1' );
  80968. this.transformControls.view = viewer.viewports[0].view;
  80969. this.transformControls.camera = viewer.viewports[0].camera;
  80970. this.transformControls._gizmo.hideAxis = {translate:['z'], rotate:['x','y','z'] };
  80971. this.transformControls2.view = viewer.viewports[1].view;
  80972. this.transformControls2.camera = viewer.viewports[1].camera;
  80973. this.transformControls2._gizmo.hideAxis = {translate:['x','y'], rotate:['x','y','z'] };
  80974. this.secondCompass.changeViewport(viewer.viewports[0]);
  80975. this.secondCompass.setDomPos();
  80976. this.secondCompass.setDisplay(true);
  80977. viewer.compass.changeViewport(viewer.viewports[1]);
  80978. viewer.compass.setDomPos();
  80979. //this.changeSkyboxGeo(true)
  80980. },
  80981. leaveSplit(){
  80982. this.split = false;
  80983. this.SplitScreen.unSplit();
  80984. viewer.setControls(viewer.orbitControls);
  80985. Potree.settings.pointDensity = this.beforeSplit.pointDensity;
  80986. /* if(this.selected && this.selected.isPointcloud){
  80987. this.showModelOutline(this.selected, true)
  80988. this.selected.material.activeAttributeName = "rgba"
  80989. } */
  80990. this.transformControls.camera = viewer.viewports[0].camera;
  80991. this.transformControls.view = viewer.viewports[0].view;
  80992. this.transformControls._gizmo.hideAxis = {rotate:['e']};
  80993. Potree.Utils.setObjectLayers(this.transformControls, 'sceneObjects' ); //恢复
  80994. viewer.compass.changeViewport(viewer.viewports[0]); //恢复
  80995. viewer.compass.setDomPos();
  80996. this.secondCompass.setDisplay(false);
  80997. },
  80998. rotateSideCamera(angle){
  80999. this.SplitScreen.rotateSideCamera(viewer.viewports.find(e=>e.name == 'right'), angle);
  81000. },
  81001. setTransformState(state){//校准时
  81002. this.transformState = state;
  81003. this.clearTranCursor();
  81004. },
  81005. //---------------------------
  81006. /* writeToHistory(content){
  81007. if(!this.prepareRecord)return;
  81008. this.prepareRecord = false
  81009. this.history.push(content)
  81010. }, */
  81011. //---------------------------
  81012. getAllObjects(){
  81013. return viewer.objs.children.concat(viewer.scene.pointclouds)
  81014. },
  81015. getModel(id){
  81016. let models = this.getAllObjects();
  81017. return models.find(e=>e.dataset_id == id)
  81018. },
  81019. removeModel(model){
  81020. if(this.selected == model) this.selectModel(null);
  81021. let dispose = (e)=>{
  81022. e.geometry && e.geometry.dispose();
  81023. e.material && e.material.dispose();
  81024. };
  81025. if(model.isPointcloud){
  81026. dispose(model);
  81027. viewer.scene.removePointCloud(model);
  81028. }else {
  81029. model.traverse(e=>{
  81030. dispose(e);
  81031. });
  81032. viewer.objs.remove(model);
  81033. this.updateMemoryUsage();
  81034. }
  81035. },
  81036. selectModel(model, state=true, fitBound, by2d){
  81037. if(!model) {
  81038. model = this.selected;
  81039. state = false;
  81040. }
  81041. if(state){
  81042. if(this.selected){
  81043. if(this.selected == model) return
  81044. else {
  81045. let transToolAttached = !!this.transformControls.object;
  81046. this.selectModel(this.selected, false, fitBound, by2d);
  81047. transToolAttached && this.transformControls.attach(model);
  81048. }
  81049. }
  81050. this.selected = model;
  81051. MergeEditor.focusOn(model, 500, !!fitBound); //通过在场景里点击模型的话,不focus
  81052. this.showModelOutline(model);
  81053. //this.updateEdgeStrength()
  81054. //console.log('selectModel', model)
  81055. }else {
  81056. if(this.selected != model)return //model本来就没选中,不需要处理(防止2d先选中新的再取消旧的)
  81057. this.showModelOutline(model, false);
  81058. this.selected = null;
  81059. this.transformControls.detach(); //viewer.transformObject(null);
  81060. //console.log('selectModel', null)
  81061. }
  81062. if(!by2d && model){
  81063. model.dispatchEvent({type:'changeSelect', selected : state});
  81064. }
  81065. },
  81066. showModelOutline(model, state){
  81067. if(this.fadeOutlineAuto){
  81068. if(state === false){
  81069. viewer.outlinePass.selectedObjects = [];
  81070. clearTimeout(this.timer);
  81071. return
  81072. }
  81073. viewer.outlinePass.selectedObjects = [model];
  81074. if(this.timer){
  81075. clearTimeout(this.timer);
  81076. }
  81077. this.timer = setTimeout(()=>{
  81078. viewer.outlinePass.selectedObjects = [];
  81079. viewer.dispatchEvent('content_changed');
  81080. }, 1000);
  81081. }else {
  81082. if(state === false){
  81083. viewer.outlinePass.selectedObjects = [];
  81084. }else {
  81085. viewer.outlinePass.selectedObjects = [model];
  81086. }
  81087. }
  81088. viewer.dispatchEvent('content_changed');
  81089. },
  81090. /*updateEdgeStrength(){
  81091. if(!this.selected)return
  81092. if(this.selected.isPointcloud){
  81093. viewer.outlinePass.edgeStrength = edgeStrengths.pointcloud// / this.selected.material.opacity
  81094. }else{
  81095. viewer.outlinePass.edgeStrength = edgeStrengths.glb
  81096. }
  81097. },*/
  81098. focusOn(objects, duration = 400, fitBound=true, dontLookUp){
  81099. if(!(objects instanceof Array)){
  81100. objects = [objects];
  81101. }
  81102. let boundingBox = new Box3;
  81103. objects.forEach(object=>{
  81104. boundingBox.union(object.boundingBox.clone().applyMatrix4(object.matrixWorld));
  81105. });
  81106. if(fitBound){
  81107. viewer.focusOnObject({boundingBox}, 'boundingBox', duration, {dontLookUp, dontChangeCamDir:true});
  81108. }else {
  81109. /*
  81110. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new THREE.Vector3)
  81111. position && viewer.focusOnObject({position}, 'point', duration, {dontChangePos: true})
  81112. */
  81113. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new Vector3);
  81114. if(!position)return
  81115. /* let targetOld = viewer.mainViewport.view.getPivot()
  81116. let projected1 = targetOld.clone().project(viewer.mainViewport.camera);
  81117. let projected2 = position.clone().project(viewer.mainViewport.camera); //使用其z
  81118. let targetNew = projected1.clone().setZ(projected2.z).unproject(viewer.mainViewport.camera);
  81119. viewer.mainViewport.view.lookAt(targetNew) */
  81120. viewer.mainViewport.view.radius = viewer.mainViewport.camera.position.distanceTo(position);
  81121. //为了不改画面,不调节方向了,只能调调radius,一定程度将target靠近model
  81122. }
  81123. },
  81124. moveBoundCenterTo(model,pos){ //使boundCenter在所要的位置
  81125. let diff = new Vector3().subVectors(pos, model.boundCenter);
  81126. model.position.add(diff);
  81127. },
  81128. getBoundCenter(model){
  81129. if(!model.boundCenter) model.boundCenter = new Vector3;
  81130. model.boundingBox.getCenter(model.boundCenter).applyMatrix4(model.matrixWorld);
  81131. },
  81132. setModelBtmHeight(model, z ){
  81133. //无论模型怎么缩放、旋转,都使最低点为z
  81134. if(z == void 0) z = model.btmHeight; //维持离地高度
  81135. else model.btmHeight = z;
  81136. model.updateMatrixWorld();
  81137. let boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  81138. let size = boundingBox2.getSize(new Vector3);
  81139. let center = boundingBox2.getCenter(new Vector3);
  81140. let hopeZ = z + size.z / 2;
  81141. //model.position.z = z + size.z / 2 - center.z
  81142. model.position.z += (hopeZ - center.z);
  81143. },
  81144. computeBtmHeight(model){ //位移之后重新计算btmHeight
  81145. model.updateMatrixWorld();
  81146. let boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  81147. let size = boundingBox2.getSize(new Vector3);
  81148. let center = boundingBox2.getCenter(new Vector3);
  81149. model.btmHeight = center.z - size.z / 2;
  81150. },
  81151. maintainBoundXY(model){ //在旋转和缩放后,立即执行这个函数,使boundCenter保持原位
  81152. model.updateMatrixWorld();
  81153. let center1 = model.boundCenter.clone();//还未更新的
  81154. this.getBoundCenter(model);//更新
  81155. let center2 = model.boundCenter.clone();
  81156. let diff = new Vector2().subVectors(center1,center2);
  81157. model.position.x += diff.x;
  81158. model.position.y += diff.y;
  81159. model.boundCenter.copy(center1);
  81160. },
  81161. maintainBoundCenter(model){
  81162. model.updateMatrixWorld();
  81163. let center1 = model.boundCenter.clone();//还未更新的
  81164. this.getBoundCenter(model);//更新
  81165. let center2 = model.boundCenter.clone();
  81166. let diff = new Vector3().subVectors(center1,center2);
  81167. model.position.add(diff);
  81168. model.boundCenter.copy(center1);
  81169. },
  81170. modelTransformCallback(model){
  81171. model.updateMatrixWorld();
  81172. if(model.matrixWorld.equals(model.lastMatrixWorld))return
  81173. viewer.scene.measurements.forEach(measure=>{
  81174. let changed;
  81175. measure.points_datasets.forEach((dataset_id,i)=>{
  81176. if(dataset_id == model.dataset_id){
  81177. changed = true;
  81178. measure.points[i] = Potree.Utils.datasetPosTransform({fromDataset:true,datasetId:dataset_id, position:measure.dataset_points[i].clone()});
  81179. measure.updateMarker(measure.markers[i], measure.points[i]);
  81180. }
  81181. });
  81182. if(changed){//仿transformByPointcloud
  81183. measure.getPoint2dInfo(measure.points);
  81184. measure.update();
  81185. measure.setSelected(false);//隐藏edgelabel
  81186. }
  81187. });
  81188. model.lastMatrixWorld = model.matrixWorld.clone();
  81189. viewer.dispatchEvent('content_changed');
  81190. },
  81191. changeOpacity(model, opacity){
  81192. let isRoot = model.dataset_id != void 0; //是否是最外层
  81193. if(model.isPointcloud){
  81194. model.changePointOpacity(opacity);
  81195. //MergeEditor.updateEdgeStrength()
  81196. }else {
  81197. //model.traverse(e=>e.material && setOp(e, opacity))
  81198. model.traverse(mesh=>{
  81199. if(mesh.material){
  81200. if(mesh.material.originOpacity == void 0 ){
  81201. mesh.material.originOpacity = mesh.material.opacity;
  81202. }
  81203. mesh.material.opacity = mesh.material.originOpacity * opacity;
  81204. if(mesh.material.opacity<1){
  81205. mesh.material.transparent = true;
  81206. /* if(model.isPointcloud){
  81207. mesh.changePointOpacity(realOpacity)
  81208. }else{
  81209. mesh.material.opacity = realOpacity
  81210. } */
  81211. mesh.renderOrder = Potree.config.renderOrders.model+1;
  81212. //mesh.material.depthWrite = false
  81213. }else {
  81214. mesh.material.transparent = false;
  81215. mesh.renderOrder = Potree.config.renderOrders.model;
  81216. //mesh.material.depthWrite = true
  81217. }
  81218. mesh.material.depthWrite = mesh.material.opacity>0.3;
  81219. }
  81220. });
  81221. }
  81222. isRoot && (model.opacity = opacity);//记录在最外层
  81223. viewer.dispatchEvent('content_changed');
  81224. },
  81225. modelAdded(model){
  81226. model.addEventListener('isVisible',(e)=>{
  81227. if(e.reason == "overlinePass")return
  81228. //console.log(e)
  81229. viewer.addEventListener('update',()=>{ //下一次更新结束后
  81230. this.updateMemoryUsage();
  81231. },{once:true});
  81232. });
  81233. this.updateMemoryUsage();
  81234. },
  81235. updateMemoryUsage(){
  81236. //obj暂时不管其贴图大小, 因为顶点造成的不仅是内存还有卡顿所以先只看顶点
  81237. const maxMemory = Potree.config.tiles3DMaxMemory + 100; //M 实际估计是这个的10倍
  81238. const eachObjPosWeight = 100/1000/1000; //M 每个顶点pos是3*4个字节?法线3*4和uv2*4 其实还有贴图
  81239. const eachCloudPointWeight = 12/1000/1000; //M 每个点 pos + 颜色 + 法线 大概
  81240. const eachVisiCPointWeight = eachCloudPointWeight * 5; // 或 maxMemory / (6*1000*1000) 大概值接近 (再除以一个数是因为显示的要比内存中的耗更多资源
  81241. const eachGltfPosWeight = 100/1000/1000; //M 每个顶点pos是3*4个字节?法线3*4和uv2*4 其实还有贴图
  81242. let posCount=0;
  81243. viewer.objs.children.forEach(e=>{
  81244. if(e.fileType == 'glb' || e.fileType == 'obj'){
  81245. e.traverse((mesh)=>{
  81246. if(mesh.geometry){
  81247. posCount += mesh.geometry.attributes.position.count;
  81248. }
  81249. });
  81250. }else if(e.fileType == '3dTiles'){
  81251. }
  81252. });
  81253. //获取点云的内存限制
  81254. let objWeight = posCount*eachObjPosWeight;
  81255. let laserWeight = Potree.numVisiblePoints * eachCloudPointWeight; //点云实际显示所占大小
  81256. let laserMemoryWeight = Potree.lru.numPoints * eachCloudPointWeight; //点云所使用内存大小
  81257. let tiles3DWeight = viewer.tiles3dVisiVCount * eachGltfPosWeight; //M 3dTiles所占内存大小
  81258. let tiles3DMemoryWeight = viewer.tiles3dMemoryUsage / 1000 / 1000; //M 3dTiles显示的所占内存大小
  81259. /* let min = 0.1, max = 6, minP = 100, maxP = 1000000;
  81260. let ratio = Math.round(math.linearClamp(score, minP, maxP, max, min )); */
  81261. let rest = maxMemory - objWeight - tiles3DWeight;
  81262. Potree.pointBudget = Math.max(30000, Math.round(rest/eachVisiCPointWeight));
  81263. //获取3dTiles的内存限制
  81264. let tiles3DMaxMemory = maxMemory - Math.round(objWeight + laserWeight);
  81265. Potree.settings.tiles3DMaxMemory = MathUtils.clamp(tiles3DMaxMemory , 30, Potree.config.tiles3DMaxMemory );
  81266. //还存在的问题:仍然有隐患,因为没用到真实缓存的大小: tiles3DMemoryWeight laserMemoryWeight, 它们比真实可见的要多。不使用是因为它们无法反应出实际需要的内存量,缓存是只增不减
  81267. //obj等普通mesh限制不了
  81268. //console.log('objWeight',objWeight.toFixed(1), 'laserMemoryWeight',laserMemoryWeight.toFixed(1), 'tiles3DWeight',tiles3DWeight.toFixed(1), 'pointBudget',Potree.pointBudget, 'tiles3DMaxMemory',tiles3DMaxMemory)
  81269. //总内存 = 内存占用空间+图片缓存 , obj的缓存比较多在图片中
  81270. },
  81271. };
  81272. /*
  81273. note:
  81274. 要注意getHoveredElements只在getIntersect时才使interactables包含加载的model, 也就是model上不能有使之成为interactables的事件,否则在鼠标hover到模型上开始转动的一瞬间很卡。
  81275. */
  81276. const texLoader$b = new TextureLoader();
  81277. const arrowSpacing = 1; //间隔
  81278. const arrowSize = arrowSpacing * 0.5;
  81279. const planeGeo$3 = new PlaneBufferGeometry(1,1);
  81280. const sphereSizeInfo = {
  81281. nearBound : 0.1, farBound:25, minSize : 50, maxSize : 200 //scale:arrowSize, restricMeshScale : true,
  81282. };
  81283. //const arrowsShowingCount = 25; //场景里最多展示多少个箭头
  81284. const arrowShowMinDis = 10;
  81285. class RouteGuider extends EventDispatcher{
  81286. constructor () {
  81287. super();
  81288. this.route = [];
  81289. this.curve = [];
  81290. this.scenePoints = [];
  81291. this.sceneMeshGroup = new Object3D;
  81292. this.mapMeshGroup = new Object3D;
  81293. this.generateDeferred;
  81294. viewer.addEventListener('loadPointCloudDone',this.init.bind(this));
  81295. this.lastResult;//保存上一个的结果,以便于反向
  81296. this.datasetIds = [];//起始和终点的datasetId
  81297. }
  81298. init(){
  81299. if(this.inited) return;
  81300. let zoom, resolution=new Vector2;
  81301. viewer.mapViewer.addEventListener('camera_changed', e => {
  81302. if(!this.routeStart || !this.routeEnd) return
  81303. var camera = e.viewport.camera;
  81304. if(camera.zoom != zoom || !resolution.equals(e.viewport.resolution)){
  81305. Common$1.intervalTool.isWaiting('routeCameraInterval', ()=>{ //延时update,防止卡顿
  81306. if(camera.zoom != zoom || !resolution.equals(e.viewport.resolution)){
  81307. //console.log('updateMapArrows')
  81308. this.updateMapArrows(true);
  81309. zoom = camera.zoom; resolution.copy(e.viewport.resolution);
  81310. }
  81311. }, browser.isMobile()?500:200);
  81312. }
  81313. });
  81314. viewer.addEventListener('camera_changed', e => {
  81315. if(!this.routeStart || !this.routeEnd || !e.changeInfo.positionChanged ) return
  81316. Common$1.intervalTool.isWaiting('routeCameraInterval2', ()=>{ //延时update,防止卡顿
  81317. this.updateArrowDisplay();
  81318. }, 1000);
  81319. });
  81320. var polesMats = {
  81321. shadowMat: new MeshBasicMaterial({
  81322. transparent:true, depthTest:false,
  81323. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_bottomMarker.png' )
  81324. }),
  81325. sphereMat : new MeshBasicMaterial({
  81326. transparent:true, depthTest:false,
  81327. map: texLoader$b.load(Potree.resourcePath+'/textures/whiteCircle.png' )
  81328. }),
  81329. hatMats:{
  81330. start: new MeshBasicMaterial({
  81331. transparent:true, depthTest:false,
  81332. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_start_route.png' )
  81333. }),
  81334. end: new MeshBasicMaterial({
  81335. transparent:true, depthTest:false,
  81336. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_target_reached.png' )
  81337. })
  81338. }
  81339. };
  81340. polesMats.shadowMat.map.anisotropy = 4;
  81341. this.poleStart = this.createPole(polesMats, 'start');
  81342. this.poleEnd = this.createPole(polesMats, 'end');
  81343. this.sceneMeshGroup.add(this.poleStart);
  81344. this.sceneMeshGroup.add(this.poleEnd);
  81345. let map = texLoader$b.load(Potree.resourcePath+'/textures/routePoint_panorama.png' );
  81346. map.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  81347. this.arrow = new Mesh(planeGeo$3, new MeshBasicMaterial({
  81348. transparent:true,
  81349. depthTest:false,
  81350. map
  81351. }));
  81352. this.arrow.scale.set(arrowSize,arrowSize,arrowSize);
  81353. Potree.Utils.setObjectLayers(this.arrow, 'sceneObjects' );
  81354. /* this.testArrow = this.arrow.clone();
  81355. this.testArrow.material = this.arrow.material.clone()
  81356. this.testArrow.material.color = 'red' */
  81357. this.arrows = new Object3D;
  81358. this.sceneMeshGroup.add(this.arrows);
  81359. Potree.Utils.setObjectLayers(this.sceneMeshGroup, 'sceneObjects' );
  81360. //this.sceneMeshGroup.traverse(e=>e.renderOrder = 90)
  81361. viewer.scene.scene.add(this.sceneMeshGroup);
  81362. this.sceneMeshGroup.visible = false;
  81363. this.poleStart.visible = false;
  81364. this.poleEnd.visible = false;
  81365. //-------------map---------------------
  81366. /* this.mapMarkStart = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  81367. transparent:true, depthTest:false,
  81368. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_start_route.png' )
  81369. }))
  81370. this.mapMarkEnd = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  81371. transparent:true, depthTest:false,
  81372. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_target_reached.png' )
  81373. }))
  81374. this.mapMarkStart.renderOrder = this.mapMarkEnd.renderOrder = 2//在箭头之上 */
  81375. let map2 = texLoader$b.load(Potree.resourcePath+'/textures/routePoint_map_fsna.png' );
  81376. this.mapArrowMats = {
  81377. default: new MeshBasicMaterial({
  81378. transparent:true, depthTest:false,
  81379. map:map2,
  81380. }),
  81381. fade: new MeshBasicMaterial({
  81382. transparent:true, depthTest:false,
  81383. map:map2,
  81384. opacity:0.4
  81385. }),
  81386. };
  81387. this.mapArrow = new Mesh( planeGeo$3, this.mapArrowMats.default);
  81388. this.mapArrow.scale.set(arrowSize,arrowSize,arrowSize);
  81389. this.mapArrows = new Object3D;
  81390. this.mapArrows.name = 'mapArrows';
  81391. this.mapMeshGroup.add(this.mapArrows);
  81392. this.mapMeshGroup.name = 'mapRouteLayer';
  81393. this.mapMeshGroup.visible = false;
  81394. viewer.mapViewer.dispatchEvent({type:'add', object:this.mapMeshGroup, name:'route'});
  81395. this.mapArrow.layers.mask = this.mapArrows.layers.mask; // 修改成和map中的layer一样的
  81396. viewer.modules.SiteModel.bus.addEventListener('FloorChange',()=>{
  81397. if(this.routeStart && this.routeEnd){
  81398. this.updateOpacityAtMap();
  81399. }
  81400. });
  81401. this.inited = true;
  81402. }
  81403. updateOpacityAtMap(){//只有当前楼层的透明度为1
  81404. var currentFloor = viewer.modules.SiteModel.currentFloor;
  81405. //console.log('updateOpacityAtMap', currentFloor && currentFloor.name)
  81406. const lift = 0.3; // 因为发送请求时用的是floorPosition的高度,而它可能会到画好的floor之下,所以有误差
  81407. this.mapArrows.children.forEach((arrow,index)=>{
  81408. let pos = this.mapPoints[index].clone();
  81409. pos.z += lift;
  81410. let inSide = currentFloor && currentFloor.ifContainsPoint(pos);
  81411. arrow.material = inSide ? this.mapArrowMats.default : this.mapArrowMats.fade;
  81412. //console.log('arrow',index, arrow.material.opacity)
  81413. });
  81414. viewer.mapViewer.dispatchEvent('content_changed');
  81415. }//但是如果楼层刚好只框柱相机位置而没框住地面位置就不好了……
  81416. createPole(polesMats, name){
  81417. const height = 1.5, sphereCount = 6, shadowSize = 0.5 /* sphereSizeInfo.scale */, sphereSize = 0.05;
  81418. var group = new Object3D;
  81419. group.name = 'pole_'+name;
  81420. var shadow = new Mesh(planeGeo$3, polesMats.shadowMat);
  81421. shadow.scale.set(shadowSize,shadowSize,shadowSize);
  81422. var sliceDis = height / (sphereCount+1);
  81423. group.add(shadow);
  81424. for(let i=0;i<sphereCount;i++){
  81425. var sphere = new Sprite$2({mat: polesMats.sphereMat, renderOrder:3});
  81426. sphere.position.set(0,0,sliceDis*(i+1));
  81427. sphere.scale.set(sphereSize,sphereSize,sphereSize);
  81428. //sphere.visible = false
  81429. group.add(sphere);
  81430. }
  81431. var hatSphere = new Sprite$2({mat: polesMats.hatMats[name], sizeInfo:sphereSizeInfo, renderOrder:4});
  81432. //sphere.visible = false
  81433. hatSphere.position.set(0,0,height);
  81434. hatSphere.scale.copy(shadow.scale);
  81435. group.add(hatSphere);
  81436. return group
  81437. }
  81438. addTestArrow(){
  81439. }
  81440. addArrow(position){
  81441. var arrow = this.arrow.clone();
  81442. arrow.position.copy(position);
  81443. this.arrows.add(arrow);
  81444. }
  81445. addMapArrow(position){
  81446. var mapArrow = this.mapArrow.clone();
  81447. mapArrow.position.copy(position).setZ(0);
  81448. this.mapArrows.add(mapArrow);
  81449. }
  81450. setArrowDir(arrows,index){
  81451. let arrow = arrows[index];
  81452. var nextOne = arrows[index+1];
  81453. var nextPos = nextOne ? nextOne.position : this.endPolePos; //routeEnd
  81454. var direction = new Vector3().subVectors(arrow.position, nextPos).setZ(0);
  81455. //direction.normalize();
  81456. //console.log(direction.toArray())
  81457. var angle = Math.atan2(direction.y, direction.x ) + Math.PI/2; //Math.PI/2是因为贴图本身箭头方向不朝x
  81458. arrow.rotation.z = angle;
  81459. //console.log(angle)
  81460. }
  81461. setRouteStart(pos, dealZ , datasetId ){
  81462. if(this.routeStart && pos && this.routeStart.equals(pos)) return //可能重复设置
  81463. this.routeStart = pos && new Vector3().copy(pos);
  81464. if(dealZ && this.routeStart){
  81465. this.routeStart.setZ(this.getZAtMap());
  81466. this.bus && this.bus.emit('reposStartMarker', this.routeStart);
  81467. }
  81468. console.log('setRouteStart',this.routeStart&&this.routeStart.toArray());
  81469. this.datasetIds[0] = datasetId;
  81470. //this.setStartPole(pos)
  81471. this.poleStart.visible = !!pos;
  81472. pos && this.poleStart.position.copy(this.routeStart);
  81473. this.generateRoute();
  81474. viewer.dispatchEvent('content_changed');
  81475. }
  81476. setStartPole(pos){
  81477. this.startPolePos = pos;
  81478. this.bus && this.bus.emit('reposStartMarker', pos);
  81479. }
  81480. setRouteEnd(pos, dealZ , datasetId ){
  81481. if(this.routeEnd && pos && this.routeEnd.equals(pos)) return
  81482. this.routeEnd = pos && new Vector3().copy(pos);
  81483. if(dealZ && this.routeEnd){
  81484. this.routeEnd.setZ(this.getZAtMap());
  81485. this.bus && this.bus.emit('reposEndMarker', this.routeEnd);
  81486. }
  81487. console.log('setRouteEnd',this.routeEnd&&this.routeEnd.toArray());
  81488. this.datasetIds[1] = datasetId;
  81489. //this.setEndPole(pos)
  81490. this.poleEnd.visible = !!pos;
  81491. pos && this.poleEnd.position.copy(this.routeEnd);
  81492. this.generateRoute();
  81493. viewer.dispatchEvent('content_changed');
  81494. }
  81495. getZAtMap(){
  81496. //找到position.z与当前高度最接近的漫游点
  81497. let result = Common$1.sortByScore(viewer.images360.panos,[],[e=> -(Math.abs(e.position.z - viewer.images360.position.z)) ]);
  81498. let pano = result && result[0] && result[0].item;
  81499. return pano ? pano.floorPosition.z : viewer.bound.boundingBox.min.z + 1
  81500. //若在平面图上画实在得不到当前楼层的,大概率是楼层画得不好,那就只能去获取当前楼层的了
  81501. //navvis的高度取的是主视图所在楼层的中心高度(可能再高些)
  81502. }
  81503. setEndPole(pos){
  81504. this.endPolePos = pos;
  81505. this.bus && this.bus.emit('reposEndMarker', pos);
  81506. }
  81507. getSourceProjectionIndex(route) {//真正的起始
  81508. var e = route.findIndex(function(t) {
  81509. return t.instruction && t.instruction.type === 'source_projection_to_navgraph'
  81510. });
  81511. return e < 0 ? 0 : e
  81512. }
  81513. getDestinationProjectionIndex(route) {//真正的终点
  81514. var e = route.findIndex(function(t) {
  81515. return t.instruction && t.instruction.type === "destination_projection_to_navgraph"
  81516. });
  81517. return e < 0 ? route.length - 1 : e
  81518. }
  81519. generateRoute(){
  81520. this.sceneMeshGroup.visible = true;
  81521. if(!this.routeStart || !this.routeEnd){
  81522. return
  81523. }
  81524. //array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  81525. let create = ()=>{
  81526. this.routeLength = this.route.reduce((total, currentValue, currentIndex, arr)=>{
  81527. if(currentIndex == 0)return 0
  81528. return total + currentValue.distanceTo(arr[currentIndex-1]);
  81529. },0);
  81530. let count = Math.max(2,Math.round(this.routeLength / arrowSpacing));//点数
  81531. const curve = new CatmullRomCurve3( this.route );
  81532. curve.curveType = 'chordal';//'centripetal' 'catmullrom'这个可能会超出路径外
  81533. this.curve = curve;
  81534. const scenePoints = curve.getSpacedPoints( count );//更平均
  81535. //const scenePoints = curve.getPoints( count );
  81536. scenePoints.splice(0,1);//去掉首尾
  81537. scenePoints.pop();
  81538. this.scenePoints = scenePoints;
  81539. this.updateMapArrows();
  81540. this.displayRoute();
  81541. {//map focus on this area
  81542. const minBound = new Vector2(1,1);//针对垂直线,在地图上只有一个点
  81543. let bound = new Box2;
  81544. this.route.forEach(e=>{
  81545. bound.expandByPoint(e);
  81546. });
  81547. let size = bound.getSize(new Vector2);
  81548. let markerSize = new Vector2(115,40); //起始和终点的标识呈长方形
  81549. let areaSize = viewer.mapViewer.viewports[0].resolution2;
  81550. let areaArea = areaSize.x * areaSize.y;
  81551. if(areaArea> 800 * 400){//是放大的
  81552. markerSize.multiplyScalar(areaArea / (800 * 400) /* / (size.x * size.y) */);
  81553. }
  81554. let margin = size.clone().divide(viewer.mapViewer.viewports[0].resolution2).multiply(markerSize); ///边距 重点是起始和终点的标识占据较大
  81555. size.add(margin);
  81556. let center = bound.getCenter(new Vector2);
  81557. size.x = Math.max(size.x, minBound.x );
  81558. size.y = Math.max(size.y, minBound.y );
  81559. let duration = 1000;
  81560. viewer.mapViewer.moveTo(center, size, duration);
  81561. }
  81562. this.bus.emit('gotResult', {dis:this.routeLength});
  81563. /* this.generateDeferred && this.generateDeferred.resolve({dis:this.routeLength})
  81564. this.generateDeferred = null */
  81565. };
  81566. if(Potree.fileServer){
  81567. let dealData = (data)=>{
  81568. if(!data.data){
  81569. console.log('没有数据');
  81570. let result;
  81571. if(data && data.code == 4002){
  81572. result = data;//正被修改数据集
  81573. }else if(this.routeStart.distanceTo(this.routeEnd) < 1){
  81574. result = { code: 500, msg: '距离太短,无法规划路线' };
  81575. }else {
  81576. result = { code: 500, msg: '超出数据集范围,无法规划路线' };
  81577. }
  81578. this.clearRoute();
  81579. this.setStartPole(this.routeStart);
  81580. this.setEndPole(this.routeEnd);
  81581. this.displayRoute(); //还是要显示一下起始
  81582. this.bus && this.bus.emit('gotResult', result );
  81583. return //this.generateDeferred && this.generateDeferred.resolve()
  81584. }
  81585. data = data.data;
  81586. this.clearRoute();
  81587. let length = data.length;
  81588. if(length < 2){//可能距离太短
  81589. console.log('路径点数为'+length+',直接取起点和终点连线');
  81590. this.route = [this.routeStart, this.routeEnd];
  81591. }else {
  81592. let startIndex = this.getSourceProjectionIndex(data);
  81593. let endIndex = this.getDestinationProjectionIndex(data);
  81594. let effectiveItems = data.slice(startIndex, endIndex + 1 );//只要点云范围内的点
  81595. effectiveItems.forEach((item,i)=>{
  81596. let pos = viewer.transform.lonlatToLocal.forward(item.location.slice(0));
  81597. pos = new Vector3().fromArray(pos);//.setZ(item.z)
  81598. this.route.push(pos);
  81599. });
  81600. console.log(this.route);
  81601. }
  81602. this.setStartPole(this.route[0]);
  81603. this.setEndPole(this.route[this.route.length-1]);
  81604. create();
  81605. /*
  81606. distance: 0.17581000000000116
  81607. distance_to_previous: 0.17581000000000116
  81608. id: 567
  81609. instruction: {type: 'source_projection_to_navgraph'}
  81610. latitude: 22.366605927999238
  81611. location: (3) [113.5957510575092, 22.366605927999238, -1.12419]
  81612. longitude: 113.5957510575092
  81613. z: -1.12419
  81614. */
  81615. };
  81616. if(this.lastResult && (this.lastResult.data || this.lastResult.data.code != 4002)){//正被修改数据集的话要重新计算
  81617. let data = Common$1.CloneObject(this.lastResult.data) , use; //直接用上次的结果
  81618. if(this.lastResult.routeStart.equals(this.routeStart) && this.lastResult.routeEnd.equals(this.routeEnd)){//和上次请求相同
  81619. use = true;
  81620. }else if(this.lastResult.routeStart.equals(this.routeEnd) && this.lastResult.routeEnd.equals(this.routeStart)){//..反向
  81621. use = true;
  81622. if(data.data){
  81623. data.data = this.lastResult.data.data.slice(0).reverse();
  81624. }
  81625. }
  81626. if(use){
  81627. console.log('直接用上次的结果');
  81628. return setTimeout(()=>{dealData(data);}, 1)//延迟是为了等待获得 RouteGuider.generateDeferred
  81629. }
  81630. }
  81631. let start = this.routeStart.clone();
  81632. let end = this.routeEnd.clone();
  81633. let startLonlat = viewer.transform.lonlatToLocal.inverse(start);
  81634. let endLonlat = viewer.transform.lonlatToLocal.inverse(end);
  81635. var query = {
  81636. source_longitude: startLonlat.x,
  81637. source_latitude: startLonlat.y,
  81638. source_z: start.z,
  81639. destination_longitude: endLonlat.x,
  81640. destination_latitude: endLonlat.y,
  81641. destination_z: end.z
  81642. };
  81643. //let url = `/laser/route/${Potree.settings.number}/getRoute/${this.datasetIds[0]}/${this.datasetIds[1]}?`
  81644. let url = `/laser/route/${Potree.settings.number}/getRoute/${Potree.settings.originDatasetId}?`;
  81645. for(let i in query){
  81646. url+= (i + '='+ query[i] +'&');
  81647. }
  81648. Potree.fileServer.get(url).then((data)=>{
  81649. console.log(data.data);
  81650. if(!this.routeStart || !this.routeEnd)return
  81651. this.lastResult = {//保存数据
  81652. routeStart : this.routeStart.clone(),
  81653. routeEnd: this.routeEnd.clone(),
  81654. data,
  81655. };
  81656. dealData(data);
  81657. });
  81658. }else {
  81659. //创个直线
  81660. /* const sliceDis = 1
  81661. let dis = this.routeStart.distanceTo(this.routeEnd);
  81662. let count = Math.max(2,Math.round(dis / sliceDis))//点数
  81663. let realSlideDis = dis / (count-1);
  81664. let dir = new THREE.Vector3().subVectors(this.routeEnd, this.routeStart).normalize().multiplyScalar(realSlideDis);
  81665. this.route = [this.routeStart];
  81666. for(let i=0;i<count-1;i++){
  81667. let lastOne = this.route[i];
  81668. this.route.push(new THREE.Vector3().addVectors(lastOne,dir))
  81669. }
  81670. this.route.splice(0,1) //route不用包含收尾 */
  81671. this.clearRoute();
  81672. this.route = [this.routeStart, this.routeEnd];
  81673. create();
  81674. }
  81675. }
  81676. updateMapArrows(ifReset){
  81677. if(this.route.length == 0)return
  81678. var zoom = viewer.mapViewer.camera.zoom;
  81679. let isBig = viewer.mapViewer.viewports[0].resolution.y > 300;
  81680. let count = Math.max(2,Math.round(this.routeLength * zoom / arrowSpacing / (isBig?35:30)));//点数
  81681. if(count == this.mapPoints.length+1)return//没变
  81682. const mapPoints = this.curve.getSpacedPoints( count );
  81683. mapPoints.splice(0,1);//去掉首尾
  81684. mapPoints.pop();
  81685. this.mapPoints = mapPoints;
  81686. var scale = (isBig ? 26 : 22)/zoom;
  81687. this.mapArrow.scale.set(scale,scale,scale);
  81688. /* this.mapMarkStart.scale.set(scale,scale,scale)
  81689. this.mapMarkEnd.scale.set(scale,scale,scale) */
  81690. if(ifReset){//因为缩放而重新排布箭头
  81691. this.clearRoute({resetMap:true});
  81692. this.displayRoute({resetMap:true});
  81693. }
  81694. this.updateOpacityAtMap();
  81695. }
  81696. updateArrowDisplay(){//根据当前位置更新显示一定范围内的箭头
  81697. if(this.scenePoints.length == 0)return
  81698. /* var a = Common.sortByScore(this.scenePoints , null, [(point)=>{ //是否还要再requires里限制最远距离?
  81699. var playerPos = viewer.scene.getActiveCamera().position.clone().setZ(0)
  81700. var pos = point.clone().setZ(0)
  81701. return -pos.distanceTo(playerPos);
  81702. }]);
  81703. //获得展示的起始点
  81704. let start = a[0].item
  81705. let startIndex = this.scenePoints.indexOf(start)
  81706. this.arrows.children.forEach((e,i)=>{
  81707. if(i<startIndex || i>startIndex+arrowsShowingCount)e.visible = false
  81708. else e.visible = true
  81709. }) */
  81710. let cameraPos = viewer.scene.getActiveCamera().position;
  81711. this.arrows.children.forEach((e,i)=>{
  81712. if(e.position.distanceTo(cameraPos) < arrowShowMinDis) e.visible = true;
  81713. else e.visible = false;
  81714. });
  81715. viewer.dispatchEvent('content_changed');
  81716. }
  81717. displayRoute(o={}){
  81718. if(!o.resetMap){
  81719. this.poleStart.position.copy(this.startPolePos || this.routeStart);
  81720. this.poleEnd.position.copy(this.endPolePos || this.routeEnd);
  81721. /* this.mapMarkStart.position.copy(this.routeStart).setZ(0)
  81722. this.mapMarkEnd.position.copy(this.routeEnd).setZ(0) */
  81723. this.scenePoints.forEach(e=>this.addArrow(e));
  81724. this.arrows.children.forEach((e,i)=>this.setArrowDir(this.arrows.children,i));
  81725. }
  81726. this.sceneMeshGroup.visible = true;//.traverse(e=>e.visible = true)
  81727. this.mapMeshGroup.visible = true;
  81728. this.mapPoints.forEach(e=>this.addMapArrow(e));
  81729. this.mapArrows.children.forEach((e,i)=>this.setArrowDir(this.mapArrows.children,i));
  81730. viewer.mapViewer.dispatchEvent({'type':'content_changed'});
  81731. this.updateArrowDisplay();
  81732. }
  81733. clearRoute(o={}){
  81734. if(!o.resetMap){
  81735. this.routeLength = 0;
  81736. this.route = [];
  81737. this.scenePoints = [];
  81738. this.mapPoints = [];
  81739. let arrows = this.arrows.children.slice(0);
  81740. arrows.forEach(e=>{
  81741. this.arrows.remove(e);
  81742. });
  81743. }
  81744. let mapArrows = this.mapArrows.children.slice(0);
  81745. mapArrows.forEach(e=>{
  81746. this.mapArrows.remove(e);
  81747. });
  81748. this.sceneMeshGroup.visible = false;
  81749. //this.sceneMeshGroup.traverse(e=>e.visible = false) //包括sprite也要设置,防止update
  81750. this.mapMeshGroup.visible = false;
  81751. viewer.mapViewer.dispatchEvent({'type':'content_changed'});
  81752. viewer.dispatchEvent('content_changed');
  81753. }
  81754. clear(){//退出
  81755. console.log('导航clear');
  81756. this.routeStart = null;
  81757. this.routeEnd = null;
  81758. this.clearRoute();
  81759. }
  81760. }
  81761. //大概每十米要花一秒
  81762. /*
  81763. 存在的问题:
  81764. 路径不准确。起始点和终点偏移。
  81765. https://uat-laser.4dkankan.com/routeDebug/ 可查整个map的通路点位图
  81766. */
  81767. //import History from "../../utils/History.js"
  81768. const cameraProps = [
  81769. {
  81770. name : 'top',
  81771. axis:["x","y"],
  81772. direction : new Vector3(0,0,-1), //镜头朝向
  81773. openCount:0,
  81774. }
  81775. ];
  81776. class Clipping extends EventDispatcher{ //实时剪裁
  81777. constructor(){
  81778. super();
  81779. this.views = {};
  81780. this.cameras = {};
  81781. this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  81782. this.orthoCamera.up.set(0,0,1);
  81783. }
  81784. init(){
  81785. if(this.inited)return
  81786. this.initViews();
  81787. this.inited = true;
  81788. this.prepareRecord = true;
  81789. this.activeViewName = 'mainView';
  81790. this.events = {
  81791. transfromCallback:(e)=>{//拖拽变化时
  81792. this.adjustCamHeight();
  81793. //检测漫游点、回退等
  81794. /* if(this.prepareRecord){
  81795. let box = viewer.transformationTool.selection[0]
  81796. this.history.writeIn({box, matrix:box.matrix.clone()})
  81797. this.prepareRecord = false
  81798. } */
  81799. },
  81800. /* onTransfromEnd:(e)=>{//拖拽结束、松开
  81801. this.prepareRecord = true
  81802. }, */
  81803. selectCallback:(e)=>{
  81804. this.adjustCamHeight();
  81805. let unableNavigate = this.activeViewName != 'mainView' || e.selection.length > 0;
  81806. if(Potree.settings.unableNavigate && !unableNavigate){
  81807. setTimeout(()=>{
  81808. Potree.settings.unableNavigate = this.activeViewName != 'mainView' || e.selection.length > 0;
  81809. },300);//延迟是因为点击时取消选择后可能立即就会触发flyToPano。 而且有的人喜欢点两下
  81810. }else Potree.settings.unableNavigate = unableNavigate;
  81811. },
  81812. onkeydown:(e)=>{
  81813. if(e.keyCode == 8 || e.keyCode == 46){// Backspace or Delete
  81814. viewer.inputHandler.selection[0] && viewer.scene.removeVolume(viewer.inputHandler.selection[0]);
  81815. }
  81816. }
  81817. };
  81818. /* this.history = new History({ //也可以写到全局,但需要加个判断物品是否存在的函数
  81819. applyData: (data)=>{
  81820. if(viewer.scene.volumes.includes(data.box)){
  81821. data.matrix.decompose( data.box.position, data.box.quaternion, data.box.scale );
  81822. }else{
  81823. this.history.undo()//找不到就回退下一个。(直接写这?)
  81824. }
  81825. }
  81826. }) */
  81827. }
  81828. initViews(){
  81829. this.splitScreenTool = new SplitScreen;
  81830. for(let i=0;i<1;i++){
  81831. let prop = cameraProps[i];
  81832. let view = new ExtendView();
  81833. this.views[prop.name] = view;
  81834. this.cameras[prop.name] = this.orthoCamera;
  81835. view.direction = prop.direction;
  81836. }
  81837. this.views.mainView = viewer.mainViewport.view;
  81838. this.cameras.mainView = viewer.mainViewport.camera;
  81839. }
  81840. switchView(name){//替换view和camera到mainViewport
  81841. if(this.activeViewName == name)return
  81842. let view = this.views[name];
  81843. let camera = this.cameras[name];
  81844. let prop = cameraProps.find(e=>e.name == name);
  81845. let {boundSize, center, boundingBox} = viewer.bound;
  81846. this.lastViewName = this.activeViewName;
  81847. this.activeViewName = name;
  81848. let lastView = this.views[this.lastViewName];
  81849. let lastCamera = this.cameras[this.lastViewName];
  81850. viewer.mainViewport.view = view;
  81851. viewer.mainViewport.camera = camera;
  81852. if(lastCamera)lastView.zoom = lastCamera.zoom;
  81853. /* if(lastView){//2d->3d
  81854. view.copy(lastView)
  81855. } */
  81856. if(name == 'mainView'){
  81857. Potree.settings.unableNavigate = false;
  81858. /* viewer.transformationTool.handles['scale.z+'].node.visible = true
  81859. viewer.transformationTool.handles['scale.z-'].node.visible = true */
  81860. }else {
  81861. Potree.settings.unableNavigate = true;
  81862. /* viewer.transformationTool.handles['scale.z+'].node.visible = false
  81863. viewer.transformationTool.handles['scale.z-'].node.visible = false */
  81864. if(prop.openCount == 0){//至多执行一次
  81865. //this.viewportFitBound(name, boundSize, center)
  81866. this.orthoMoveFit(center, {bound:boundingBox}, 0);
  81867. this.camHeightOutOfModel = view.position.z; //记录下此刻相机高度。
  81868. }
  81869. prop.openCount++;
  81870. this.adjustCamHeight();
  81871. /* this.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), center )
  81872. this.targetPlane.projectPoint(view.position, this.shiftTarget ) //target转换到过模型中心的平面,以保证镜头一定在模型外
  81873. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport)) */
  81874. if(view.zoom)camera.zoom = view.zoom;//恢复上次的zoom
  81875. }
  81876. viewer.updateScreenSize({forceUpdateSize:true});//更新camera aspect left等
  81877. if(viewer.inputHandler.selection.length){
  81878. this.focusOnObject(viewer.inputHandler.selection[0]);
  81879. }
  81880. }
  81881. focusOnObject(box, duration=0){
  81882. if(this.activeViewName == 'mainView'){
  81883. viewer.focusOnObject({boundingBox:box.boundingBox.clone().applyMatrix4(box.matrixWorld)}, 'boundingBox', duration);
  81884. }else {
  81885. this.orthoMoveFit(box.position, {bound:box.boundingBox.clone().applyMatrix4(box.matrixWorld)}, duration);
  81886. }
  81887. this.adjustCamHeight();
  81888. }
  81889. orthoMoveFit(pos, info, duration){
  81890. var margin = {x:viewer.mainViewport.resolution.x*0.4, y:viewer.mainViewport.resolution.y*0.4};
  81891. this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin );
  81892. }
  81893. adjustCamHeight(){
  81894. if(this.activeViewName != 'top')return
  81895. let view = this.views.top;
  81896. let height;
  81897. if(viewer.inputHandler.selection.length){ //相机高度位于选中的box的顶部
  81898. let box = viewer.inputHandler.selection[0];
  81899. height = box.boundingBox.clone().applyMatrix4(box.matrixWorld).max.z;
  81900. }else {
  81901. height = this.camHeightOutOfModel; //显示全部点云
  81902. }
  81903. view.position.z = height;
  81904. //console.log('adjustCamHeight',height)
  81905. //缺点:1 会导致缩放很小的时候,transformationTool的轴因放大到了相机背面。(只有scale轴做了处理)
  81906. //2 无法直接切换 看不到的box,但可以先取消选择
  81907. //3 但是俯视图中无法切换到被上层盖住的box(不过把俯视图作为辅助,只针对单个box调动的话,问题不大)
  81908. }
  81909. enter(){
  81910. this.init();
  81911. viewer.transformationTool.setModeEnable(['translation']);
  81912. //viewer.transformationTool.handles['rotation.x'].node.visible = false
  81913. viewer.transformationTool.frame.material.visible = false; //不盖住boxVolume的frame
  81914. this.targetPlane = viewer.mainViewport.targetPlane = new Plane();
  81915. this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  81916. this.getAllBoxes().forEach(box=>{
  81917. Potree.Utils.updateVisible(box,'hidden',true); //显现
  81918. });
  81919. viewer.transformationTool.history.clear();
  81920. viewer.transformationTool.addEventListener('transformed', this.events.transfromCallback);
  81921. //viewer.transformationTool.addEventListener('stopDrag', this.events.onTransfromEnd)
  81922. viewer.inputHandler.addEventListener('selection_changed', this.events.selectCallback);
  81923. viewer.inputHandler.addEventListener('keydown', this.events.onkeydown);
  81924. this.setPointLevelAuto();
  81925. var initialPointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == Potree.settings.originDatasetId);
  81926. //隐藏 初始数据集以外的数据集
  81927. viewer.scene.pointclouds.forEach(e=>{
  81928. if(e.dataset_id!=Potree.settings.originDatasetId){
  81929. Potree.Utils.updateVisible(e,'enterClipping',false);
  81930. //Potree.settings.floorplanEnables[e.dataset_id] = false
  81931. e.panos.forEach(pano=>pano.setEnable(false)); //禁止漫游
  81932. }else {
  81933. Potree.Utils.updateVisible(e,'enterClipping',true, 1, 'add');
  81934. //Potree.settings.floorplanEnables[e.dataset_id] = true
  81935. }
  81936. });
  81937. viewer.flyToDataset({ pointcloud : initialPointcloud, duration:0});
  81938. }
  81939. leave(){
  81940. viewer.transformationTool.setModeEnable(['scale', 'translation', 'rotation'] );
  81941. viewer.transformationTool.frame.material.visible = true; //恢复
  81942. this.switchView( 'mainView' );
  81943. this.getAllBoxes().forEach(box=>{
  81944. Potree.Utils.updateVisible(box,'hidden',false);//隐身
  81945. });
  81946. viewer.transformationTool.removeEventListener('transformed', this.events.transfromCallback);
  81947. //viewer.transformationTool.removeEventListener('stopDrag', this.events.onTransfromEnd)
  81948. viewer.inputHandler.removeEventListener('selection_changed', this.events.selectCallback);
  81949. //viewer.inputHandler.removeEventListener('keydown', this.events.onkeydown)
  81950. viewer.transformObject(null);
  81951. viewer.transformationTool.history.clear();
  81952. //恢复 初始数据集以外的数据集
  81953. viewer.scene.pointclouds.forEach(e=>{
  81954. if(e.dataset_id!=Potree.settings.originDatasetId){
  81955. Potree.Utils.updateVisible(e,'enterClipping',true);
  81956. e.panos.forEach(pano=>pano.setEnable(true));
  81957. }else {
  81958. Potree.Utils.updateVisible(e,'enterClipping',false, 0, 'cancel');
  81959. }
  81960. });
  81961. }
  81962. setTranMode(mode){//rotate or translate
  81963. this.tranMode = mode;
  81964. viewer.transformationTool.setModeEnable([mode]);
  81965. }
  81966. //问:是否要显示其他数据集
  81967. setPointLevelAuto(){
  81968. /*
  81969. let visiCount = viewer.images360.panos.length
  81970. let maxCount = 200, minCount = 20, minPer = 0.7, maxPer = 1
  81971. let percent = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount - minCount) / (maxCount - minCount),0,1)
  81972. Potree.settings.UserDensityPercent = percent ---还是不限制了,尤其是平面图希望更细致点,毕竟剪裁主要要看清剪裁的部位。
  81973. */
  81974. viewer.setPointBudget(5*1000*1000); //给个中等到高等之间的质量
  81975. Potree.settings.sizeFitToLevel = true;
  81976. viewer.setPointLevels();
  81977. }
  81978. getAllBoxes(){
  81979. return viewer.scene.volumes.filter(v=>v.clip && v instanceof Potree.BoxVolume )
  81980. }
  81981. getCalcData(){//给后台矩阵数据,以裁剪点云。
  81982. let Clip = viewer.modules.Clip; //裁剪下载模块
  81983. let data = {
  81984. transformation_matrix: viewer.scene.pointclouds.filter(p=>p.dataset_id == Potree.settings.originDatasetId).map((cloud)=>{
  81985. let data = {
  81986. id: cloud.dataset_id,
  81987. matrix : new Matrix4().elements, //参照downloadNoCrop,给默认值,表示没有最外层裁剪
  81988. visiMatrixes: cloud.material.clipBoxes_in.filter(e=>!e.box.isNew).map(e=>Clip.getTransformationMatrix(cloud, e.inverse).elements),
  81989. unVisiMatrixes: cloud.material.clipBoxes_out.filter(e=>!e.box.isNew).map(e=>Clip.getTransformationMatrix(cloud, e.inverse).elements),
  81990. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements //需要保证没有位移,否则剪裁后的模型位置会变化
  81991. };
  81992. return data
  81993. }) ,
  81994. aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //剪裁空间
  81995. };
  81996. return data
  81997. }
  81998. saveClipData(){//输出所有的clip volumeBox
  81999. let oldState = !viewer.clipUnabled;
  82000. viewer.setClipState(true);
  82001. let data = this.getAllBoxes().filter(e=>!e.isNew).map(volume=>{
  82002. return {
  82003. clipTask: volume.clipTask,
  82004. position: Potree.Utils.datasetPosTransform({position:volume.position, toDataset: true, datasetId: Potree.settings.originDatasetId}).toArray(),
  82005. rotation: Potree.Utils.datasetRotTransform({rotation:volume.rotation, toDataset: true, datasetId: Potree.settings.originDatasetId, getRotation:true}).toArray().slice(0,3),
  82006. scale: volume.scale.toArray(),
  82007. }
  82008. });
  82009. console.log(data);
  82010. console.log(JSON.stringify(data));
  82011. viewer.setClipState(oldState);
  82012. return data
  82013. }
  82014. loadFromData(data=[]){
  82015. data.forEach(v=>{
  82016. let volume = new Potree.BoxVolume({clip:true, clipTask:v.clipTask});
  82017. volume.scale.fromArray(v.scale);
  82018. volume.position.fromArray(v.position);
  82019. volume.rotation.fromArray(v.rotation);
  82020. volume.position.copy(Potree.Utils.datasetPosTransform({position:volume.position, fromDataset: true, datasetId:Potree.settings.originDatasetId}));
  82021. volume.rotation.copy(Potree.Utils.datasetRotTransform({rotation:volume.rotation, fromDataset: true, datasetId:Potree.settings.originDatasetId, getRotation:true}));
  82022. viewer.scene.addVolume(volume);
  82023. viewer.volumeTool.scene.add(volume);
  82024. });
  82025. }
  82026. }
  82027. //注意:实时裁剪只对初始数据集有效
  82028. /*
  82029. 备注:
  82030. 2023
  82031. 发送给后台数据样例:
  82032. {"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"}
  82033. 发送给算法部的数据样例:
  82034. {
  82035. "model": [
  82036. {
  82037. "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",
  82038. "file": "/mnt/data/pvt000004/1079784714115481600/pvt000004_202302271512444930_laserData/laserData/laser.las",
  82039. "visiMatrixes": [[..],[..]],
  82040. "dataSetId": "1630105213031026688",
  82041. "sceneCode": "SS-t-MVQ1Jb80oMG",
  82042. "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",
  82043. "unVisiMatrixes": [[..],[..]]
  82044. }
  82045. ],
  82046. "aabb": "b-12742000 -12742000 -12742000 12742000 12742000 12742000"
  82047. }
  82048. */
  82049. const vertexShader = `
  82050. attribute float randam;
  82051. attribute float sprite;
  82052. attribute float centerHeight; //add
  82053. //uniform float fireHeight; //add
  82054. uniform float time;
  82055. uniform float size;
  82056. uniform float heightOfNearPlane;
  82057. //varying float heightRatio;
  82058. varying float vSprite;
  82059. varying float vOpacity;
  82060. float PI = 3.14;
  82061. float quadraticIn( float t )
  82062. {
  82063. float tt = t * t;
  82064. return tt * tt;
  82065. //变化曲线 越来越快
  82066. }
  82067. void main() {
  82068. float progress = fract( time + ( 2.0 * randam - 1.0 ) );
  82069. float progressNeg = 1.0 - progress;
  82070. float ease = quadraticIn( progress );
  82071. float influence = sin( PI * ease );
  82072. //vec3 newPosition = position * vec3( 1.0, 1.0 , ease);
  82073. vec3 newPosition = position;
  82074. newPosition.z = (newPosition.z - centerHeight) * ease + centerHeight;
  82075. gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );
  82076. gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;
  82077. vOpacity = min( influence * 4.0, 1.0 ) * progressNeg;
  82078. vSprite = sprite;
  82079. //heightRatio = (newPosition.z - centerHeight) / fireHeight ;
  82080. }
  82081. `;
  82082. const fragmentShader = `
  82083. uniform vec3 color;
  82084. uniform sampler2D u_sampler;
  82085. varying float vSprite;
  82086. varying float vOpacity;
  82087. //varying float heightRatio;
  82088. void main()
  82089. {
  82090. vec2 texCoord = vec2(gl_PointCoord.x * 0.25 + vSprite, gl_PointCoord.y);
  82091. gl_FragColor = vec4( texture2D( u_sampler, texCoord ).xyz * color * vOpacity, 1.0 );
  82092. }
  82093. `;
  82094. // import { vertexShader, fragmentShader } from './shaders'
  82095. let ONE_SPRITE_ROW_LENGTH = 0.25; //对应着色器的0.25
  82096. let texture;
  82097. const getTexture = ()=>{
  82098. if(!texture){
  82099. texture = new TextureLoader().load( Potree.resourcePath+'/textures/fire.png');
  82100. }
  82101. return texture
  82102. };
  82103. const boxGeo = new BoxBufferGeometry(1,1,1,1);
  82104. const boxMat = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82105. class FireParticle extends Points{
  82106. constructor (prop) {
  82107. super();
  82108. for ( var key in prop ){
  82109. this[key] = prop[key];
  82110. }
  82111. this.strength = this.strength || 1;
  82112. this.radius = prop.radius || 1;
  82113. this.height = prop.height || 5;
  82114. this.computeParams();
  82115. this.geometry = this.createGeometry( this.radius, this.height, this.particleCount );
  82116. if(this.color == void 0) this.color = 0xff3200;
  82117. this.createMaterial( ); //小蓝火:0x00338f
  82118. //---?:
  82119. this.velocity = new Vector3();
  82120. this.acceleration = new Vector3();
  82121. this.angle = 0;
  82122. this.angleVelocity = 0;
  82123. this.angleAcceleration = 0;
  82124. this.size = 16;
  82125. this.opacity = 1;
  82126. this.age = 0;
  82127. this.alive = 0;
  82128. this.sizeTween = null;
  82129. this.colorTween = null;
  82130. this.opacityTween = null;
  82131. this.setSize({viewport:viewer.mainViewport});
  82132. this.setFov(viewer.fov);
  82133. let setSize = (e)=>{
  82134. if(e.viewport.name != "MainView")return
  82135. this.setSize(e);
  82136. };
  82137. let setFov = (e)=>{
  82138. this.setFov(e.fov);
  82139. };
  82140. viewer.addEventListener('resize',setSize);
  82141. viewer.addEventListener('fov_changed',setFov);
  82142. this.addEventListener('dispose',()=>{
  82143. viewer.removeEventListener('resize',setSize);
  82144. viewer.removeEventListener('fov_changed',setFov);
  82145. });
  82146. }
  82147. computeParams(){
  82148. let length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  82149. const minSize = 0.3, maxSize = 3, minRadiusBound = 0.3, maxRadiusBound = 10;
  82150. this.size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius, minRadiusBound, maxRadiusBound);
  82151. //console.log('fire material particle size:', size )
  82152. this.particleCount = Math.ceil( length * Math.sqrt(this.strength * this.height ) * this.radius / (this.size * this.size) * 25 );
  82153. //console.log('fire particleCount',this.particleCount)
  82154. }
  82155. getPointsForBound(){
  82156. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82157. }
  82158. getBound(points){ // points为生成点(圆心)
  82159. this.boundPoints = [];
  82160. let boundingBox = new Box3();
  82161. let margin = this.size * 0.13 + 0.3;
  82162. points.forEach(bottom=>{
  82163. let top = bottom.clone();
  82164. top.z += this.height;
  82165. boundingBox.expandByPoint(bottom);
  82166. boundingBox.expandByPoint(top);
  82167. this.boundPoints.push(bottom,top);
  82168. });
  82169. let xyExpand = this.radius+margin;
  82170. boundingBox.expandByVector(new Vector3(xyExpand,xyExpand,margin));
  82171. this.boundingBox = boundingBox;
  82172. /* if(!this.debugBox){
  82173. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  82174. this.add(this.debugBox)
  82175. }
  82176. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  82177. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  82178. }
  82179. createGeometry( radius, height, particleCount){
  82180. let geometry = new BufferGeometry();
  82181. let count , points;
  82182. if(this.positions.length>1){
  82183. const spaceDis = 0.2;//间隔距离
  82184. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  82185. //console.log('count', count)
  82186. points = this.curve.getSpacedPoints( count ); //得到的数量会比count多一个
  82187. count = points.length;
  82188. //得到的点不太均匀,两端容易点少。
  82189. this.getBound(points);
  82190. }else {
  82191. this.getBound(this.positions);
  82192. }
  82193. var position = new Float32Array(particleCount * 3);
  82194. var randam = new Float32Array(particleCount);
  82195. var sprite = new Float32Array(particleCount);
  82196. var centerHeight = new Float32Array(particleCount);
  82197. for (var i = 0; i < particleCount; i++) {
  82198. var center = new Vector3().copy(this.positions.length>1 ? points[Math.floor(i/particleCount * count)] : this.positions[0]);
  82199. centerHeight[i] = center.z;
  82200. if (i === 0) {
  82201. // to avoid going out of Frustum
  82202. position[i * 3 + 0] = center.x;
  82203. position[i * 3 + 1] = center.y;
  82204. position[i * 3 + 2] = center.z;
  82205. }else {
  82206. var r = Math.sqrt(Math.random()) * radius;
  82207. var angle = Math.random() * 2 * Math.PI;
  82208. position[i * 3 + 0] = center.x + Math.cos(angle) * r;
  82209. position[i * 3 + 1] = center.y + Math.sin(angle) * r;
  82210. position[i * 3 + 2] = center.z + (radius - r) / radius * height/2 + height/2; //不太明白这句为什么能达到height高度
  82211. sprite[i] = 0.25 * (Math.random() * 4 | 0);
  82212. randam[i] = Math.random();
  82213. //center在底部
  82214. }
  82215. }
  82216. geometry.setAttribute('centerHeight', new BufferAttribute(centerHeight, 1));
  82217. geometry.setAttribute('position', new BufferAttribute(position, 3));
  82218. geometry.setAttribute('randam', new BufferAttribute(randam, 1));
  82219. geometry.setAttribute('sprite', new BufferAttribute(sprite, 1));
  82220. return geometry;
  82221. }
  82222. updateGeometry(){
  82223. this.computeParams();
  82224. this.geometry.dispose();
  82225. this.geometry = this.createGeometry( this.radius, this.height, this.particleCount );
  82226. this.material.uniforms.size.value = this.size;
  82227. }
  82228. createMaterial(){
  82229. const material = new ShaderMaterial( {
  82230. uniforms:{
  82231. color: { type: "c", value: new Color(this.color) },
  82232. size: { type: "f", value: this.size},
  82233. u_sampler: { type: "t", value: getTexture() },
  82234. time: { type: "f", value: 0.0 },
  82235. heightOfNearPlane: { type: "f", value:0}, //相对far ,以确保画面缩放时点的大小也会缩放
  82236. height :{ type: "f", value:this.height} ,
  82237. },
  82238. vertexShader,
  82239. fragmentShader,
  82240. blending: AdditiveBlending, //加法融合模式 glBlendFunc(GL_ONE, GL_ONE)
  82241. depthTest: true,
  82242. depthWrite: false,
  82243. transparent: true
  82244. } );
  82245. this.material = material;
  82246. this.setPerspective(this.fov, this.screenHeight);
  82247. }
  82248. setSize(e){
  82249. let viewport = e.viewport;
  82250. this.screenHeight = viewport.resolution.y;
  82251. this.setPerspective(this.fov, this.screenHeight);
  82252. }
  82253. setFov(fov){
  82254. this.fov = fov;
  82255. this.setPerspective(this.fov, this.screenHeight);
  82256. }
  82257. setPerspective(fov, height){
  82258. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  82259. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  82260. this.material.uniforms.heightOfNearPlane.value = far;
  82261. }
  82262. update(delta){
  82263. if(!Potree.Utils.getObjVisiByReason(this,'force')){//被手动隐藏了
  82264. return
  82265. }
  82266. if(!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())){
  82267. Potree.Utils.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82268. //console.log('unvi')
  82269. return
  82270. }else {
  82271. Potree.Utils.updateVisible(this,'isInsideFrustum', true );
  82272. }
  82273. delta *= 1;//更改速度
  82274. this.material.uniforms.time.value = (this.material.uniforms.time.value + delta) % 1;
  82275. viewer.dispatchEvent('content_changed');
  82276. }
  82277. dispose(){
  82278. this.geometry.dispose();
  82279. this.material.dispose();
  82280. this.dispatchEvent('dispose');
  82281. }
  82282. }
  82283. class Tween {
  82284. constructor(times, values) {
  82285. this.times = times || [];
  82286. this.values = values || [];
  82287. }
  82288. lerp(t) {
  82289. if(this.times.length == 0) return
  82290. let i = 0, n = this.times.length;
  82291. while(i < n && t > this.times[i]) i++;
  82292. if(i == 0) return this.values[0]
  82293. if(i == n) return this.values[n-1]
  82294. const ratio = (t - this.times[i-1]) / (this.times[i] - this.times[i-1]);
  82295. if(this.values[0] instanceof Vector3) {
  82296. return this.values[i-1].clone().lerp(this.values[i], ratio)
  82297. } else {
  82298. return this.values[i-1] + ratio * (this.values[i] - this.values[i-1])
  82299. }
  82300. }
  82301. clone () {
  82302. return Common$1.CloneClassObject(this)
  82303. }
  82304. }
  82305. class Particle$1{
  82306. constructor(prop={}){
  82307. this.position = new Vector3();
  82308. this.velocity = new Vector3(); // units per second
  82309. this.angle = 0;
  82310. this.angleVelocity = 0; // degrees per second
  82311. this.angleAcceleration = 0; // degrees per second, per second
  82312. this.size = 16.0;
  82313. this.color = new Color();
  82314. this.opacity = 1.0;
  82315. this.age = 0;
  82316. this.alive = 0; // use float instead of boolean for shader purposes
  82317. this.lastChangeVage = 0; //add
  82318. this.sizeTween = prop.sizeTween || new Tween( [0, 1], [32, 128] );
  82319. this.opacityTween = prop.opacityTween || new Tween( [0.8, 2], [0.5, 0] );
  82320. this.colorTween = prop.colorTween || new Tween( [0.4, 1], [ new Vector3(0,0,0.2), new Vector3(0, 0, 0.5) ] );
  82321. }
  82322. update(dt)
  82323. {
  82324. this.position.add(this.velocity.clone().multiplyScalar(dt));
  82325. this.velocity.multiplyScalar( 1+this.acceleration*dt );
  82326. // convert from degrees to radians: 0.01745329251 = Math.PI/180
  82327. this.angle += this.angleVelocity * 0.01745329251 * dt;
  82328. this.angleVelocity += this.angleAcceleration * 0.01745329251 * dt;
  82329. this.age += dt;
  82330. // if the tween for a given attribute is nonempty,
  82331. // then use it to update the attribute's value
  82332. if ( this.sizeTween.times.length > 0 )
  82333. this.size = this.sizeTween.lerp( this.age/this.deathAge );
  82334. if ( this.colorTween.times.length > 0 )
  82335. {
  82336. var colorHSL = this.colorTween.lerp( this.age/this.deathAge );
  82337. this.color = new Color().setHSL( colorHSL.x, colorHSL.y, colorHSL.z );
  82338. }
  82339. if ( this.opacityTween.times.length > 0 )
  82340. {
  82341. this.opacity = this.opacityTween.lerp( this.age/this.deathAge);
  82342. }
  82343. viewer.dispatchEvent('content_changed');
  82344. }
  82345. }
  82346. const vertexShader$1 = `
  82347. attribute vec3 customColor;
  82348. attribute float customOpacity;
  82349. attribute float customSize;
  82350. attribute float customAngle;
  82351. attribute float customVisible;
  82352. uniform float heightOfNearPlane;
  82353. varying vec4 vColor;
  82354. varying float vAngle;
  82355. void main()
  82356. {
  82357. if ( customVisible > 0.5 )
  82358. vColor = vec4( customColor, customOpacity );
  82359. else
  82360. vColor = vec4(0.0, 0.0, 0.0, 0.0);
  82361. vAngle = customAngle;
  82362. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  82363. //gl_PointSize = customSize * ( 300.0 / length( mvPosition.xyz ) );
  82364. gl_Position = projectionMatrix * mvPosition;
  82365. gl_PointSize = ( heightOfNearPlane * customSize ) / gl_Position.w;
  82366. }
  82367. `;
  82368. const fragmentShader$1 = `
  82369. uniform sampler2D u_sampler;
  82370. varying vec4 vColor;
  82371. varying float vAngle;
  82372. void main()
  82373. {
  82374. gl_FragColor = vColor;
  82375. float c = cos(vAngle);
  82376. float s = sin(vAngle);
  82377. 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);
  82378. vec4 rotatedTexture = texture2D( u_sampler, rotatedUV );
  82379. gl_FragColor = gl_FragColor * rotatedTexture;
  82380. }
  82381. `;
  82382. const Type = Object.freeze({ "CUBE":1, "SPHERE":2 });
  82383. let particleTexture;
  82384. const getTexture$1 = ()=>{
  82385. if(!particleTexture){
  82386. particleTexture = new TextureLoader().load( Potree.resourcePath+'/textures/smokeparticle.png');
  82387. }
  82388. return particleTexture
  82389. };
  82390. const boxGeo$1 = new BoxBufferGeometry(1,1,1,1);
  82391. const boxMat$1 = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82392. const defaults =
  82393. {
  82394. positions: [],
  82395. positionStyle : "sphere",
  82396. positionBase : new Vector3( 0, 0, 0 ),
  82397. positionSpread : new Vector3( 1, 1, 0), //cube
  82398. radius : 1, // sphere
  82399. velocityStyle : 'cube',
  82400. velocityBase : new Vector3( 0, 0, 0.5), // cube 基础速度
  82401. velocitySpread : new Vector3( 1, 1, 0.3),
  82402. accelerationBase : 0.3, //基础加速度
  82403. accelerationSpread : 0.6,
  82404. //没使用
  82405. speedBase : 0.1, //sphere
  82406. speedSpread : 0.5,
  82407. angleBase : 0,
  82408. angleSpread : 360,
  82409. angleVelocityBase : 1,
  82410. angleVelocitySpread : 30,
  82411. angleAccelerationBase : 1,
  82412. angleAccelerationSpread : 5,
  82413. sizeBase : 0,
  82414. sizeSpread : 0,
  82415. sizeTween : [[0, 0.3, 1], [0.3, 1.4, 6 ]],
  82416. colorBase : new Vector3(0.0, 1.0, 0.5),
  82417. colorSpread : new Vector3(0.0, 0.0, 0.0),
  82418. colorTween : new Tween( [0.2, 1], [ new Vector3(0,0,0.4), new Vector3(0, 0, 0.1) ] ),
  82419. opacityBase : 0.1,//1.0,
  82420. opacitySpread : 0.2,
  82421. opacityTween :[ [0, 0.1, 0.9, 1], [0.1, 0.4 , 0.03, 0 ] ],
  82422. //particlesPerSecond : 20,
  82423. strength : 1,
  82424. particleDeathAge : 3, //从底下升起后能持续的时间
  82425. //emitterDeathAge : 60 // time (seconds) at which to stop creating particles.
  82426. height : 3,
  82427. };
  82428. const debugSphere = new Mesh(new SphereBufferGeometry(0.03, 5,5), new MeshBasicMaterial({color:'white',depthTest:false}));
  82429. class SmokeParticle extends Points{
  82430. constructor(prop={}) {
  82431. super();
  82432. this.blendStyle = NormalBlending; // false;
  82433. this.emitterAge = 0.0;
  82434. //this.emitterAlive = true;
  82435. prop = $.extend({}, defaults, prop);
  82436. for ( var key in prop ){
  82437. let value = prop[key];
  82438. if(value instanceof Array && value[0] instanceof Array ) this[ key ] = new Tween(...value);
  82439. else if(value instanceof Vector3 || value instanceof Color){
  82440. this[ key ] = value.clone();
  82441. }else {
  82442. this[ key ] = value;
  82443. }
  82444. }
  82445. this.defaultSizeTween = this.sizeTween.clone();
  82446. this.defaultOpacityTween = this.opacityTween.clone();
  82447. this.geometry = new BufferGeometry();
  82448. this.computeParams();
  82449. this.createMaterial();
  82450. this.createGeometry();
  82451. this.dynamic = true;
  82452. this.sortParticles = true;
  82453. this.frustumCulled = false;//似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  82454. prop.position && this.position.copy(prop.position);
  82455. //---------------------------------------
  82456. this.setSize({viewport:viewer.mainViewport});
  82457. this.setFov(viewer.fov);
  82458. let setSize = (e)=>{
  82459. if(e.viewport.name != "MainView")return
  82460. this.setSize(e);
  82461. };
  82462. let setFov = (e)=>{
  82463. this.setFov(e.fov);
  82464. };
  82465. /* let reStart = (e)=>{
  82466. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  82467. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  82468. //console.log('归零')
  82469. //this.reStart()
  82470. },1)
  82471. }
  82472. } */
  82473. viewer.addEventListener('resize',setSize);
  82474. viewer.addEventListener('fov_changed',setFov);
  82475. //viewer.addEventListener('pageVisible', reStart)
  82476. this.addEventListener('dispose',()=>{
  82477. viewer.removeEventListener('resize',setSize);
  82478. viewer.removeEventListener('fov_changed',setFov);
  82479. //viewer.removeEventListener('pageVisible', reStart)
  82480. });
  82481. }
  82482. computeParams(){
  82483. let length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  82484. //注意:烟最低高度一米, 0<strength<1
  82485. if(this.positionStyle == 'cube'){
  82486. this.positionSpread.set(this.radius,this.radius,0);
  82487. }
  82488. this.velocityBase.set(0,0, (this.height - 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge) / this.particleDeathAge );
  82489. //let height = this.velocityBase.z * this.particleDeathAge + 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge;//s = V0 * t + 0.5 * a * t*t ;
  82490. this.velocityBase.z = Math.max(0,this.velocityBase.z);
  82491. this.particleCount = Math.ceil( length * Math.sqrt(this.strength * this.height * this.radius ) );
  82492. this.particleCount = Math.max(5,this.particleCount);
  82493. {
  82494. const minSize = 1, maxSize = 2, minBound = 0.01, maxBound = 1;
  82495. let size = minSize + (maxSize - minSize) * MathUtils.smoothstep( this.strength, minBound, maxBound);
  82496. this.sizeTween.values = this.defaultSizeTween.values.map(e=> e*size);
  82497. }
  82498. {
  82499. const minSize = 1 , maxSize = 1.5, minBound = 0.01, maxBound = 1;
  82500. let opac = minSize + (maxSize - minSize) * MathUtils.smoothstep( this.strength, minBound, maxBound);
  82501. this.opacityTween.values = this.defaultOpacityTween.values.map(e=> e*opac );
  82502. }
  82503. //console.log('smoke particleCount',this.particleCount)
  82504. }
  82505. reStart(){
  82506. this.emitterAge = 0;
  82507. this.createGeometry();
  82508. }
  82509. updateGeometry(){
  82510. this.computeParams();
  82511. this.reStart();
  82512. }
  82513. createParticle(center)
  82514. {
  82515. var particle = new Particle$1({
  82516. sizeTween : this.sizeTween,
  82517. opacityTween : this.opacityTween,
  82518. colorTween : this.colorTween,
  82519. });
  82520. particle.deathAge = this.particleDeathAge;
  82521. particle.center = center;
  82522. if (this.positionStyle == 'cube')
  82523. particle.position = this.randomVector3( this.positionBase, this.positionSpread );
  82524. if (this.positionStyle == 'sphere')
  82525. {
  82526. /* var z = 2 * Math.random() - 1
  82527. var t = Math.PI * 2 * Math.random();
  82528. var r = Math.sqrt( 1 - z*z ) ;
  82529. var vec3 = new THREE.Vector3( r * Math.cos(t), r * Math.sin(t), z );
  82530. particle.position = new THREE.Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  82531. */
  82532. //怎么改半径
  82533. let y = 2 * Math.random() - 1;
  82534. let t = Math.PI * 2 * Math.random();
  82535. let r = Math.sqrt( 1 - y*y ) ; //因为 r*r = 1-y*y = x*x + z*z = r*r(cos^2 + sin^2 );
  82536. let lowDownRatio = 0.2; //压低近平面
  82537. let vec3 = new Vector3( r * Math.cos(t), y, Math.abs(r * Math.sin(t) ) * lowDownRatio);
  82538. particle.position = new Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  82539. }
  82540. particle.position.add(center);//add
  82541. if ( this.velocityStyle == 'cube' )
  82542. {
  82543. particle.velocity = this.randomVector3( this.velocityBase, this.velocitySpread );
  82544. }
  82545. if ( this.velocityStyle == 'sphere' )
  82546. {
  82547. //var direction = particle.position.clone()
  82548. var direction = new Vector3(0,0,1); //烟应该都是向上的
  82549. var speed = this.randomValue( this.speedBase, this.speedSpread );
  82550. particle.velocity = direction.normalize().multiplyScalar( speed );
  82551. }
  82552. particle.acceleration = this.randomValue( this.accelerationBase, this.accelerationSpread );
  82553. particle.angle = this.randomValue( this.angleBase, this.angleSpread );
  82554. particle.angleVelocity = this.randomValue( this.angleVelocityBase, this.angleVelocitySpread );
  82555. particle.angleAcceleration = this.randomValue( this.angleAccelerationBase, this.angleAccelerationSpread );
  82556. particle.size = this.randomValue( this.sizeBase, this.sizeSpread );
  82557. var color = this.randomVector3( this.colorBase, this.colorSpread );
  82558. particle.color = new Color().setHSL( color.x, color.y, color.z );
  82559. particle.opacity = this.randomValue( this.opacityBase, this.opacitySpread );
  82560. particle.age = 0;
  82561. particle.alive = 0; // particles initialize as inactive
  82562. return particle;
  82563. }
  82564. getPointsForBound(){
  82565. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82566. }
  82567. getBound(points){ // points为生成点(圆心)
  82568. this.boundPoints = [];
  82569. let boundingBox = new Box3();
  82570. let maxSize = this.sizeTween.values.slice().sort((a,b)=>b-a)[0];
  82571. let margin0 = maxSize * 0.11;
  82572. let margin1 = margin0 + 0.5 ;//保守估计还会飘出这么多距离吧: size + 飘动
  82573. points.forEach(bottom=>{
  82574. let top = bottom.clone();
  82575. top.z += this.height;
  82576. boundingBox.expandByPoint(bottom);
  82577. boundingBox.expandByPoint(top);
  82578. this.boundPoints.push(bottom,top);
  82579. });
  82580. let xyExpand = this.radius+margin1;
  82581. boundingBox.expandByVector(new Vector3(xyExpand,xyExpand,0));
  82582. boundingBox.min.z -= margin0;
  82583. boundingBox.max.z += margin1;
  82584. this.boundingBox = boundingBox;
  82585. /* if(!this.debugBox){
  82586. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  82587. this.add(this.debugBox)
  82588. }
  82589. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  82590. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  82591. }
  82592. createGeometry(){
  82593. this.particleArray = [];
  82594. const positions = [];
  82595. const colors = [];
  82596. const alives = [];
  82597. const opacitys = [];
  82598. const sizes = [];
  82599. const angles = [];
  82600. let count, points;
  82601. if(this.positions.length>1){
  82602. const spaceDis = 0.6;//间隔距离
  82603. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  82604. points = this.curve.getSpacedPoints( count );
  82605. count = points.length;
  82606. /* points.forEach(e=> {
  82607. var sphere = debugSphere.clone();
  82608. sphere.position.copy(e)
  82609. viewer.scene.scene.add(sphere)
  82610. }) */
  82611. let haventGetPoints = points.slice();
  82612. var getRanPoints = function(i){
  82613. var a = Math.random();
  82614. let choseIndex = Math.floor(haventGetPoints.length * a);
  82615. var point = haventGetPoints[choseIndex];
  82616. if(haventGetPoints.length == 1){
  82617. haventGetPoints = points.slice();
  82618. }else {
  82619. haventGetPoints.splice(choseIndex, 1);
  82620. }
  82621. return point
  82622. };
  82623. this.getBound(points);
  82624. }else {
  82625. this.getBound(this.positions);
  82626. }
  82627. for (var i = 0; i < this.particleCount; i++)
  82628. {
  82629. var center = new Vector3().copy(this.positions.length>1 ? getRanPoints(i) : this.positions[0]);
  82630. //var center = new THREE.Vector3().copy(this.positions.length>1 ? points[Math.floor(i/this.particleCount * count)] : this.positions[0])
  82631. // remove duplicate code somehow, here and in update function below.
  82632. this.particleArray[i] = this.createParticle(center);
  82633. positions[3*i] = this.particleArray[i].position.x;
  82634. positions[3*i+1] = this.particleArray[i].position.y;
  82635. positions[3*i+2] = this.particleArray[i].position.z;
  82636. colors[3*i] = this.particleArray[i].color.r;
  82637. colors[3*i+1] = this.particleArray[i].color.g;
  82638. colors[3*i+2] = this.particleArray[i].color.b;
  82639. alives[i] = this.particleArray[i].alive;
  82640. opacitys[i] = this.particleArray[i].opacity;
  82641. sizes[i] = this.particleArray[i].size;
  82642. angles[i] = this.particleArray[i].angle;
  82643. }
  82644. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ));
  82645. this.geometry.setAttribute( 'customColor', new BufferAttribute( new Float32Array(colors), 3 ) );
  82646. this.geometry.setAttribute( 'customVisible', new BufferAttribute( new Float32Array(alives), 1 ) );
  82647. this.geometry.setAttribute( 'customOpacity', new BufferAttribute( new Float32Array(opacitys), 1 ) );
  82648. this.geometry.setAttribute( 'customSize', new BufferAttribute( new Float32Array(sizes), 1 ) );
  82649. this.geometry.setAttribute( 'customAngle', new BufferAttribute( new Float32Array(angles), 1 ) );
  82650. }
  82651. createMaterial(){
  82652. this.material = new ShaderMaterial(
  82653. {
  82654. uniforms:
  82655. {
  82656. u_sampler: { type: "t", value: getTexture$1() },
  82657. heightOfNearPlane: { type: "f", value:0} //相对far ,以确保画面缩放时点的大小也会缩放
  82658. },
  82659. vertexShader: vertexShader$1,vertexShader: vertexShader$1,
  82660. fragmentShader: fragmentShader$1,
  82661. transparent: true,
  82662. alphaTest: 0.5, // if having transparency issues, try including: alphaTest: 0.5,
  82663. blending: this.blendStyle,
  82664. depthTest: this.blendStyle != NormalBlending
  82665. });
  82666. this.setPerspective(this.fov, this.screenHeight);
  82667. }
  82668. update(dt){
  82669. if(!Potree.Utils.getObjVisiByReason(this,'force')){//被手动隐藏了
  82670. return
  82671. }
  82672. if(!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())){
  82673. Potree.Utils.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82674. //console.log('unvi')
  82675. return
  82676. }else {
  82677. Potree.Utils.updateVisible(this,'isInsideFrustum', true );
  82678. }
  82679. if(dt > 1){
  82680. console.log('update dt>1', dt);
  82681. }
  82682. //dt *= 0.5;
  82683. const recycleIndices = [];
  82684. const recycleAges = [];
  82685. const positions = [];
  82686. const colors = [];
  82687. const alives = [];
  82688. const opacitys = [];
  82689. const sizes = [];
  82690. const angles = [];
  82691. for (var i = 0; i < this.particleCount; i++)
  82692. {
  82693. if ( this.particleArray[i].alive )
  82694. {
  82695. if ( this.velocityStyle == 'cube' )
  82696. { //一定几率改变下方向
  82697. let ratio = Math.random();
  82698. if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*ratio ){
  82699. this.particleArray[i].velocity = this.randomVector3( this.velocityBase, this.velocitySpread );
  82700. this.particleArray[i].lastChangeVage = this.particleArray[i].age;
  82701. }
  82702. }else {
  82703. /* if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*0.3 ){
  82704. if( Math.random()>0.1){//一定几率改变下方向
  82705. var speed = this.randomValue( this.speedBase, this.speedSpread );
  82706. this.particleArray[i].velocity = this.randomVector3( new THREE.Vector3, new THREE.Vector3(1,1,1) );
  82707. this.particleArray[i].velocity.normalize().multiplyScalar( speed );
  82708. }
  82709. this.particleArray[i].lastChangeVage = this.particleArray[i].age
  82710. } */
  82711. }
  82712. this.particleArray[i].update(dt);
  82713. // check if particle should expire
  82714. // could also use: death by size<0 or alpha<0.
  82715. if ( this.particleArray[i].age > this.particleDeathAge )
  82716. {
  82717. this.particleArray[i].alive = 0.0;
  82718. recycleIndices.push(i);
  82719. recycleAges.push((this.particleArray[i].age - this.particleDeathAge)%(this.particleDeathAge ));
  82720. }
  82721. // update particle properties in shader
  82722. positions[3*i] = this.particleArray[i].position.x;
  82723. positions[3*i+1] = this.particleArray[i].position.y;
  82724. positions[3*i+2] = this.particleArray[i].position.z;
  82725. colors[3*i] = this.particleArray[i].color.r;
  82726. colors[3*i+1] = this.particleArray[i].color.g;
  82727. colors[3*i+2] = this.particleArray[i].color.b;
  82728. alives[i] = this.particleArray[i].alive;
  82729. opacitys[i] = this.particleArray[i].opacity;
  82730. sizes[i] = this.particleArray[i].size;
  82731. angles[i] = this.particleArray[i].angle;
  82732. }
  82733. }
  82734. // check if particle emitter is still running
  82735. //if ( !this.emitterAlive ) return;
  82736. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ) );
  82737. this.geometry.setAttribute( 'customColor', new BufferAttribute( new Float32Array(colors), 3 ) );
  82738. this.geometry.setAttribute( 'customVisible', new BufferAttribute( new Float32Array(alives), 1 ) );
  82739. this.geometry.setAttribute( 'customOpacity', new BufferAttribute( new Float32Array(opacitys), 1 ) );
  82740. this.geometry.setAttribute( 'customSize', new BufferAttribute( new Float32Array(sizes), 1 ) );
  82741. this.geometry.setAttribute( 'customAngle', new BufferAttribute( new Float32Array(angles), 1 ) );
  82742. this.geometry.attributes.customColor.needsUpdate = true;
  82743. this.geometry.attributes.customVisible.needsUpdate = true;
  82744. this.geometry.attributes.customOpacity.needsUpdate = true;
  82745. this.geometry.attributes.customSize.needsUpdate = true;
  82746. this.geometry.attributes.customAngle.needsUpdate = true;
  82747. // if no particles have died yet, then there are still particles to activate
  82748. if ( this.emitterAge < this.particleDeathAge ) //开始时一个个放出来
  82749. {
  82750. let particlesPerSecond = this.particleCount / this.particleDeathAge;
  82751. // determine indices of particles to activate
  82752. var startIndex = Math.round( particlesPerSecond * (this.emitterAge + 0) );
  82753. var endIndex = Math.round( particlesPerSecond * (this.emitterAge + dt) );
  82754. if ( endIndex > this.particleCount )
  82755. endIndex = this.particleCount;
  82756. for (var i = startIndex; i < endIndex; i++)
  82757. this.particleArray[i].alive = 1.0;
  82758. }
  82759. // if any particles have died while the emitter is still running, we imediately recycle them
  82760. for (var j = 0; j < recycleIndices.length; j++)
  82761. {
  82762. var i = recycleIndices[j];
  82763. this.particleArray[i] = this.createParticle(this.particleArray[i].center);
  82764. this.particleArray[i].alive = 1.0; // activate right away
  82765. this.particleArray[i].age = recycleAges[j];
  82766. positions[3*i] = this.particleArray[i].position.x;
  82767. positions[3*i+1] = this.particleArray[i].position.y;
  82768. positions[3*i+2] = this.particleArray[i].position.z;
  82769. }
  82770. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ) );
  82771. this.geometry.attributes.position.needsUpdate = true;
  82772. // stop emitter?
  82773. this.emitterAge += dt;
  82774. //if ( this.emitterAge > this.emitterDeathAge ) this.emitterAlive = false;
  82775. }
  82776. randomValue(base, spread)
  82777. {
  82778. //return base + spread * (Math.random() - 0.5);
  82779. let p = Math.random();
  82780. return base * p + spread * (1-p)
  82781. }
  82782. randomVector3(base, spread)
  82783. {
  82784. var rand3 = new Vector3( Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 );
  82785. return new Vector3().addVectors( base, new Vector3().multiplyVectors( spread, rand3 ) );
  82786. }
  82787. setSize(e){
  82788. let viewport = e.viewport;
  82789. this.screenHeight = viewport.resolution.y;
  82790. this.setPerspective(this.fov, this.screenHeight);
  82791. }
  82792. setFov(fov){
  82793. this.fov = fov;
  82794. this.setPerspective(this.fov, this.screenHeight);
  82795. }
  82796. setPerspective(fov, height){
  82797. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  82798. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  82799. this.material.uniforms.heightOfNearPlane.value = far;
  82800. }
  82801. dispose(){
  82802. this.geometry.dispose();
  82803. this.material.dispose();
  82804. this.dispatchEvent('dispose');
  82805. }
  82806. }
  82807. /*
  82808. 改进:如果有必要
  82809. 根据curve中分成的点,分成多个簇,每个簇掌管该部分的可见性和particle的数量。
  82810. 在camera_changed时根据远近修改每个簇的particle的数量,当然不会大于初始创建的个数。多出的随机隐藏。
  82811. */
  82812. const vertexShader$2 = `
  82813. attribute vec3 color;
  82814. attribute float size;
  82815. attribute float angle;
  82816. attribute float opacity;
  82817. attribute float visible;
  82818. varying vec4 vColor;
  82819. varying float vAngle;
  82820. uniform float heightOfNearPlane;
  82821. void main() {
  82822. if(visible > 0.5) {
  82823. vColor = vec4(color, opacity);
  82824. } else {
  82825. vColor = vec4(0.0, 0.0, 0.0, 0.0);
  82826. }
  82827. vAngle = angle;
  82828. vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
  82829. gl_Position = projectionMatrix * mvPosition;
  82830. gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;
  82831. }
  82832. `;
  82833. const fragmentShader$2 = `
  82834. uniform sampler2D u_sampler;
  82835. varying vec4 vColor;
  82836. varying float vAngle;
  82837. void main() {
  82838. gl_FragColor = vColor;
  82839. float u = cos(vAngle);
  82840. float v = sin(vAngle);
  82841. vec2 uv = vec2(
  82842. u * (gl_PointCoord.x - 0.5) + v * (gl_PointCoord.y - 0.5) + 0.5,
  82843. u * (gl_PointCoord.y - 0.5) - v * (gl_PointCoord.x - 0.5) + 0.5
  82844. );
  82845. vec4 texture = texture2D(u_sampler, uv);
  82846. gl_FragColor = gl_FragColor * texture;
  82847. }
  82848. `;
  82849. // import { vertexShader, fragmentShader } from './shader'
  82850. const DEG2RAD = Math.PI / 180;
  82851. class Particle$2 {
  82852. constructor() {
  82853. this.position = new Vector3();
  82854. this.velocity = new Vector3();
  82855. this.angle = 0;
  82856. this.angleVelocity = 0;
  82857. this.angleAcceleration = 0;
  82858. this.size = 16;
  82859. this.color = new Color();
  82860. this.opacity = 1;
  82861. this.rebornCount = 0;//重生次数
  82862. this.age = 0;
  82863. this.alive = 0; //注意,一开始时是未出生的
  82864. this.deadAge = 0;//已死亡时间
  82865. this.sizeTween = null;
  82866. this.colorTween = null;
  82867. this.opacityTween = null;
  82868. }
  82869. update(dt) {
  82870. //s = s0 + (v0 + at) * t 或 lastS + delta(vt)
  82871. this.position.add(this.velocity.clone().multiplyScalar(dt));
  82872. this.velocity.multiplyScalar( 1+this.acceleration*dt );
  82873. this.angle += this.angleVelocity * DEG2RAD * dt;
  82874. this.angleVelocity += this.angleAcceleration * DEG2RAD * dt;
  82875. this.age += dt;
  82876. if(this.sizeTween.times.length > 0) {
  82877. this.size = this.sizeTween.lerp(this.age/this.deathAge);
  82878. }
  82879. if(this.colorTween.times.length > 0) {
  82880. const colorHSL = this.colorTween.lerp(this.age/this.deathAge);
  82881. this.color = new Color().setHSL(colorHSL.x, colorHSL.y, colorHSL.z);
  82882. }
  82883. if(this.opacityTween.times.length > 0) {
  82884. this.opacity = this.opacityTween.lerp(this.age/this.deathAge);
  82885. }
  82886. viewer.dispatchEvent('content_changed');
  82887. }
  82888. }
  82889. class Util {
  82890. constructor() {}
  82891. randomValue(min, max) {
  82892. //return min + max * (Math.random() - 0.5)
  82893. let p = Math.random();
  82894. return min * p + max * (1-p)
  82895. }
  82896. randomVector3(min, max) {
  82897. const rand3 = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);
  82898. return new Vector3().addVectors(min, new Vector3().multiplyVectors(max, rand3))
  82899. }
  82900. }
  82901. const util$1 = new Util();
  82902. const Shape$1 = {
  82903. CUBE: 1,
  82904. SPHERE: 2
  82905. };
  82906. let particleTexture$1;
  82907. const getTexture$2 = ()=>{
  82908. if (!particleTexture$1) {
  82909. particleTexture$1 = new TextureLoader().load(Potree.resourcePath + '/textures/explode.png');
  82910. }
  82911. return particleTexture$1
  82912. };
  82913. const sphereGeo = new SphereBufferGeometry(1, 10,4);
  82914. const sphereMat = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82915. const defaults$1 = {
  82916. position: new Vector3(0,0,1),
  82917. positionShape: Shape$1.SPHERE,
  82918. positionRange: new Vector3(1,1,1),
  82919. //cube
  82920. radius: 1.3,
  82921. //sphere
  82922. velocityShape: Shape$1.SPHERE,
  82923. velocity: new Vector3(0,0,2),
  82924. //cube
  82925. velocityRange: new Vector3(0,0,3),
  82926. //sphere
  82927. speed: 0.4,
  82928. speedRange: 1,
  82929. size: 0.4,
  82930. sizeRange: 2,
  82931. //sizeTween: new Tween( [0, 0.05, 0.3, 0.45], [0, 1, 3, 0.1] ),
  82932. sizeTween: [[0, 0.04, 0.2, 1],[0.1, 1, 6, 8]] ,
  82933. color: new Vector3(1.0,1.0,1.0),
  82934. colorRange: new Vector3(0,0,0),
  82935. colorTween: new Tween(),
  82936. opacity: 1.0,
  82937. opacityRange: 0.0,
  82938. opacityTween: new Tween([0, 0.06, 0.3, 0.8, 1],[0, 1, 0.3, 0.05, 0]),
  82939. blendMode: AdditiveBlending,
  82940. acceleration: 0.5,
  82941. accelerationRange: 0,
  82942. angle: 0,
  82943. angleRange: 0,
  82944. angleVelocity: 0,
  82945. angleVelocityRange: 0,
  82946. angleAcceleration: 0,
  82947. angleAccelerationRange: 0,
  82948. strength:1,
  82949. //particlesPerSecond: 8,
  82950. particleDeathAge: 0.7 ,
  82951. recycleTimes : 3 , //每个粒子在一次爆炸后循环次数,循环完毕进入particleSpaceTime,等待下一次爆炸.
  82952. //爆炸时长: particleDeathAge * (recycleTimes+1)
  82953. particleSpaceTime: 3, //间隔
  82954. };
  82955. class ExplodeParticle extends Points {
  82956. constructor(params) {
  82957. super();
  82958. this.age = 0;
  82959. this.alive = true;
  82960. //this.deathAge = 60
  82961. this.loop = true;
  82962. this.blendMode = NormalBlending;
  82963. this.setParameters(params);
  82964. this.createParticles();
  82965. this.frustumCulled = false;//似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  82966. //------------------------------------
  82967. this.setSize({viewport:viewer.mainViewport});
  82968. this.setFov(viewer.fov);
  82969. let setSize = (e)=>{
  82970. if(e.viewport.name != "MainView")return
  82971. this.setSize(e);
  82972. };
  82973. let setFov = (e)=>{
  82974. this.setFov(e.fov);
  82975. };
  82976. /* let reStart = (e)=>{
  82977. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  82978. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  82979. //console.log('归零')
  82980. //this.reStart()
  82981. },1)
  82982. }
  82983. } */
  82984. viewer.addEventListener('resize',setSize);
  82985. viewer.addEventListener('fov_changed',setFov);
  82986. //viewer.addEventListener('pageVisible', reStart)
  82987. this.addEventListener('dispose',()=>{
  82988. viewer.removeEventListener('resize',setSize);
  82989. viewer.removeEventListener('fov_changed',setFov);
  82990. //viewer.removeEventListener('pageVisible', reStart)
  82991. });
  82992. }
  82993. computeParams(){
  82994. if(this.curve){
  82995. this.position.copy(this.curve.points[0]);
  82996. }
  82997. const minSize = 0.8, maxSize = 10, minRadiusBound = 0.2, maxRadiusBound = 20;
  82998. let size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius*this.strength , minRadiusBound, maxRadiusBound);
  82999. this.sizeTween.values = this.defaultSizeTween.values.map(e=> e*size);
  83000. this.particleCount = Math.ceil( this.strength * this.radius * 5 /* * this.radius * this.radius */ );
  83001. this.speed = defaults$1.speed * this.radius;
  83002. this.speedRange = defaults$1.speedRange * this.radius;
  83003. console.log(this.particleCount);
  83004. {
  83005. this.boundPoints = [];
  83006. this.boundPoints.push(this.position.clone());
  83007. let maxSize = this.sizeTween.values.slice().sort((a,b)=>b-a)[0];
  83008. let margin = maxSize * 0.35 + 0.5;
  83009. let scale = this.radius+margin;
  83010. let sphere = new Sphere(this.position, scale);//加上防止剪裁
  83011. this.boundingSphere = sphere; //虽然还是会有一些后续移动的会超出
  83012. this.boundingBox = new Box3().setFromCenterAndSize(this.position, new Vector3(scale*2,scale*2,scale*2));
  83013. /* if(!this.debugSphere){
  83014. this.debugSphere = new THREE.Mesh(sphereGeo, sphereMat)
  83015. this.add(this.debugSphere)
  83016. }
  83017. this.debugSphere.scale.set(scale,scale,scale) */
  83018. }
  83019. }
  83020. getPointsForBound(){
  83021. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  83022. }
  83023. reStart(){
  83024. this.age = 0;
  83025. this.createParticles();
  83026. }
  83027. setParameters(params) {
  83028. params = $.extend({}, defaults$1, params);
  83029. for (var key in params) {
  83030. let value = params[key];
  83031. if (key == 'position')
  83032. this.position.copy(value);
  83033. else if (value instanceof Array && value[0]instanceof Array){
  83034. this[key] = new Tween(...value);
  83035. }else if(value instanceof Vector3 || value instanceof Color){
  83036. this[ key ] = value.clone();
  83037. }else {
  83038. this[key] = value;
  83039. }
  83040. }
  83041. this.defaultSizeTween = this.sizeTween.clone();
  83042. //Object.assign(this, params)
  83043. this.particles = [];
  83044. this.age = 0.0;
  83045. this.alive = true;
  83046. this.geometry = new BufferGeometry();
  83047. this.computeParams();
  83048. this.material = new ShaderMaterial({
  83049. uniforms: {
  83050. u_sampler: {
  83051. value: this.texture || getTexture$2()
  83052. },
  83053. heightOfNearPlane: {
  83054. type: "f",
  83055. value: 0
  83056. }//相对far ,以确保画面缩放时点的大小也会缩放
  83057. },
  83058. vertexShader: vertexShader$2,
  83059. fragmentShader: fragmentShader$2,
  83060. transparent: true,
  83061. alphaTest: 0.5,
  83062. depthTest: this.blendMode == NormalBlending,
  83063. blending: this.blendMode
  83064. });
  83065. }
  83066. createParticles() {
  83067. this.particles = [];
  83068. const count = this.particleCount;
  83069. const positionArray = new Float32Array(count * 3);
  83070. const colorArray = new Float32Array(count * 3);
  83071. const sizeArray = new Float32Array(count);
  83072. const angleArray = new Float32Array(count);
  83073. const opacityArray = new Float32Array(count);
  83074. const visibleArray = new Float32Array(count);
  83075. for (let i = 0; i < count; i++) {
  83076. const particle = this.createParticle();
  83077. /* positionArray[i * 3] = particle.position.x
  83078. positionArray[i * 3 + 1] = particle.position.y
  83079. positionArray[i * 3 + 2] = particle.position.z
  83080. colorArray[i * 3] = particle.color.r
  83081. colorArray[i * 3 + 1] = particle.color.g
  83082. colorArray[i * 3 + 2] = particle.color.b
  83083. sizeArray[i] = particle.size
  83084. angleArray[i] = particle.angel
  83085. opacityArray[i] = particle.opacity
  83086. visibleArray[i] = particle.alive */
  83087. this.particles[i] = particle;
  83088. }
  83089. this.geometry.setAttribute('position', new BufferAttribute(positionArray,3));
  83090. this.geometry.setAttribute('color', new BufferAttribute(colorArray,3));
  83091. this.geometry.setAttribute('angle', new BufferAttribute(angleArray,1));
  83092. this.geometry.setAttribute('size', new BufferAttribute(sizeArray,1));
  83093. this.geometry.setAttribute('visible', new BufferAttribute(visibleArray,1));
  83094. this.geometry.setAttribute('opacity', new BufferAttribute(opacityArray,1));
  83095. }
  83096. createParticle() {
  83097. const particle = new Particle$2();
  83098. particle.sizeTween = this.sizeTween;
  83099. particle.colorTween = this.colorTween;
  83100. particle.opacityTween = this.opacityTween;
  83101. particle.deathAge = this.particleDeathAge;
  83102. if (this.positionShape == Shape$1.CUBE) {
  83103. particle.position = util$1.randomVector3(new Vector3, this.positionRange);
  83104. }
  83105. if (this.positionShape == Shape$1.SPHERE) {
  83106. /* const z = 2 * Math.random() - 1
  83107. const t = Math.PI * 2 * Math.random()
  83108. const r = Math.sqrt(1 - z*z)
  83109. const vec3 = new THREE.Vector3(r * Math.cos(t), r * Math.sin(t), z)
  83110. particle.position = vec3.multiplyScalar(this.radius) */
  83111. const y = 2 * Math.random() - 1;
  83112. const t = Math.PI * 2 * Math.random();
  83113. const r = Math.sqrt(1 - y * y);
  83114. const vec3 = new Vector3(r * Math.cos(t),y,r * Math.sin(t));
  83115. particle.position = vec3.multiplyScalar(this.radius);
  83116. }
  83117. if (this.velocityShape == Shape$1.CUBE) {
  83118. particle.velocity = util$1.randomVector3(this.velocity, this.velocityRange);
  83119. }
  83120. if (this.velocityShape == Shape$1.SPHERE) {
  83121. const direction = new Vector3().addVectors(particle.position, new Vector3(0,0,this.radius*2));//向上升?
  83122. const speed = util$1.randomValue(this.speed, this.speedRange);
  83123. particle.velocity = direction.normalize().multiplyScalar(speed);
  83124. }
  83125. particle.acceleration = util$1.randomValue(this.acceleration, this.accelerationRange);
  83126. particle.angle = util$1.randomValue(this.angle, this.angleRange);
  83127. particle.angleVelocity = util$1.randomValue(this.angleVelocity, this.angleVelocityRange);
  83128. particle.angleAcceleration = util$1.randomValue(this.angleAcceleration, this.angleAccelerationRange);
  83129. particle.size = util$1.randomValue(this.size, this.sizeRange);
  83130. const color = util$1.randomVector3(this.color, this.colorRange);
  83131. particle.color = new Color().setHSL(color.x, color.y, color.z);
  83132. particle.opacity = util$1.randomValue(this.opacity, this.opacityRange);
  83133. return particle
  83134. }
  83135. update(dt) {
  83136. if(!Potree.Utils.getObjVisiByReason(this,'force')){//被手动隐藏了
  83137. return
  83138. }
  83139. if(this.delayStartTime>0){ // 爆炸延迟
  83140. return this.delayStartTime -= dt
  83141. }
  83142. if(!Potree.Utils.isInsideFrustum(this.boundingSphere, viewer.scene.getActiveCamera())){
  83143. Potree.Utils.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  83144. return
  83145. }else {
  83146. Potree.Utils.updateVisible(this,'isInsideFrustum', true );
  83147. }
  83148. //const timeRatio = 0.5
  83149. if(dt > 1){
  83150. console.log('update dt>1', dt);
  83151. }
  83152. //dt *= timeRatio
  83153. let particleDeathAge = this.particleDeathAge;/* * timeRatio */
  83154. let particleSpaceTime = this.particleSpaceTime; /* * timeRatio */
  83155. const recycleIndices = [];
  83156. const recycleAges = [];
  83157. const recycleRebornCount = [];
  83158. const positionArray = this.geometry.attributes.position.array;
  83159. const opacityArray = this.geometry.attributes.opacity.array;
  83160. const visibleArray = this.geometry.attributes.visible.array;
  83161. const colorArray = this.geometry.attributes.color.array;
  83162. const angleArray = this.geometry.attributes.angle.array;
  83163. const sizeArray = this.geometry.attributes.size.array;
  83164. for (let i = 0; i < this.particleCount; i++) {
  83165. const particle = this.particles[i];
  83166. if (particle.alive) {
  83167. particle.update(dt);
  83168. if (particle.age > particleDeathAge) {
  83169. particle.alive = 0.0;
  83170. if(particle.rebornCount >= this.recycleTimes){
  83171. particle.deadAge = particle.age - particleDeathAge; //已死亡时间
  83172. }else {//直接循环
  83173. recycleIndices.push(i);
  83174. recycleAges.push(/* ( */particle.age - particleDeathAge/* )%(this.particleDeathAge ) */);
  83175. recycleRebornCount.push(particle.rebornCount+1);
  83176. }
  83177. }
  83178. positionArray[i * 3] = particle.position.x;
  83179. positionArray[i * 3 + 1] = particle.position.y;
  83180. positionArray[i * 3 + 2] = particle.position.z;
  83181. colorArray[i * 3] = particle.color.r;
  83182. colorArray[i * 3 + 1] = particle.color.g;
  83183. colorArray[i * 3 + 2] = particle.color.b;
  83184. visibleArray[i] = particle.alive;
  83185. opacityArray[i] = particle.opacity;
  83186. angleArray[i] = particle.angle;
  83187. sizeArray[i] = particle.size;
  83188. }else {
  83189. if(particle.rebornCount >= this.recycleTimes){
  83190. if(particle.age > particleDeathAge) {//其他已经死亡的粒子的时间继续增加
  83191. particle.deadAge += dt;
  83192. }
  83193. }
  83194. }
  83195. if (particle.rebornCount >= this.recycleTimes && particle.age > particleDeathAge) {//已经死亡
  83196. if(particle.deadAge >= particleSpaceTime){//死亡时间超过设定的间隔时间后重启
  83197. recycleIndices.push(i);
  83198. let wholeTime = particleDeathAge * (this.recycleTimes+1) + particleSpaceTime;
  83199. recycleAges.push((particle.deadAge - particleSpaceTime)% wholeTime ); //剩余时间就是重生后的age
  83200. recycleRebornCount.push(0);
  83201. }
  83202. }
  83203. }
  83204. this.geometry.attributes.size.needsUpdate = true;
  83205. this.geometry.attributes.color.needsUpdate = true;
  83206. this.geometry.attributes.angle.needsUpdate = true;
  83207. this.geometry.attributes.visible.needsUpdate = true;
  83208. this.geometry.attributes.opacity.needsUpdate = true;
  83209. this.geometry.attributes.position.needsUpdate = true;
  83210. if (!this.alive)
  83211. return
  83212. if (this.age < particleDeathAge) {
  83213. let startIndex = Math.round(this.particleCount * (this.age + 0)/ particleDeathAge);
  83214. let endIndex = Math.round(this.particleCount * (this.age + dt)/ particleDeathAge);
  83215. if (endIndex > this.particleCount) {
  83216. endIndex = this.particleCount;
  83217. }
  83218. for (let i = startIndex; i < endIndex; i++) {
  83219. this.particles[i].alive = 1.0;
  83220. }
  83221. }
  83222. for (let j = 0; j < recycleIndices.length; j++) {
  83223. let i = recycleIndices[j];
  83224. this.particles[i] = this.createParticle();
  83225. this.particles[i].alive = 1.0; //出生
  83226. this.particles[i].age = recycleAges[j];
  83227. this.particles[i].rebornCount= recycleRebornCount[j];
  83228. /* if(this.particles[i].age < particleDeathAge){
  83229. positionArray[i * 3] = this.particles[i].position.x
  83230. positionArray[i * 3 + 1] = this.particles[i].position.y
  83231. positionArray[i * 3 + 2] = this.particles[i].position.z
  83232. visibleArray[i] = particle.alive?
  83233. } */
  83234. }
  83235. this.geometry.attributes.position.needsUpdate = true;
  83236. this.age += dt;
  83237. if (this.age > this.deathAge && !this.loop) {
  83238. this.alive = false;
  83239. }
  83240. }
  83241. setSize(e) {
  83242. let viewport = e.viewport;
  83243. this.screenHeight = viewport.resolution.y;
  83244. this.setPerspective(this.fov, this.screenHeight);
  83245. }
  83246. setFov(fov) {
  83247. this.fov = fov;
  83248. this.setPerspective(this.fov, this.screenHeight);
  83249. }
  83250. setPerspective(fov, height) {
  83251. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  83252. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  83253. this.material.uniforms.heightOfNearPlane.value = far;
  83254. }
  83255. updateGeometry(){
  83256. this.computeParams();
  83257. this.reStart();
  83258. }
  83259. dispose(){
  83260. this.geometry.dispose();
  83261. this.material.dispose();
  83262. this.dispatchEvent('dispose');
  83263. }
  83264. }
  83265. const colors$2 = {
  83266. 'fire+smoke':0xffffff,
  83267. 'smoke': 0xffffff,
  83268. 'explode':0xffffff,
  83269. };
  83270. let depthMatPrefix = {
  83271. clipDistance : 100, occlusionDistance:60, /* 变为backColor距离 */
  83272. maxClipFactor:0.5, backColor:"#777" ,
  83273. useDepth:true, transparent: !0,
  83274. };
  83275. let lineMats$2;
  83276. let getLineMat$1 = function(type){
  83277. if(!lineMats$2){
  83278. lineMats$2 = {
  83279. 'fire+smoke':LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83280. color: colors$2['fire+smoke'],
  83281. lineWidth: 2
  83282. })),
  83283. 'smoke' :LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83284. color: colors$2['smoke'],
  83285. lineWidth: 2
  83286. })),
  83287. 'explode' :LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83288. color: colors$2['explode'],
  83289. lineWidth: 2
  83290. })),
  83291. };
  83292. }
  83293. return lineMats$2[type]
  83294. };
  83295. let handleMats;
  83296. let getHandleMat = function(type){
  83297. if(!handleMats){
  83298. let texLoader = new TextureLoader();
  83299. handleMats = {
  83300. "fire+smoke" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83301. map: texLoader.load(Potree.resourcePath+'/textures/icon-fire.png' ),
  83302. color: colors$2['fire+smoke'],
  83303. })),
  83304. "smoke" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83305. map: texLoader.load(Potree.resourcePath+'/textures/icon-smoke.png' ),
  83306. color: colors$2['smoke'],
  83307. })),
  83308. "explode" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83309. map: texLoader.load(Potree.resourcePath+'/textures/icon-explode.png' ),
  83310. color: colors$2['explode'],
  83311. })),
  83312. };
  83313. }
  83314. return handleMats[type]
  83315. };
  83316. let ParticleEditor = {
  83317. bus: new EventDispatcher,
  83318. particleGroup : new Object3D ,
  83319. curveGroup:new Object3D ,
  83320. init:function(){
  83321. this.particleGroup.name = 'particles';
  83322. viewer.scene.scene.add( this.particleGroup );
  83323. this.curveGroup.name = 'particles-curves';
  83324. viewer.scene.scene.add( this.curveGroup );
  83325. },
  83326. addParticle : function(prop={}){
  83327. let particle;
  83328. if(prop.type == 'fire'){
  83329. particle = new FireParticle(prop);
  83330. }else if(prop.type == 'smoke'){
  83331. particle = new SmokeParticle(prop);
  83332. }else if(prop.type == 'explode'){
  83333. particle = new ExplodeParticle(prop);
  83334. }
  83335. this.particleGroup.add(particle);
  83336. return particle
  83337. }
  83338. ,
  83339. removeParticle(particle){
  83340. //particle.dispatchEvent('delete')
  83341. particle.dispose();
  83342. this.particleGroup.remove(particle);
  83343. particle.curve.dispose();
  83344. }
  83345. ,
  83346. update(delta){
  83347. this.particleGroup.children.forEach(e=>e.update(delta));
  83348. }
  83349. ,
  83350. startInsertion(type = 'fire', prop={}){ //viewer.modules.ParticleEditor.startInsertion()
  83351. let deferred = $.Deferred();
  83352. let particles = [];
  83353. let finish = (ifDone)=>{
  83354. if(ifDone){
  83355. deferred.resolve(particles);
  83356. }
  83357. viewer.dispatchEvent({
  83358. type : "CursorChange", action : "remove", name:"addSth"
  83359. });
  83360. viewer.removeEventListener('global_click', click);
  83361. this.bus.removeEventListener('cancel_insertions',cancel);
  83362. };
  83363. let curve = new CurveCtrl([], getLineMat$1(type), colors$2[type], type+'_curve', {handleMat:getHandleMat(type)} );
  83364. this.curveGroup.add(curve);
  83365. prop.curve = curve;
  83366. prop.type = type;
  83367. //console.log('创建curve',type,curve.uuid)
  83368. let cancel = ()=>{
  83369. console.log('cancel_insertions', curve.uuid );
  83370. curve.dispose();
  83371. finish(false);
  83372. };
  83373. this.bus.dispatchEvent('cancel_insertions');//删除旧的
  83374. this.bus.addEventListener('cancel_insertions',cancel);
  83375. var click = (e)=>{
  83376. if(e.button === MOUSE.RIGHT){
  83377. if(curve.points.length>=1){ //if(type.includes('fire') || type.includes('smoke') ){
  83378. particles = this.createFromData(prop);
  83379. finish(true);
  83380. }
  83381. return
  83382. }
  83383. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  83384. if(!I)return
  83385. curve.addPoint(I, null, true);
  83386. if(type == 'explode'){
  83387. particles = this.createFromData(prop);
  83388. finish(true);
  83389. }
  83390. return {stopContinue:true}//防止继续执行别的侦听,如flytopano
  83391. };
  83392. viewer.addEventListener('global_click', click, {importance:10});//add importance
  83393. viewer.dispatchEvent({
  83394. type : "CursorChange", action : "add", name:"addSth"
  83395. });
  83396. return deferred.promise()
  83397. },
  83398. createFromData(prop){
  83399. const type = prop.type;
  83400. var particles = [];
  83401. let curve = prop.curve;
  83402. if(!curve){
  83403. curve = new CurveCtrl(prop.points, getLineMat$1(type), colors$2[type], type+'_curve', {handleMat:getHandleMat(type)} );
  83404. this.curveGroup.add(curve);
  83405. }
  83406. if(type.includes('fire') || type.includes('smoke') ){
  83407. if(type.includes('fire')){
  83408. var fire = this.addParticle({
  83409. type : 'fire',
  83410. positions : curve.points,
  83411. curve,
  83412. radius : prop.radius,
  83413. height: prop.height,
  83414. strength : prop.strength,
  83415. });
  83416. particles.push(fire);
  83417. }
  83418. if(type.includes('smoke')){
  83419. var smoke = this.addParticle({
  83420. type : 'smoke',
  83421. positions : curve.points,
  83422. curve,
  83423. positionStyle : 'sphere' ,
  83424. strength : prop.smokeStrength,
  83425. radius: prop.smokeRadius,
  83426. height: prop.smokeHeight,
  83427. });
  83428. particles.push(smoke);
  83429. }
  83430. }else if(type == 'explode'){
  83431. var explode = this.addParticle({
  83432. type : 'explode',
  83433. position : curve.points[0],
  83434. strength: prop.strength,
  83435. radius : prop.radius,
  83436. particleSpaceTime: prop.particleSpaceTime,
  83437. curve,
  83438. delayStartTime:prop.delayStartTime,
  83439. });
  83440. particles.push(explode);
  83441. }
  83442. curve.addEventListener('dragCurvePoint',()=>{
  83443. Common$1.intervalTool.isWaiting('particlePointChange', ()=>{ //延时update,防止卡顿
  83444. particles.forEach(e=>e.updateGeometry());
  83445. //geoNeedsUpdate = false
  83446. curve.dispatchEvent('sendUpdatePoints');
  83447. }, 400);
  83448. });
  83449. return particles
  83450. }
  83451. };
  83452. let CamAniEditor = {
  83453. createAnimation(data){
  83454. let animation = new CameraAnimation$1(viewer);
  83455. if(data) {
  83456. animation.name = data.name;
  83457. animation.duration = data.duration;
  83458. animation.useDurSlice = data.useDurSlice;
  83459. for(const cpdata of data.points){
  83460. /* const position = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.position, datasetId: Potree.settings.originDatasetId })
  83461. const target = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.target, datasetId: Potree.settings.originDatasetId })
  83462. */
  83463. const position = new Vector3().copy(cpdata.position);
  83464. const target = new Vector3().copy(cpdata.target);
  83465. const duration = cpdata.time;
  83466. const cp = animation.createControlPoint(null, {position, target, duration});
  83467. }
  83468. }
  83469. animation.changeCallback();
  83470. viewer.scene.addCameraAnimation(animation);
  83471. return animation
  83472. },
  83473. removeAnimation(animation){
  83474. animation.dispatchEvent('dispose');
  83475. viewer.scene.removeCameraAnimation(animation);
  83476. }
  83477. };
  83478. const clickPanoToDisLink = false;//是否在编辑漫游点连接时,通过点击漫游点能断开连接
  83479. let images360, Alignment$1, SiteModel$1, suggestCircleMat;
  83480. const texLoader$c = new TextureLoader();
  83481. texLoader$c.crossOrigin = "anonymous";
  83482. const rotQua = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI);
  83483. const lineMats$3 = {};
  83484. const circleMats = {};
  83485. const renderOrders$1 = {
  83486. circleSelected:3,
  83487. circle:2,
  83488. line:1,
  83489. };
  83490. const pointColor = {
  83491. /* selected:"#c80",
  83492. default:'#1ac' */
  83493. selected:"#c60",
  83494. default:'#17c'
  83495. };
  83496. const opacitys = {//点云透明度
  83497. 'topView':{
  83498. default:0.4,
  83499. selected: 0.6
  83500. },
  83501. 'sideView':{//侧面重叠概率高
  83502. default:0.2,
  83503. selected: 0.5
  83504. },
  83505. };//调这么低是因为有的重叠边缘太亮了
  83506. const cameraProps$1 = [
  83507. {
  83508. name : 'top',
  83509. axis:["x","y"],
  83510. direction : new Vector3(0,0,-1), //镜头朝向
  83511. openCount:0,
  83512. },
  83513. {
  83514. name : 'right',
  83515. axis:["y","z"],
  83516. direction : new Vector3(1,0,0),
  83517. openCount:0,
  83518. },
  83519. {
  83520. name : 'mainView',
  83521. openCount:0,
  83522. }
  83523. ];
  83524. class PanoEditor extends EventDispatcher{
  83525. constructor(){
  83526. super();
  83527. this.panoGroup = [], //分组
  83528. this.viewports = {},
  83529. this.panoLink = {},
  83530. this.panoMeshs = new Object3D,
  83531. this.lineMeshes = new Object3D;
  83532. this.views = {};
  83533. this.cameras = {};
  83534. this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  83535. this.orthoCamera.up.set(0,0,1);
  83536. this.selectedPano;
  83537. this.selectedGroup;
  83538. this.operation;
  83539. this.visiblePanos = [];
  83540. this.suggestLines = [];
  83541. }
  83542. init(){
  83543. {//init lineMats
  83544. lineMats$3.default = LineDraw.createFatLineMat({
  83545. color: '#eeeeee',
  83546. lineWidth: 2,
  83547. depthTest:false
  83548. });
  83549. lineMats$3.hovered = LineDraw.createFatLineMat({
  83550. color: '#00c8af',
  83551. lineWidth: 2,
  83552. depthTest:false
  83553. });
  83554. lineMats$3.selected = LineDraw.createFatLineMat({
  83555. color: '#00c8af',
  83556. lineWidth: 3,
  83557. depthTest:false
  83558. });
  83559. lineMats$3.suggestLink = LineDraw.createFatLineMat({
  83560. color: '#ff2222',
  83561. lineWidth: 4, dashed:true,
  83562. depthTest:false
  83563. });
  83564. }
  83565. suggestCircleMat = new MeshBasicMaterial({
  83566. map: texLoader$c.load(Potree.resourcePath+'/textures/whiteCircle.png' ) ,
  83567. color:'#ff2222', transparent:true,
  83568. depthTest:false, depthWrite:false
  83569. });
  83570. this.initViews();
  83571. /* {
  83572. this.box = new BoxVolume({
  83573. clip:true
  83574. })
  83575. this.box.clipTask = ClipTask['SHOW_INSIDE_Big' ]
  83576. this.box.name = "panoEditClipBox";
  83577. } */
  83578. viewer.addEventListener('allLoaded',()=>{
  83579. images360 = viewer.images360;
  83580. Alignment$1 = viewer.modules.Alignment;
  83581. SiteModel$1 = viewer.modules.SiteModel;
  83582. this.panoMeshs.name = 'panoMeshs';
  83583. viewer.scene.scene.add(this.panoMeshs);
  83584. this.lineMeshes.name = 'lineMeshes';
  83585. viewer.scene.scene.add(this.lineMeshes);
  83586. Potree.settings.ifShowMarker = false;
  83587. {
  83588. this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  83589. dontHideWhenFaceCamera: true,
  83590. rotFullCircle:true
  83591. });
  83592. this.transformControls.setSize(1.5);
  83593. viewer.scene.scene.add(this.transformControls);
  83594. this.transformControls._gizmo.hideAxis = {/* translate:['x','y'], */ rotate:['x','y','e'] };
  83595. this.transformControls.setRotateMethod(2);
  83596. this.fakeMarkerForTran = new Mesh(new BoxBufferGeometry(0.3,0.3,0.3) , new MeshBasicMaterial({
  83597. color:"#FFFFFF", opacity:0.4, transparent:true, visible:false
  83598. }));//一个看不见的mesh,只是为了让transformControls移动点云
  83599. viewer.scene.scene.add(this.fakeMarkerForTran);
  83600. let afterMoveCircle = (type)=>{
  83601. if(type == 'position'){
  83602. let moveVec = new Vector3().subVectors(this.fakeMarkerForTran.position, this.fakeMarkerForTran.oldState.position);
  83603. this.selectedClouds.forEach(cloud=>Alignment$1.translate(cloud, moveVec));
  83604. }else {
  83605. let center = this.selectedPano.position;
  83606. let forward = new Vector3(0,1,0);
  83607. let vec1 = forward.clone().applyQuaternion(this.fakeMarkerForTran.oldState.quaternion);
  83608. let vec2 = forward.clone().applyQuaternion(this.fakeMarkerForTran.quaternion);
  83609. let diffAngle = math.getAngle(vec1,vec2,'z');
  83610. this.selectedClouds.forEach(cloud=>{
  83611. Alignment$1.rotateAround(center, cloud, null, diffAngle);
  83612. });
  83613. }
  83614. this.fakeMarkerForTran.oldState = {
  83615. position: this.fakeMarkerForTran.position.clone(),
  83616. quaternion: this.fakeMarkerForTran.quaternion.clone(),
  83617. };
  83618. Alignment$1.history.beforeChange(this.selectedClouds);
  83619. };
  83620. this.fakeMarkerForTran.addEventListener('position_changed', afterMoveCircle.bind(this,'position'));
  83621. this.fakeMarkerForTran.addEventListener("rotation_changed", afterMoveCircle.bind(this,'rotation') );
  83622. this.transformControls.addEventListener('transform_end',()=>{
  83623. Alignment$1.history.afterChange(this.selectedClouds);
  83624. });
  83625. Alignment$1.history.addEventListener('undo',()=>{
  83626. this.updateTranCtl();
  83627. });
  83628. }
  83629. this.initPanoLink();
  83630. this.addPanoMesh();
  83631. viewer.scene.pointclouds.forEach(e=>{
  83632. e.material.color = pointColor.default;
  83633. });
  83634. viewer.setEDLEnabled(true); //为了降一倍的绘制. 同时用描边增强立体感,弥补点云稀疏
  83635. viewer.setEDLRadius(3);
  83636. viewer.setEDLStrength(0.02);
  83637. this.switchView('top');
  83638. {//默认选择一个楼层
  83639. let panoVisiReady, siteModelReady;
  83640. let floorInit = ()=>{
  83641. if(!panoVisiReady || !siteModelReady)return
  83642. setTimeout(()=>{
  83643. if(this.currentFloor == 'all'){//还未选择楼层的话
  83644. let floor = SiteModel$1.entities.find(e=>e.buildType == 'floor' && e.panos.length); //选择有漫游点的一层
  83645. if(!floor){
  83646. floor = 'all'; //SiteModel.entities.find(e=>e.buildType == 'floor')
  83647. console.log('没有一层有漫游点?!');
  83648. }
  83649. console.log('initDataDone');
  83650. console.log('gotoFloor 1');
  83651. this.gotoFloor(floor);
  83652. }
  83653. },1); //2d那边用了nextTick ,so setTimeout here
  83654. };
  83655. SiteModel$1.bus.addEventListener('initDataDone',()=>{
  83656. siteModelReady = true;
  83657. floorInit();
  83658. },{once:true});
  83659. this.addEventListener('panoVisiReady',()=>{//2d初始化完成,才可以由3d修改pano显示 (因为在之前2d会给每个pano传来显示的消息,在这之前的修改都会别覆盖)
  83660. panoVisiReady = true;
  83661. floorInit();
  83662. },{once:true});
  83663. }
  83664. Alignment$1.bus.addEventListener('switchHandle', this.updateCursor.bind(this));
  83665. viewer.addEventListener('global_click',(e)=>{
  83666. if(e.button === MOUSE.RIGHT){//取消旋转和平移
  83667. //console.log('right click',e)
  83668. this.setLinkOperateState('addLink',false);
  83669. this.setLinkOperateState('removeLink',false);
  83670. }else if(this.clickToZoomInEnabled){
  83671. if(this.activeViewName == 'mainView'){
  83672. viewer.controls.zoomToLocation(e.mouse);
  83673. }else {
  83674. this.zoomIn(e.intersect.orthoIntersect, e.pointer);
  83675. }
  83676. this.setZoomInState(false);
  83677. }
  83678. });
  83679. /* {//旋转时的辅助线--绕某个点旋转的版本
  83680. this.rotGuideLine = LineDraw.createLine([], {color:'#aaffee'})
  83681. this.rotGuideLine.visible = false
  83682. this.rotGuideLine.name = 'rotGuideLine'
  83683. this.rotGuideLine.renderOrder = renderOrders.line
  83684. viewer.scene.scene.add(this.rotGuideLine)
  83685. let startPoint
  83686. Alignment.bus.addEventListener('rotateStart', (e)=>{
  83687. startPoint = e.startPoint
  83688. })
  83689. Alignment.bus.addEventListener('rotate', (e)=>{
  83690. LineDraw.updateLine(this.rotGuideLine, [startPoint, e.endPoint] )
  83691. this.rotGuideLine.visible = true
  83692. })
  83693. viewer.fpControls.addEventListener("end",(e)=>{
  83694. startPoint = null
  83695. this.rotGuideLine.visible = false
  83696. })
  83697. } */
  83698. {//连接时的辅助线
  83699. this.linkGuideLine = LineDraw.createLine([], {color:'#ddd', deshed:true, dashSize:0.1,gapSize:0.05, depthTest:false});
  83700. this.linkGuideLine.visible = false;
  83701. this.linkGuideLine.name = 'linkGuideLine';
  83702. viewer.scene.scene.add(this.linkGuideLine);
  83703. this.linkGuideLine.renderOrder = renderOrders$1.line;
  83704. let update = (e)=>{
  83705. if(this.operation != 'addLink' || this.activeViewName != 'top' && this.activeViewName != 'mainView' ||!this.selectedPano){
  83706. return this.linkGuideLine.visible = false
  83707. }
  83708. let endPos;
  83709. if(this.activeViewName == 'top' ){
  83710. endPos = e.intersect.orthoIntersect.clone().setZ(this.selectedPano.position.z);
  83711. }else if(this.activeViewName == 'mainView' ){
  83712. if(!e.intersect || !e.intersect.point)return
  83713. endPos = e.intersect.point.position;
  83714. }
  83715. LineDraw.updateLine(this.linkGuideLine, [this.selectedPano.position, endPos] );
  83716. this.linkGuideLine.visible = true;
  83717. viewer.dispatchEvent('content_changed');
  83718. };
  83719. viewer.addEventListener('global_mousemove', (e)=>{
  83720. update(e);
  83721. });
  83722. //this.addEventListener('updateLinkGuideLine', update)
  83723. }
  83724. /*
  83725. viewer.inputHandler.addEventListener('keydown', (e)=>{
  83726. if(e.event.key == "r" ){
  83727. this.setTranMode('rotate')
  83728. }else if(e.event.key == "t"){
  83729. this.setTranMode('translate')
  83730. }
  83731. }) */
  83732. /* {
  83733. viewer.addEventListener('camera_changed', (e)=>{
  83734. Common.intervalTool.isWaiting('updatePointLevels', ()=>{
  83735. this.updatePointLevels()
  83736. }, 1050)
  83737. })
  83738. setTimeout(()=>{
  83739. this.updatePointLevels()
  83740. }, viewer.scene.pointclouds.length*150) //等待差不多updat出了正确的visibleNode时
  83741. } */
  83742. this.panoReposCallback = ()=>{
  83743. viewer.controls.setTarget(this.selectedPano.position); //3d时绕其为中心转动
  83744. };
  83745. });
  83746. }
  83747. setTranMode(mode){//rotate or translate
  83748. console.log('setTranMode',mode);
  83749. this.tranMode = mode;
  83750. if(this.activeViewName == 'mainView'){
  83751. mode && this.transformControls.setMode(mode);
  83752. this.updateTranCtl();
  83753. }else {
  83754. Alignment$1.switchHandle(mode);
  83755. }
  83756. this.updateIntersectEnable();
  83757. }
  83758. updateIntersectEnable(){
  83759. //侧面容易因intersect卡住, 如果非必要关闭intersect. 3d页面也会卡,但controls需要所以不能去掉
  83760. Potree.settings.intersectWhenHover = !!(this.activeViewName == 'mainView' || this.selectedPano && this.tranMode );
  83761. }
  83762. updateTranCtl(){// 设置3D页面的transformControls相关
  83763. if(!this.tranMode || !this.selectedPano || this.activeViewName != 'mainView' ) {
  83764. return this.transformControls.detach()
  83765. }else if(this.checkIfAllLinked({group:this.selectedGroup})){
  83766. this.dispatchEvent('needToDisConnect');
  83767. return this.transformControls.detach()
  83768. }
  83769. this.transformControls.attach(this.fakeMarkerForTran);
  83770. let {position, quaternion} = this.getPanoPose(this.selectedPano);
  83771. this.fakeMarkerForTran.position.copy(position);
  83772. this.fakeMarkerForTran.quaternion.copy(quaternion);
  83773. this.fakeMarkerForTran.oldState = {
  83774. position: position.clone(),
  83775. quaternion: quaternion.clone(),
  83776. };
  83777. }
  83778. //////////////////////////////////
  83779. initViews(){
  83780. this.splitScreenTool = new SplitScreen;
  83781. this.targetPlane = viewer.mainViewport.targetPlane = new Plane();
  83782. this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  83783. for(let i=0;i<2;i++){
  83784. let prop = cameraProps$1[i];
  83785. let view = new ExtendView();
  83786. this.views[prop.name] = view;
  83787. this.cameras[prop.name] = this.orthoCamera;
  83788. view.name = prop.name;
  83789. view.direction = prop.direction;
  83790. }
  83791. this.views.mainView = viewer.mainViewport.view;
  83792. this.cameras.mainView = viewer.mainViewport.camera;
  83793. }
  83794. switchView(name ){//替换view和camera到mainViewport
  83795. let view = this.views[name];
  83796. let camera = this.cameras[name];
  83797. let prop = cameraProps$1.find(e=>e.name == name);
  83798. let {boundSize, center} = viewer.bound;
  83799. this.lastViewName = this.activeViewName;
  83800. this.activeViewName = name;
  83801. let lastView = this.views[this.lastViewName];
  83802. let lastCamera = this.cameras[this.lastViewName];
  83803. viewer.mainViewport.view = view;
  83804. viewer.mainViewport.camera = camera;
  83805. if(lastCamera)lastView.zoom = lastCamera.zoom;
  83806. this.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), center );
  83807. this.targetPlane.projectPoint(view.position, this.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  83808. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport));
  83809. if(view.zoom)camera.zoom = view.zoom;//恢复上次的zoom
  83810. viewer.updateScreenSize({forceUpdateSize:true});//更新camera aspect left等
  83811. this.updateCursor();
  83812. if(name == 'mainView'){
  83813. viewer.mainViewport.alignment = null;
  83814. let changeMat = ()=>{
  83815. viewer.scene.pointclouds.forEach(e=>{
  83816. e.material.activeAttributeName = 'rgba';
  83817. e.material.useFilterByNormal = false;
  83818. e.changePointOpacity(1 );
  83819. });
  83820. };
  83821. /* if(prop.openCount == 0){ //点数较多时,首次转到3D视角会卡顿,因为要切换材质。
  83822. let delay1 = THREE.Math.clamp(viewer.scene.pointclouds.length*0.5, 1, 200)
  83823. setTimeout(()=>{
  83824. this.activeViewName == 'mainView' && changeMat()
  83825. },delay1)
  83826. //console.log('switchview',delay1 )
  83827. }else{ */
  83828. changeMat();
  83829. //}
  83830. Potree.Utils.updateVisible(viewer.reticule, 'force', true);
  83831. if(lastView){//2d->3d
  83832. view.copy(lastView);
  83833. let direction = view.direction;
  83834. let panos = images360.panos.filter(e=>e.circle.visible);
  83835. let nearestPano = Common$1.sortByScore(panos , [], [(pano)=>{
  83836. let vec = new Vector3().subVectors(pano.position, view.position);
  83837. return -vec.dot(direction);
  83838. }], true);
  83839. //console.log('最近',nearestPano )
  83840. if(nearestPano && nearestPano[0] ){ //尽量不变画面范围,使pano点保持原位,转换到mainView
  83841. let halfHeight = lastCamera.top/lastCamera.zoom;
  83842. let dis = halfHeight / Math.tan( MathUtils.degToRad(camera.fov/2));
  83843. view.position.add(direction.clone().multiplyScalar(-nearestPano[0].score - dis));
  83844. //console.log('getCloser', -nearestPano[0].score - dis)
  83845. this.lastDisToPano = dis; //记录一下
  83846. }
  83847. }
  83848. viewer.fpControls.lockKey = false;
  83849. }else {
  83850. if(this.lastViewName == 'mainView'){//3d->2d
  83851. let direction = lastView.direction;
  83852. let panos = images360.panos.filter(e=>e.circle.visible);
  83853. //尽量靠近画布中心,且距离相机较近
  83854. let nearestPano = Common$1.sortByScore(panos , [], [(pano)=>{
  83855. let vec = new Vector3().subVectors(pano.position, lastView.position);
  83856. let dis = vec.dot(direction);
  83857. return dis < 0 ? dis * 10 : - dis
  83858. },(pano)=>{
  83859. let vec = new Vector3().subVectors(pano.position, lastView.position);
  83860. let angle = vec.angleTo(direction);
  83861. return - angle * 70
  83862. }], true);
  83863. //目前还存在的问题就是不知selectedPano和最近点的取舍
  83864. //console.log('panos',nearestPano )
  83865. if(nearestPano && nearestPano[0] ){
  83866. //console.log('nearestPano',nearestPano[0].item.id )
  83867. let pos1 = nearestPano[0].item.position.clone();
  83868. let pos2 = pos1.clone();
  83869. let dis = new Vector3().subVectors(nearestPano[0].item.position, lastView.position).dot(direction); //-nearestPano[0].score
  83870. //根据2d->3d的式子逆求zoom
  83871. let halfHeight = Math.abs(dis) * Math.tan( MathUtils.degToRad(lastCamera.fov/2));
  83872. camera.zoom = camera.top / halfHeight;
  83873. camera.updateProjectionMatrix();
  83874. if(name == 'right'){//侧视图
  83875. view.direction = direction.clone().setZ(0); //水平方向设定为3d的方向
  83876. this.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), center );
  83877. this.targetPlane.projectPoint(view.position, this.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  83878. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport));
  83879. }
  83880. view.applyToCamera(camera);//update
  83881. pos1.project(lastCamera);
  83882. pos2.project(camera);
  83883. //目标是找到画面上最接近中心的一点(最好是漫游点,不然就是点云),让其在转换画面后在画面上的位置不变。万一找到的点不在屏幕中(比如当屏幕中没点云时),就默认让那个点移动到屏幕中央,也就是假设当前它pos1在屏幕中央位置。
  83884. //
  83885. if(pos1.z>1){
  83886. console.warn('选取的点在相机背后了!?');
  83887. }
  83888. //如果最近点超出屏幕范围 (-1,1), 最好将其拉到边缘,甚至居中 。这样屏幕上就不会没有漫游点了
  83889. let bound = 0.9;
  83890. pos1.x = MathUtils.clamp(pos1.x, -bound, bound);
  83891. pos1.y = MathUtils.clamp(pos1.y, -bound, bound);
  83892. let vecOnscreen = new Vector3().subVectors(pos1,pos2);
  83893. let moveVec = Potree.Utils.getOrthoCameraMoveVec(vecOnscreen, camera );
  83894. //console.log('pos1', pos1)
  83895. view.position.sub(moveVec);
  83896. }
  83897. }else {
  83898. if(prop.openCount == 0){//至多执行一次
  83899. this.viewportFitBound(name, boundSize, center);
  83900. }
  83901. }
  83902. viewer.scene.pointclouds.forEach(e=>{
  83903. e.material.activeAttributeName = 'color';
  83904. e.material.useFilterByNormal = true;
  83905. let opaProp = name == 'top' ? opacitys.topView : opacitys.sideView;
  83906. if(this.selectedPano && this.selectedClouds.includes(e) ){
  83907. e.changePointOpacity(opaProp.selected,true);
  83908. e.material.color = pointColor.selected;
  83909. }else {
  83910. e.changePointOpacity(opaProp.default,true);
  83911. e.material.color = pointColor.default;
  83912. }
  83913. });
  83914. Potree.Utils.updateVisible(viewer.reticule, 'force', false);
  83915. if(name == 'top') viewer.mainViewport.alignment = {rotate:true,translate:true};
  83916. if(name == 'right'){
  83917. viewer.mainViewport.alignment = {translate:true, rotateSide:true, translateVec:new Vector3(0,0,1)}; //只能上下移动
  83918. viewer.mainViewport.rotateSide = true;
  83919. }else {
  83920. viewer.mainViewport.rotateSide = false;
  83921. }
  83922. viewer.fpControls.lockKey = true;
  83923. }
  83924. this.updateTranCtl();
  83925. this.setTranMode(this.tranMode); // update
  83926. this.setZoomInState(false); //取消放大模式
  83927. //this.updatePointLevels()
  83928. this.updateIntersectEnable();
  83929. prop.openCount ++;
  83930. }
  83931. viewportFitBound(){ //使一个viewport聚焦在某个范围
  83932. if(viewer.mainViewport.resolution.x == 0 || viewer.mainViewport.resolution.y == 0){
  83933. return setTimeout(()=>{
  83934. this.viewportFitBound();
  83935. },10)
  83936. }
  83937. this.gotoFloor(this.currentFloor, true, 0, null, true);
  83938. }
  83939. rotateSideCamera(angle){//侧视图绕模型中心水平旋转
  83940. this.splitScreenTool.rotateSideCamera(viewer.mainViewport, angle);
  83941. }
  83942. zoomIn(intersect, pointer){
  83943. let camera = viewer.mainViewport.camera;
  83944. let endZoom = 200;
  83945. //this.orthoMoveFit(intersect, {endZoom:viewer.mainViewport.camera.zoom < aimZoom ? aimZoom : null} , 300)
  83946. let startZoom = camera.zoom;
  83947. if(startZoom >= endZoom){return}
  83948. viewer.mainViewport.view.zoomOrthoCamera(camera, endZoom, pointer, 300);
  83949. }
  83950. orthoMoveFit(pos, info, duration){
  83951. var margin = {x:200, y:230};
  83952. this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin );
  83953. }
  83954. setZoomInState(state, informinformBy2d){//是否点击后可放大
  83955. //if(state && this.activeViewName == 'mainView')return console.log('3D不可放大')
  83956. this.clickToZoomInEnabled = !!state;
  83957. if(state){
  83958. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"zoomInCloud"} );
  83959. }else {
  83960. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"zoomInCloud" });
  83961. }
  83962. if(!state && !informinformBy2d){
  83963. this.dispatchEvent({type:'operationCancel', operation: 'zoomIn'});
  83964. }
  83965. }
  83966. gotoFloor(floor, force, duration = 600, informBy2d, fitBound=true){// 选择不同楼层, 切换点位显示。 'all'为全部显示
  83967. floor = floor || 'all';
  83968. if(this.currentFloor == floor && !force)return
  83969. if(this.currentFloor != floor){//如果楼层没变,不修改可视
  83970. //let pointclouds = viewer.findPointcloudsAtFloor(floor)
  83971. let panos = floor == 'all' ? viewer.images360.panos : floor.panos;
  83972. viewer.images360.panos.forEach(pano=>{
  83973. let v = panos.includes(pano);
  83974. this.switchPanoVisible(pano,v);
  83975. });
  83976. }
  83977. this.updateLinesVisible();
  83978. //切换楼层时清空选择状态
  83979. if(this.selectedPano && floor != 'all' && !floor.panos.includes(this.selectedPano)){
  83980. this.selectedPano.circle.dispatchEvent('click');
  83981. }
  83982. if(this.selectedLine){
  83983. this.selectedLine.dispatchEvent('click');
  83984. }
  83985. let bound, center;
  83986. if(floor == 'all'){
  83987. bound = viewer.images360.bound.bounding;
  83988. center = viewer.images360.bound.center;
  83989. }else {
  83990. bound = this.getPanosBound(floor);
  83991. center = bound.getCenter(new Vector3());
  83992. if(floor.panos.length == 0)console.log(floor.name, 'floor无漫游点' );
  83993. }
  83994. if(this.activeViewName != 'mainView' ){
  83995. fitBound && this.orthoMoveFit(center, {bound}, duration);
  83996. }else if(this.activeViewName == 'mainView'){
  83997. //if(floor != 'all'){ //切换一下位置,因为原处点云会消失
  83998. //viewer.scene.view.setView({position:center, duration })
  83999. viewer.focusOnObject({boundingBox:bound},'boundingBox');
  84000. //}
  84001. }
  84002. this.currentFloor = floor;
  84003. //if(!informBy2d){ //注释原因:2d居然不会自己变
  84004. this.dispatchEvent({type:'changeFloor', floor});
  84005. //}
  84006. }
  84007. getPanosBound(floor){
  84008. if(!floor.panosBound){
  84009. if(floor.panos.length == 0){
  84010. floor.panosBound = viewer.images360.bound.bounding.clone();
  84011. }else {
  84012. let minSize = new Vector3(10,10,10);
  84013. let bound = math.getBoundByPoints(floor.panos.map(e=>e.position), minSize);
  84014. floor.panosBound = bound.bounding;
  84015. }
  84016. }
  84017. return floor.panosBound
  84018. }
  84019. switchPanoVisible(pano, v, informBy2d){
  84020. //console.log(pano.id,v)
  84021. Potree.Utils.updateVisible(pano.circle , 'panoEditor', v);
  84022. Potree.Utils.updateVisible(pano, 'panoEditor', v);
  84023. Potree.Utils.updateVisible(pano.pointcloud, 'panoEditor', v);
  84024. if(v){
  84025. this.visiblePanos.includes(pano) || this.visiblePanos.push(pano);
  84026. }else {
  84027. let index = this.visiblePanos.indexOf(pano);
  84028. index>-1 && this.visiblePanos.splice(index,1);
  84029. }
  84030. if(informBy2d){
  84031. this.dispatchEvent('panoVisiReady');
  84032. this.updateLinesVisible();
  84033. }
  84034. informBy2d || this.dispatchEvent({type:"switchPanoVisible", pano, v});
  84035. /* {
  84036. setTimeout(()=>{
  84037. Common.intervalTool.isWaiting('updatePointLevels2', ()=>{
  84038. this.updatePointLevels()
  84039. }, 50)
  84040. },1)//等update过visibleNodes
  84041. } */
  84042. }
  84043. updateLinesVisible(){
  84044. this.lineMeshes.children.forEach(line=>{
  84045. let names = line.name.split('-');
  84046. var pano0 = images360.getPano(names[0]);
  84047. var pano1 = images360.getPano(names[1]);
  84048. line.visible = this.visiblePanos.includes(pano0) || this.visiblePanos.includes(pano1);
  84049. });
  84050. }
  84051. updateCursor(){
  84052. let cursor;
  84053. if(this.activeViewName == 'mainView' || !this.selectedPano){
  84054. cursor = null;
  84055. }else {
  84056. cursor = Alignment$1.handleState;
  84057. }
  84058. if(cursor == 'rotate'){
  84059. viewer.dispatchEvent({
  84060. type : "CursorChange", action : "add", name:"rotatePointcloud"
  84061. });
  84062. viewer.dispatchEvent({
  84063. type : "CursorChange", action : "remove", name:"movePointcloud"
  84064. });
  84065. }else if(cursor == 'translate'){
  84066. viewer.dispatchEvent({
  84067. type : "CursorChange", action : "add", name:"movePointcloud"
  84068. });
  84069. viewer.dispatchEvent({
  84070. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  84071. });
  84072. }else {
  84073. viewer.dispatchEvent({
  84074. type : "CursorChange", action : "remove", name:"movePointcloud"
  84075. });
  84076. viewer.dispatchEvent({
  84077. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  84078. });
  84079. }
  84080. //this.cursorState = cursor
  84081. }
  84082. setLinkOperateState(name, state, informinformBy2d){
  84083. if(state && name == this.operation || !state && name != this.operation)return
  84084. let old = this.operation;
  84085. this.operation = state ? name : null;
  84086. if(this.operation == 'removeLink'){
  84087. if(this.selectedLine){
  84088. this.selectedLine.dispatchEvent('click');//删除
  84089. }
  84090. if(this.selectedPano && clickPanoToDisLink){
  84091. this.selectedPano.circle.dispatchEvent('click');//删除
  84092. }
  84093. }
  84094. if(this.operation != 'addLink'){
  84095. this.linkGuideLine.visible = false;
  84096. }
  84097. if(!state && !informinformBy2d){
  84098. this.dispatchEvent({type: "operationCancel", operation: old});
  84099. }
  84100. if(this.operation == 'addLink'){
  84101. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"connectPano"} );
  84102. }else {
  84103. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"connectPano"} );
  84104. }
  84105. if(this.operation == 'removeLink'){
  84106. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"disconnectPano"} );
  84107. }else {
  84108. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"disconnectPano"} );
  84109. }
  84110. viewer.dispatchEvent('content_changed');
  84111. }
  84112. /////////////////////////////////
  84113. initPanoLink(){
  84114. images360.panos.forEach((pano)=>{
  84115. this.panoLink[pano.id] = {};
  84116. this.panoGroup.push([pano]);
  84117. });
  84118. images360.panos.forEach((pano)=>{
  84119. pano.visibles.forEach(index=>{//visibles中存的是下标!
  84120. this.linkChange(pano, images360.getPano(index,'index'), 'add');
  84121. });
  84122. });
  84123. //console.log('panoLink',this.panoLink)
  84124. }
  84125. linkChange(pano0, pano1, type){//修改link (type == 'remove'时,pano1可以为空)
  84126. let temp = [];
  84127. if(type == 'add'){
  84128. if(!pano1)return console.error('不支持add时pano1为空')
  84129. this.panoLink[pano0.id][pano1.id] = this.panoLink[pano0.id][pano1.id] || {};
  84130. this.panoLink[pano1.id][pano0.id] = this.panoLink[pano1.id][pano0.id] || {};
  84131. }else {
  84132. if(!pano1){
  84133. for(let id in this.panoLink[pano0.id]){
  84134. if(this.panoLink[pano0.id][id]){
  84135. this.panoLink[id][pano0.id] = false;
  84136. temp.push(id);
  84137. }
  84138. }
  84139. this.panoLink[pano0.id] = {}; //全部断连
  84140. }else {
  84141. this.panoLink[pano0.id][pano1.id] = false;
  84142. this.panoLink[pano1.id][pano0.id] = false;
  84143. }
  84144. }
  84145. if(!pano1){ //全部断连
  84146. temp.forEach(id=>{
  84147. this.lineChange(pano0, images360.getPano(id) , type);
  84148. });
  84149. }else {
  84150. this.lineChange(pano0, pano1, type);
  84151. }
  84152. this.groupChange(pano0, pano1, type);
  84153. //this.updateSelectGroup()
  84154. this.selectPano(this.selectedPano, false,true); //更新选中点云显示
  84155. }
  84156. lineChange(pano0, pano1, type){//修改line
  84157. if(type == 'add'){
  84158. if(this.panoLink[pano0.id][pano1.id].line) return
  84159. let line = LineDraw.createFatLine([pano0.position, pano1.position], {mat:lineMats$3.default});
  84160. line.name = `${pano0.id}-${pano1.id}`;
  84161. line.renderOrder = line.pickOrder = renderOrders$1.line;
  84162. this.lineMeshes.add(line);
  84163. this.panoLink[pano0.id][pano1.id].line = this.panoLink[pano1.id][pano0.id].line = line;
  84164. line.addEventListener('mouseover', ()=>{
  84165. if(this.clickToZoomInEnabled)return
  84166. //if(this.activeViewName == 'mainView')return
  84167. if(this.selectedLine != line)line.material = lineMats$3.hovered;
  84168. viewer.dispatchEvent({
  84169. type : "CursorChange", action : "add", name:"hoverLine"
  84170. });
  84171. });
  84172. line.addEventListener('mouseleave', ()=>{
  84173. if(this.clickToZoomInEnabled)return
  84174. //if(this.activeViewName == 'mainView')return
  84175. if(this.selectedLine != line)line.material = lineMats$3.default;
  84176. viewer.dispatchEvent({
  84177. type : "CursorChange", action : "remove", name:"hoverLine"
  84178. });
  84179. });
  84180. line.addEventListener('click', (e)=>{
  84181. if(this.clickToZoomInEnabled)return
  84182. //if(this.activeViewName == 'mainView')return
  84183. if(this.operation == 'removeLink'){
  84184. if(this.selectedLine == line) this.selectLine(null);
  84185. return this.linkChange(pano0, pano1, 'remove')
  84186. }
  84187. this.selectLine(line);
  84188. });
  84189. }else {
  84190. let line = this.lineMeshes.children.find(e=>e.name == `${pano0.id}-${pano1.id}` || e.name == `${pano1.id}-${pano0.id}` );
  84191. if(line){
  84192. this.lineMeshes.remove(line);
  84193. line.geometry.dispose();
  84194. }
  84195. }
  84196. }
  84197. groupChange(pano0, pano1, type){//修改group (type == 'remove'时,pano1可以为空)
  84198. if(type == 'add'){
  84199. Common$1.pushToGroupAuto([pano0, pano1], this.panoGroup );
  84200. }else {
  84201. let atGroup = this.panoGroup.find(e=>e.includes(pano0) && (e.includes(pano1) || !pano1));//所在组
  84202. if(!atGroup){
  84203. if(pano1){
  84204. console.log('这两个pano原本就不在一个组', pano0.id, pano1.id);
  84205. }else {
  84206. console.log('pano0不在任何组', pano0);
  84207. }
  84208. return
  84209. }
  84210. //断开连接时,因为组内没有其他成员的连接信息,所以需要清除整组,并将剩余的一个个重新连接
  84211. this.panoGroup.splice(this.panoGroup.indexOf(atGroup),1); //删除
  84212. atGroup.forEach(pano=>{//然后再重新生成这两个和组的关系,各自分组
  84213. this.panoGroup.push([pano]);
  84214. for(let id in this.panoLink[pano.id]){
  84215. if(this.panoLink[pano.id][id]){
  84216. let pano_ = images360.getPano(id);
  84217. Common$1.pushToGroupAuto([pano, pano_], this.panoGroup );
  84218. }
  84219. }
  84220. });
  84221. }
  84222. }
  84223. selectLine(line){
  84224. if(this.selectedLine == line)return
  84225. if(this.selectedLine){
  84226. this.selectedLine.material = lineMats$3.default;
  84227. }
  84228. if(line){
  84229. line.material = lineMats$3.selected;
  84230. }
  84231. this.selectedLine = line;
  84232. }
  84233. addPanoMesh(){
  84234. let map = texLoader$c.load(Potree.resourcePath+'/textures/correct_n.png' );
  84235. /* circleMats.default_normal = new THREE.MeshBasicMaterial({
  84236. map,
  84237. color: 0xffffff,
  84238. transparent: true,
  84239. depthTest: false,
  84240. depthWrite: false,
  84241. }) */
  84242. window.circleMats = circleMats;
  84243. circleMats.default_normal = new DepthBasicMaterial({
  84244. map,
  84245. color: 0xffffff,
  84246. transparent: true,
  84247. useDepth:true,
  84248. backColor: 0x33ffdd,
  84249. occlusionDistance: 10,//变为backColor距离
  84250. clipDistance : 5,//消失距离
  84251. maxClipFactor: 0.8,
  84252. maxOcclusionFactor: 0.8,
  84253. });
  84254. circleMats.default_rtk_on = circleMats.default_normal.clone();
  84255. circleMats.default_rtk_on.map = texLoader$c.load(Potree.resourcePath+'/textures/rtk-y-n.png' );
  84256. circleMats.default_rtk_off = circleMats.default_normal.clone();
  84257. circleMats.default_rtk_off.map = texLoader$c.load(Potree.resourcePath+'/textures/rtk-f-n.png' );
  84258. circleMats.selected_normal = circleMats.default_normal.clone();
  84259. circleMats.selected_normal.map = texLoader$c.load(Potree.resourcePath+'/textures/correct_s.png' );
  84260. circleMats.selected_normal.useDepth = false;
  84261. circleMats.selected_rtk_on = circleMats.selected_normal.clone();
  84262. circleMats.selected_rtk_on.map = texLoader$c.load(Potree.resourcePath+'/textures/rtk-y-s.png' );
  84263. circleMats.selected_rtk_off = circleMats.selected_normal.clone();
  84264. circleMats.selected_rtk_off.map = texLoader$c.load(Potree.resourcePath+'/textures/rtk-f-s.png' );
  84265. circleMats.hovered_normal = circleMats.default_normal.clone();
  84266. circleMats.hovered_normal.color.set(0x00ff00);
  84267. circleMats.hovered_normal.useDepth = false;
  84268. circleMats.hovered_rtk_on = circleMats.default_rtk_on.clone();
  84269. circleMats.hovered_rtk_on.color.set(0x00ff00);
  84270. circleMats.hovered_rtk_on.useDepth = false;
  84271. circleMats.hovered_rtk_off = circleMats.default_rtk_off.clone();
  84272. circleMats.hovered_rtk_off.color.set(0x00ff00);
  84273. circleMats.hovered_rtk_off.useDepth = false;
  84274. let setPos = (circle)=>{
  84275. circle.position.copy(circle.pano.position);
  84276. for(let id in this.panoLink[circle.pano.id]){
  84277. let linkInfo = this.panoLink[circle.pano.id][id];
  84278. if(linkInfo){
  84279. LineDraw.updateLine(linkInfo.line, [circle.pano.position, images360.getPano(id).position] );
  84280. }
  84281. }
  84282. circle.waitUpdate(); //update sprite Matrix
  84283. };
  84284. images360.panos.forEach(pano=>{
  84285. var circle = new Sprite$2({mat: circleMats['default' + '_'+ this.getPanoRtkState(pano) ] , sizeInfo:{
  84286. minSize : 50 , maxSize : 120, nearBound : 2, farBound : 10,
  84287. },
  84288. renderOrder : renderOrders$1.circle,
  84289. pickOrder: renderOrders$1.circle
  84290. });
  84291. circle.pickDontCheckDis = true;
  84292. circle.name = 'panoCircle';
  84293. circle.sid = pano.id;
  84294. circle.pano = pano;
  84295. pano.circle = circle;
  84296. this.panoMeshs.add(circle);
  84297. setPos(circle);
  84298. pano.addEventListener('rePos', setPos.bind(this,circle));
  84299. let drag = (e)=>{
  84300. /* if(this.activeViewName == 'mainView' && this.tranMode == 'translate'){//如果3d页不禁止xy的话,这段打开
  84301. this.transformControls.dispatchEvent('dragging')//触发拖拽
  84302. return
  84303. } */
  84304. if(this.tranMode != 'translate' || this.activeViewName == 'mainView')return e.refuse()
  84305. this.selectPano(circle.pano); //为了方便拖拽点云,拖动circle就直接选中
  84306. viewer.inputHandler.drag.object = null; //取消拖拽状态,否则不触发点云拖动
  84307. };
  84308. circle.addEventListener('drag', drag);
  84309. circle.addEventListener('mouseover', ()=>{
  84310. this.hoverPano(pano,true);
  84311. });
  84312. circle.addEventListener('mouseleave', ()=>{
  84313. this.hoverPano(pano,false);
  84314. });
  84315. circle.addEventListener('click', ()=>{
  84316. //if(this.activeViewName == 'mainView')return
  84317. if(this.clickToZoomInEnabled)return
  84318. if(clickPanoToDisLink && this.operation == 'removeLink'){
  84319. this.linkChange(pano, null, 'remove'); //删除所有连接
  84320. }
  84321. if(this.selectedPano == circle.pano) return this.selectPano(null)
  84322. if(this.operation == 'addLink' && this.selectedPano){
  84323. this.linkChange(this.selectedPano, circle.pano, 'add');
  84324. //this.setLinkOperateState('addLink',false)
  84325. return
  84326. }
  84327. //if(this.operation == 'removeLink' && this.selectedPano){ //和选择中心点冲突
  84328. // this.linkChange(this.selectedPano, circle.pano, 'remove')
  84329. // //this.setLinkOperateState('removeLink',false)
  84330. // return
  84331. // }
  84332. this.selectPano(circle.pano);
  84333. });
  84334. });
  84335. }
  84336. hoverPano(pano, state){
  84337. if(this.clickToZoomInEnabled)return
  84338. if(pano && state){ //在hover一个pano之前,一定会先取消已经hover的pano, 最多存在一个hovered的pano
  84339. if(this.hoveredPano == pano)return
  84340. if(this.hoveredPano){
  84341. this.hoverPano(this.hoveredPano,false);
  84342. }
  84343. this.hoveredPano = pano;
  84344. pano.hovered = true;
  84345. if(/* this.activeViewName == 'mainView' || */Alignment$1.handleState && this.selectedPano && this.selectedPano == pano)return
  84346. if(this.operation != 'addLink' || !this.selectedPano || this.selectedPano == pano){ // this.selectedPano == pano?
  84347. viewer.dispatchEvent({
  84348. type : "CursorChange", action : "add", name:"hoverPano"
  84349. });
  84350. }
  84351. if(this.selectedPano != pano) pano.circle.material = circleMats['hovered' + '_'+ this.getPanoRtkState(pano) ];
  84352. }else if(pano && !state){//unhover
  84353. if(this.hoveredPano != pano)return
  84354. pano.hovered = false;
  84355. viewer.dispatchEvent({
  84356. type : "CursorChange", action : "remove", name:"hoverPano"
  84357. });
  84358. if(this.selectedPano != pano) pano.circle.material = circleMats['default' + '_'+ this.getPanoRtkState(pano) ];
  84359. this.hoveredPano = null;
  84360. }else {//unhover any
  84361. if(this.hoveredPano){
  84362. this.hoverPano(this.hoveredPano, false);
  84363. }
  84364. }
  84365. }
  84366. selectPano(pano, informinformBy2d, force){
  84367. if(this.selectedPano == pano && !force)return
  84368. let lastSeletedPano = this.selectedPano;
  84369. let opaProp = this.activeViewName == 'top' ? opacitys.topView : opacitys.sideView;
  84370. if(this.selectedPano){
  84371. this.selectedPano.circle.material = circleMats['default' + '_'+ this.getPanoRtkState(this.selectedPano) ];
  84372. this.selectedPano.circle.renderOrder = renderOrders$1.circle;
  84373. this.selectedPano.removeEventListener('rePos',this.panoReposCallback);
  84374. if(this.activeViewName == 'mainView'){
  84375. }else {
  84376. this.selectedClouds.forEach(e=>{
  84377. e.changePointOpacity(opaProp.default,true);
  84378. e.material.color = pointColor.default;
  84379. });
  84380. }
  84381. }
  84382. this.selectedPano = pano || null;
  84383. this.updateSelectGroup();
  84384. if(pano){
  84385. this.selectedPano.circle.material = circleMats['selected' + '_'+ this.getPanoRtkState(this.selectedPano) ];
  84386. this.selectedPano.circle.renderOrder = this.selectedPano.circle.pickOrder = renderOrders$1.circleSelected; //侧视图能显示在最前
  84387. viewer.controls.setTarget(this.selectedPano.position); //3d时绕其为中心转动
  84388. this.selectedPano.addEventListener('rePos',this.panoReposCallback);
  84389. if(this.activeViewName == 'mainView'){
  84390. }else {
  84391. this.selectedClouds.forEach(e=>{
  84392. e.changePointOpacity(opaProp.selected,true);
  84393. e.material.color = pointColor.selected;
  84394. });
  84395. }
  84396. if(this.currentFloor != 'all'){//如果原本不是展示全部楼层的话,自动切换楼层
  84397. let atFloor = SiteModel$1.entities.find(e=>e.buildType == 'floor' && e.panos.includes(pano));
  84398. if(!atFloor){
  84399. atFloor = 'all';
  84400. }else {
  84401. }
  84402. this.gotoFloor(atFloor, false, 600 );
  84403. }
  84404. }else {
  84405. viewer.controls.setTarget(null);
  84406. }
  84407. this.updateCursor();
  84408. this.updateTranCtl();
  84409. if(informinformBy2d){
  84410. if(this.selectedPano){
  84411. if(this.activeViewName == 'mainView'){ //平移,focus选中的pano
  84412. let distance = this.lastDisToPano || 5;
  84413. if(lastSeletedPano){
  84414. distance = viewer.mainViewport.camera.position.distanceTo(lastSeletedPano.position);
  84415. }
  84416. viewer.focusOnObject({ position:this.selectedPano.position}, 'point', null, {distance });
  84417. }else {
  84418. this.orthoMoveFit(this.selectedPano.position, {}, 500);
  84419. }
  84420. }
  84421. }else {
  84422. this.dispatchEvent({type:'panoSelect', pano });
  84423. }
  84424. this.updateIntersectEnable();
  84425. viewer.dispatchEvent('content_changed');
  84426. }
  84427. /* updatePointLevels(){
  84428. if(this.pauseUpdateLevels)return
  84429. let maxBudget = Potree.config.pointDensity.panoEdit.pointBudget
  84430. let visiCount1 = viewer.scene.pointclouds.filter(e=>e.visible).length
  84431. let visiCount2 = viewer.scene.pointclouds.filter(e=>e.visibleNodes.length>0).length //屏幕范围内可见的个数
  84432. let maxCount = 200, minCount = 1, minPer = 0.45 , maxPer = 1
  84433. let percent1 = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount1 - minCount) / (maxCount - minCount),0,1)
  84434. let percent2 = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount2 - minCount) / (maxCount - minCount),0,1)
  84435. let percent = percent1*percent2
  84436. if(this.activeViewName == 'mainView' ){
  84437. //假设每个pointcloud所带的点个数大致相同,那么当可见点云个数越多,所能展示的level越低,否则因总个数超过budget的话密度会参差不齐。
  84438. //pointcloud.changePointSize()
  84439. //console.log('updatePointLevels', percent, visiCount)
  84440. Potree.settings.UserDensityPercent = Math.sqrt(percent2)
  84441. viewer.setPointBudget(maxBudget * percent2)
  84442. }else{
  84443. Potree.settings.UserDensityPercent = 1
  84444. viewer.setPointBudget(maxBudget * percent)
  84445. }
  84446. viewer.setPointBudget(maxBudget * percent)
  84447. viewer.setPointLevels()
  84448. //侧面容易卡顿,但和显示的点数无关,似乎是因加载点云多而卡?为何正面不会
  84449. //console.warn('setPointBudget', Potree.pointBudget, visiCount1,visiCount2, Potree.settings.UserDensityPercent)
  84450. } */
  84451. getPanoRtkState(pano){
  84452. return pano.panosData.has_rtk ? pano.rtkState ? 'rtk_on' : 'rtk_off' : 'normal'
  84453. }
  84454. setPanoRtkState(pano,state){
  84455. pano.rtkState = state;
  84456. pano.circle.material = circleMats[(this.selectedPano == pano ? 'selected' : 'default') + '_'+ this.getPanoRtkState(pano) ];
  84457. }
  84458. updateSelectGroup(){//更新选中的组
  84459. this.selectedGroup = this.panoGroup.find(e=>e.includes(this.selectedPano));
  84460. if(this.selectedGroup){
  84461. this.selectedGroup = [this.selectedPano, ...this.selectedGroup.filter(e=>e != this.selectedPano)];//将选中的放第一个,便于旋转时绕其旋转。
  84462. }
  84463. //this.selectedClouds = this.selectedPano ? (this.selectedGroup || [this.selectedPano]).map(e=>e.pointcloud) : []
  84464. this.selectedClouds = this.selectedPano ? this.selectedGroup.map(e=>e.pointcloud) : [];
  84465. }
  84466. checkIfCanSave(){//如果未全部相连,不能保存
  84467. for(let datasetId in Potree.settings.datasetsPanos ) {
  84468. if(!this.checkIfAllLinked({datasetId})){
  84469. console.log('没有全部连通,不能保存。其中一个:', datasetId);
  84470. return
  84471. }
  84472. }
  84473. return true
  84474. }
  84475. checkIfAllLinked(o){//某个(or组所在的)数据集是否全部连通
  84476. let datasetId, group;
  84477. if(o.group){
  84478. group = o.group;
  84479. let pano = o.group[0];
  84480. if(!pano)return //会有没有漫游点的点云来编辑吗
  84481. datasetId = pano.pointcloud.dataset_id;
  84482. }else if(o.datasetId){
  84483. datasetId = o.datasetId;
  84484. group = this.panoGroup.find(panos=>panos[0].pointcloud.dataset_id == datasetId );
  84485. if(!group)return //要找的数据集的pano全部都孤立了
  84486. }
  84487. if(datasetId == void 0)return
  84488. let panos = Potree.settings.datasetsPanos[datasetId].panos;
  84489. return panos.length == group.length
  84490. }
  84491. getSuggestLinkPanos(){//给出建议连接的点
  84492. let panos = [];
  84493. let startTime = Date.now();
  84494. for(let datasetId in Potree.settings.datasetsPanos ) {
  84495. if(!this.checkIfAllLinked({datasetId})){
  84496. let groups = this.panoGroup.filter(panos=>panos[0].pointcloud.dataset_id == datasetId );
  84497. groups = groups.sort((a,b)=>{return b.length - a.length});//找出个数最多的一组来连接其他组
  84498. let mainGroup = groups[0].slice(), subGroup;
  84499. for(let i=1,len=groups.length;i<len;i++){
  84500. subGroup = groups[i];
  84501. let minDis = {dis:Infinity, panos:[]};
  84502. for(let a=0, len1=mainGroup.length; a<len1; a++){
  84503. for(let b=0, len2=subGroup.length; b<len2; b++){
  84504. let dis = mainGroup[a].position.distanceToSquared(subGroup[b].position);
  84505. if(dis<minDis.dis){
  84506. minDis.dis = dis; minDis.panos = [mainGroup[a], subGroup[b]];
  84507. }
  84508. }
  84509. }
  84510. panos.push(minDis.panos);
  84511. //console.log('第i次',minDis)
  84512. mainGroup.push(...subGroup);//连接后,加入集合
  84513. }
  84514. }
  84515. }
  84516. //console.log('cost', Date.now() - startTime)
  84517. return panos
  84518. }
  84519. showSuggestLinkPanos(){
  84520. let groups = this.getSuggestLinkPanos();
  84521. let s = 0.7;
  84522. let createCircle = (pano)=>{
  84523. let circle = new Mesh(pano.circle.geometry, suggestCircleMat);
  84524. circle.name = 'suggest-circle';
  84525. circle.scale.set(s,s,s);
  84526. circle.renderOrder = 100;
  84527. pano.circle.add(circle);
  84528. };
  84529. groups.forEach(panos=>{
  84530. createCircle(panos[0]);
  84531. createCircle(panos[1]);
  84532. let line = LineDraw.createFatLine([panos[0].position, panos[1].position], {mat: lineMats$3.suggestLink});
  84533. this.suggestLines.push(line);
  84534. line.renderOrder = renderOrders$1.line;
  84535. viewer.scene.scene.add(line);
  84536. });
  84537. }
  84538. getPanoPose(pano){
  84539. let pose = {
  84540. position: pano.position.clone(),
  84541. quaternion: new Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua) ,
  84542. };
  84543. return pose
  84544. }
  84545. exportSavingData(){//输出漫游点新的坐标和朝向、以及连接信息
  84546. let sweepLocations = {};
  84547. for(let datasetId in Potree.settings.datasetsPanos ) {
  84548. let {panos} = Potree.settings.datasetsPanos[datasetId];
  84549. let data = panos.map(pano=>{
  84550. let visibles = [];
  84551. for(let id in this.panoLink[pano.id]){
  84552. if(this.panoLink[pano.id][id]){
  84553. visibles.push(viewer.images360.getPano(id).index);
  84554. }
  84555. }
  84556. let {position, quaternion} = this.getPanoPose(pano);
  84557. return Object.assign({}, pano.panosData, {
  84558. uuid: pano.uuid,
  84559. /* pose:{
  84560. translation: dealData(pano.position.clone() ),
  84561. rotation: dealData(new THREE.Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua) ),
  84562. }, */
  84563. pose : {
  84564. translation : dealData(position),
  84565. rotation : dealData(quaternion)
  84566. },
  84567. visibles,
  84568. use_rtk : !!pano.rtkState
  84569. //subgroup: 0,group: 1, "id_view":..
  84570. })
  84571. });
  84572. sweepLocations[datasetId] = {sweepLocations:data};
  84573. }
  84574. /* this.lineMeshes.children.forEach(e=>{//从line中搜集连接信息,而不从linkInfo,这样visibles不会重复一次
  84575. let names = e.name.split('-') //是不是该转成数字
  84576. var pano0 = names[0]
  84577. var pano1 = names[1]
  84578. sweepLocations.find(s=>s.uuid == pano0).visibles.push(pano1)
  84579. }) */
  84580. function dealData(value){
  84581. let v = math.toPrecision(value, 6);
  84582. if(v instanceof Quaternion){
  84583. return {x:v.x, y:v.y, z:v.z, w:v.w}
  84584. }else if(v instanceof Vector3){
  84585. return {x:v.x, y:v.y, z:v.z}
  84586. }
  84587. }
  84588. //console.log(sweepLocations)
  84589. return sweepLocations
  84590. }
  84591. }
  84592. /*
  84593. 不同数据集之间不能连线
  84594. 不同楼层可能也不能
  84595. 如果楼层在不同建筑物怎么办? 楼层切换按钮只能在一个建筑内切换。
  84596. 全部相连时不能移动和旋转
  84597. 如果未全部相连,不能保存
  84598. */
  84599. var PanoEditor$1 = new PanoEditor();
  84600. const texLoader$d = new TextureLoader();
  84601. const circleGeo = new CircleGeometry(1.45,100);
  84602. const sphereGeo$1 = new SphereBufferGeometry(0.008,8,8);
  84603. const magDisMin = 1;//相机离目标位置的距离的分界线,当离得远时要缩小fov以使看到的视野固定(望远镜效果)
  84604. const magDisMax = 20;
  84605. /* const radius_ = 0.2; //当相机离目标位置的距离>magDistance_时,希望看到的视野的半径
  84606. const maxFov = THREE.Math.radToDeg(Math.atan(radius_ / magDisMin )) * 2//提前计算出当相机离目标位置的距离<magDisMin时的fov,均使用=magDisMin时的fov。只要保证该fov大于主相机的fov就会有放大效果
  84607. */
  84608. let w$1 = 230/1.43;
  84609. let maxPX = 1366*1024; //ipad pro. 大于这个分辨率的就直接用devicePixelRatio, 如macbook也是
  84610. const 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); //触屏或高分辨率的可能要放大些。但在手机上不能太大
  84611. //console.log('width2dPX', width2dPX)
  84612. const orthoView = new ExtendView();
  84613. class Magnifier extends Object3D {//放大镜or望远镜
  84614. constructor (viewer) {
  84615. super();
  84616. this.width = this.height = width2dPX/* * window.devicePixelRatio */;
  84617. this.camera = new PerspectiveCamera(50, 1, 0.01, 10000); //fov aspect near far
  84618. this.camera.up = new Vector3(0,0,1);
  84619. this.viewport = new Viewport( null, this.camera, {
  84620. left:0, bottom:0, width:1, height: 1, name:'magnifier' , cameraLayers:['magnifierContent'],
  84621. pixelRatio:1
  84622. });
  84623. this.viewport.setResolution(this.width, this.height,0,0);
  84624. {
  84625. let density;
  84626. let sizeType;
  84627. let colorType;
  84628. let opacityBefore = new Map();
  84629. let visiMap = new Map();
  84630. this.viewport.beforeRender = ()=>{
  84631. viewer.scene.pointclouds.forEach(e=>{//因为更改pointDensity时会自动变opacity,所以这项最先获取
  84632. visiMap.set(e,e.visible);
  84633. e.visible = Potree.Utils.getObjVisiByReason(e, 'datasetSelection'); //先将隐藏的点云显示
  84634. opacityBefore.set(e,e.temp.pointOpacity);
  84635. });
  84636. //使放大镜里的pointDensity是'magnifier' 最高质量。
  84637. density = Potree.settings.pointDensity;
  84638. Potree.settings.pointDensity = 'magnifier';
  84639. viewer.scene.pointclouds.forEach(e=>{//因为全景模式的pointSizeType是fixed所以要还原下
  84640. sizeType = e.material.pointSizeType;
  84641. e.material.pointSizeType = Potree.config.material.pointSizeType;
  84642. //材质
  84643. colorType = e.material.activeAttributeName;
  84644. e.material.activeAttributeName = 'rgba';
  84645. e.changePointOpacity(1);
  84646. });
  84647. };
  84648. this.viewport.afterRender = ()=>{
  84649. Potree.settings.pointDensity = density;
  84650. viewer.scene.pointclouds.forEach(e=>{
  84651. e.visible = visiMap.get(e);
  84652. e.material.pointSizeType = sizeType;
  84653. e.material.activeAttributeName = colorType;
  84654. e.changePointOpacity(opacityBefore.get(e));
  84655. });
  84656. };
  84657. }
  84658. this.renderTarget = new WebGLRenderTarget(this.width,this.height, {
  84659. minFilter: LinearFilter, magFilter: LinearFilter,
  84660. format: RGBAFormat ,
  84661. /* type: THREE.FloatType,
  84662. minFilter: THREE.NearestFilter,
  84663. magFilter: THREE.NearestFilter,
  84664. */
  84665. } );
  84666. this.rtEDL = new WebGLRenderTarget(this.width, this.height, { //好像没用到? 因为这里不绘制测量线
  84667. minFilter: NearestFilter,
  84668. magFilter: NearestFilter,
  84669. format: RGBAFormat,
  84670. type: FloatType,
  84671. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  84672. });
  84673. this.mesh = new Mesh(circleGeo, new MeshBasicMaterial({
  84674. side: DoubleSide ,
  84675. map: this.renderTarget.texture ,
  84676. transparent:true,
  84677. depthTest: !1,
  84678. //depthWrite: !1,
  84679. }));
  84680. this.overlayMesh = new Mesh(circleGeo, new MeshBasicMaterial({
  84681. side: DoubleSide ,
  84682. map:texLoader$d.load(Potree.resourcePath+'/textures/crosshair.png') ,
  84683. transparent:true,
  84684. depthTest: !1,
  84685. //depthWrite: !1,
  84686. }));
  84687. this.targetPoint = new Object3D;
  84688. this.targetPoint.add(new Mesh(sphereGeo$1, new MeshBasicMaterial({
  84689. color:"#ff0000",
  84690. transparent:true,
  84691. opacity:0.7,
  84692. })));
  84693. this.targetPoint.add(new Mesh(sphereGeo$1, new MeshBasicMaterial({
  84694. color:"#ff0000",
  84695. transparent:true,
  84696. opacity:0.3,
  84697. depthTest:false //被遮挡层
  84698. })));
  84699. this.targetPoint.name = 'magnifierPointTarget';
  84700. viewer.scene.scene.add(this.targetPoint);
  84701. Potree.Utils.setObjectLayers(this.targetPoint, 'magnifierContent' );
  84702. this.add(this.mesh);
  84703. this.add(this.overlayMesh);
  84704. this.position.set(-1000,-1000,-100000);//令它看不见
  84705. this.mesh.renderOrder = 10;
  84706. this.overlayMesh.renderOrder = 11;
  84707. this.aimPos;
  84708. Potree.Utils.setObjectLayers(this, 'magnifier' );
  84709. //viewer.inputHandler.addInputListener(this)
  84710. viewer.addEventListener('camera_changed',(e)=>{ // 平移、滚轮时更新
  84711. if(e.viewport == viewer.mainViewport) this.update(); //不过intersectPoint没更新
  84712. });
  84713. this.mesh.layers.set(Potree.config.renderLayers.magnifier);
  84714. this.overlayMesh.layers.set(Potree.config.renderLayers.magnifier);
  84715. //this.layers.set(Potree.config.renderLayers.magnifier);//这句在外层写没用
  84716. this.dontRender = false;
  84717. viewer.addEventListener('global_drag', (e)=>{//拖拽时不渲染。主要是右键平移时渲染延迟了,会闪烁。
  84718. this.dontRender = true;
  84719. });
  84720. viewer.addEventListener('global_drop', (e)=>{
  84721. this.dontRender = false;
  84722. });
  84723. viewer.addEventListener('global_mouseup', (e)=>{//测量时拖拽场景再mouseup
  84724. this.dontRender = false;
  84725. });
  84726. var updateVisi = (e)=>{
  84727. if(e.hoverViewport == viewer.mainViewport){
  84728. Potree.Utils.updateVisible(this,"atViewport", true);
  84729. this.update(e.intersect && e.intersect.location);
  84730. }else {
  84731. Potree.Utils.updateVisible(this,"atViewport", false); //小地图不显示
  84732. }
  84733. };
  84734. viewer.addEventListener('global_mousemove', updateVisi);
  84735. viewer.addEventListener('global_touchstart', updateVisi);
  84736. viewer.addEventListener('updateMagnifier', updateVisi);
  84737. /* viewer.addEventListener("beginSplitView",()=>{
  84738. this.updateVisible("splitView", false)
  84739. })
  84740. viewer.addEventListener("finishSplitView",()=>{
  84741. this.updateVisible("splitView", true)
  84742. }) */
  84743. this.addEventListener("setEnable",(e)=>{
  84744. Potree.Utils.updateVisible(this, "enable", e.value); //界面开关
  84745. /* if(Potree.settings.displayMode == 'showPanos') && e.value){
  84746. Potree.settings.pointDensity = 'magnifier'
  84747. }else if() */
  84748. viewer.dispatchEvent('content_changed');
  84749. });
  84750. if(Potree.settings.isOfficial){
  84751. Potree.Utils.updateVisible(this, "enable", false);
  84752. }else {
  84753. Potree.Utils.updateVisible(this, "measure", false);
  84754. viewer.addEventListener("measureMovePoint",()=>{//测量开始
  84755. //Potree.Utils.updateVisible(this, "measure", true)
  84756. });
  84757. viewer.addEventListener("endMeasureMove",()=>{
  84758. Potree.Utils.updateVisible(this, "measure", false);
  84759. viewer.dispatchEvent('content_changed');
  84760. });
  84761. }
  84762. viewer.scene.view.addEventListener('flyingDone',()=>{
  84763. if(!this.visible)return
  84764. let pickWindowSize = 100;
  84765. let intersect = viewer.inputHandler.getIntersect({viewport:viewer.mainViewport, usePointcloud:true, pickWindowSize} );
  84766. this.update(intersect && intersect.location);
  84767. });
  84768. }
  84769. //注意:在鼠标没有移动的时候,无法获取到最新的intersect, 放大镜内的内容可能是错误的。全景模式下更奇怪,原因未知
  84770. update(aimPos){//相机靠近 navvis的做法
  84771. var dontRender = this.dontRender || !(aimPos instanceof Vector3) || Potree.settings.displayMode == 'showPanos' && viewer.images360.flying;
  84772. aimPos = aimPos instanceof Vector3 ? aimPos : this.aimPos;
  84773. if(!aimPos || !this.visible)return
  84774. var playerCamera = viewer.scene.getActiveCamera();
  84775. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  84776. var dis = playerPos.distanceTo(aimPos);
  84777. var dirToCamera = new Vector3().subVectors(playerPos, aimPos ).normalize();
  84778. const fareast = 300;
  84779. //相机位置
  84780. if(playerCamera.type == 'OrthographicCamera'){
  84781. var finalDisToAim = 2;
  84782. }else {
  84783. var finalDisToAim = dis>magDisMin ? dis > fareast ? magDisMax : (dis-magDisMin) / (fareast-magDisMin) * (magDisMax-magDisMin) + magDisMin : dis / 2; //dis>magDistance_ ? magDistance_ : dis / 2;
  84784. }
  84785. this.camera.fov = playerCamera.type == 'OrthographicCamera' ? 30 : playerCamera.fov / 2;
  84786. this.camera.updateProjectionMatrix();
  84787. if(playerCamera.type == 'OrthographicCamera'){
  84788. orthoView.position.copy(aimPos).sub(viewer.mainViewport.view.direction.multiplyScalar(finalDisToAim));
  84789. orthoView.yaw = viewer.mainViewport.view.yaw;
  84790. orthoView.pitch = viewer.mainViewport.view.pitch;
  84791. orthoView.applyToCamera(this.camera);
  84792. }else {
  84793. this.camera.position.copy(aimPos).add(dirToCamera.multiplyScalar(finalDisToAim));
  84794. this.camera.lookAt(aimPos);
  84795. }
  84796. //自身位置
  84797. //let pos2d = viewer.inputHandler.pointer.clone(); //跟随鼠标
  84798. let pos2d = Potree.Utils.getPos2d(aimPos, viewer.mainViewport, viewer.renderArea).vector; //更新目标点的实时二维位置
  84799. let margin = 0.4, maxY = 0.4;
  84800. let screenPos = pos2d.clone().setY(pos2d.y + (pos2d.y>maxY ? -margin : margin ));
  84801. let newPos = new Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  84802. if(playerCamera.type != 'OrthographicCamera'){
  84803. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  84804. this.position.copy(playerPos.clone().add(dir));
  84805. }else {
  84806. viewer.navCubeViewer.splitScreen.setShiftTarget(viewer.mainViewport, viewer.bound.center);
  84807. viewer.mainViewport.targetPlane.setFromNormalAndCoplanarPoint( viewer.mainViewport.view.direction.clone(), viewer.bound.center );
  84808. viewer.mainViewport.targetPlane.projectPoint(newPos, viewer.mainViewport.shiftTarget );
  84809. this.position.copy(viewer.mainViewport.shiftTarget.clone() );
  84810. //this.position.copy(playerPos.clone().add(dir))
  84811. }
  84812. let s = finalDisToAim * this.camera.fov / 30;
  84813. this.quaternion.copy(playerCamera.quaternion);
  84814. this.targetPoint.position.copy(aimPos);
  84815. this.targetPoint.scale.set(s,s,s);
  84816. this.aimPos = aimPos;
  84817. var scale = math.getScaleForConstantSize({//
  84818. width2d : width2dPX,
  84819. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new Vector3()),
  84820. resolution: viewer.mainViewport.resolution2
  84821. });
  84822. this.scale.set(scale, scale, scale);
  84823. if(!dontRender){
  84824. this.waitRender = true;
  84825. }
  84826. viewer.dispatchEvent('content_changed');
  84827. }
  84828. /* update(aimPos){ //仅改fov的版本
  84829. aimPos = aimPos instanceof THREE.Vector3 ? aimPos : this.aimPos
  84830. if(!aimPos || !this.visible)return
  84831. //相机位置
  84832. var playerCamera = viewer.scene.getActiveCamera()
  84833. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  84834. var dis = playerPos.distanceTo(aimPos);
  84835. if(dis<magDisMin){
  84836. this.camera.fov = maxFov
  84837. }else{
  84838. this.camera.fov = THREE.Math.radToDeg(Math.atan(radius_ / dis )) * 2 //radius_是能看到的范围半径。当dis大于magDisMin时就放大,否则维持fov为maxFov
  84839. }
  84840. this.camera.updateProjectionMatrix()
  84841. this.camera.position.copy(playerPos)
  84842. this.camera.lookAt(aimPos)
  84843. this.quaternion.copy(playerCamera.quaternion);
  84844. let pointer = viewer.inputHandler.pointer.clone();
  84845. let margin = 0.4, maxY = 0.4
  84846. let screenPos = pointer.clone().setY(pointer.y + (pointer.y>maxY ? -margin : margin ))
  84847. let newPos = new THREE.Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  84848. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  84849. this.position.copy(playerPos.clone().add(dir))
  84850. this.aimPos = aimPos
  84851. this.targetPoint.position.copy(aimPos);
  84852. var scale = math.getScaleForConstantSize({//
  84853. width2d : width2dPX,
  84854. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new THREE.Vector3()),
  84855. resolution: viewer.mainViewport.resolution2
  84856. })
  84857. this.scale.set(scale, scale, scale);
  84858. if(!this.dontRender){
  84859. this.waitRender = true
  84860. }
  84861. }//位置需要计算,不仅仅是点云,所以需要深度图
  84862. */
  84863. render(){
  84864. if(!this.visible || !this.waitRender && !viewer.needRender)return //viewer.needRender为true要渲染是因为可能是点云node加载完
  84865. viewer.render({
  84866. target : this.renderTarget,
  84867. viewports : [this.viewport],
  84868. camera : this.camera,
  84869. magnifier : true,
  84870. rtEDL: this.rtEDL
  84871. /* width :this.renderTarget.width,
  84872. height: this.renderTarget.height, */
  84873. });
  84874. this.waitRender = false;
  84875. viewer.dispatchEvent('content_changed');
  84876. }
  84877. }
  84878. let texLoader$e = new TextureLoader();
  84879. let defaultOpacity = 0.6;
  84880. let Buttons$2 = Potree.defines.Buttons;
  84881. //鼠标指示小圆片
  84882. class Reticule extends Mesh{
  84883. constructor(viewer){
  84884. var defaultTex = texLoader$e.load(Potree.resourcePath+'/textures/whiteCircle.png'/* reticule-256x256.png' */);
  84885. super(new PlaneBufferGeometry(0.11,0.11,1,1),new MeshBasicMaterial({
  84886. side: DoubleSide ,
  84887. map: defaultTex,
  84888. transparent:true,
  84889. depthTest: !1,
  84890. opacity: defaultOpacity,
  84891. //depthWrite: !1,
  84892. }));
  84893. this.name = 'reticule';
  84894. this.defaultTex = defaultTex;
  84895. this.crosshairTex = texLoader$e.load(Potree.resourcePath+'/textures/reticule_cross_hair.png');
  84896. this.forbitTex = texLoader$e.load(Potree.resourcePath+'/textures/pic-forbid.png');
  84897. this.defaultTex.anisotropy = 4;
  84898. this.crosshairTex.anisotropy = 4;
  84899. this.forbitTex.anisotropy = 4;
  84900. //this.layers.set(0/* RenderLayers.RETICULE */);
  84901. this.renderOrder = 100;
  84902. this.layers.set(Potree.config.renderLayers.marker);
  84903. this.direction = new Vector3;
  84904. this.mouseLastMoveTime = Date.now();
  84905. this.hoverViewport;
  84906. this.matrixMap = new Map;
  84907. this.matrixAutoUpdate = false;
  84908. this.hide(0);
  84909. //viewer.inputHandler.addInputListener(this);
  84910. Potree.settings.intersectWhenHover && viewer.addEventListener('global_mousemove',this.move.bind(this));
  84911. //viewer.addEventListener('global_click',this.move.bind(this))
  84912. viewer.addEventListener('global_mousedown',this.move.bind(this));//主要针对触屏
  84913. this.state = {};
  84914. let startCrossStyle = ()=>{
  84915. this.state.cross = true;
  84916. this.judgeTex();
  84917. };
  84918. let endCrossStyle = ()=>{
  84919. this.state.cross = false;
  84920. this.judgeTex();
  84921. };
  84922. viewer.addEventListener('measureMovePoint',startCrossStyle);
  84923. viewer.addEventListener('endMeasureMove',endCrossStyle);
  84924. viewer.addEventListener('start_inserting_tag',startCrossStyle);
  84925. viewer.addEventListener('endTagMove',endCrossStyle);
  84926. viewer.addEventListener('reticule_forbit',(e)=>{
  84927. if(this.state.forbit != e.v){
  84928. console.log('change forbit ',e.v);
  84929. }
  84930. this.state.forbit = e.v;
  84931. this.judgeTex();
  84932. });
  84933. Potree.Utils.setObjectLayers(this, 'sceneObjects' );
  84934. }
  84935. judgeTex(){
  84936. if(this.state.forbit){
  84937. this.material.map = this.forbitTex;
  84938. }else if(this.state.cross){
  84939. this.material.map = this.crosshairTex;
  84940. }else {
  84941. this.material.map = this.defaultTex;
  84942. }
  84943. viewer.mapViewer && viewer.mapViewer.dispatchEvent({type:'content_changed'});
  84944. }
  84945. move(e){
  84946. if(e.type == "global_mousemove" && (e.isTouch || e.buttons != Buttons$2.NONE) && !this.state.cross){
  84947. return//按下时不更新,除非拖拽测量
  84948. }
  84949. this.mouseLastMoveTime = Date.now();
  84950. this.updatePosition(e.intersect, e.hoverViewport);
  84951. }
  84952. hide(duration = 500){
  84953. if(this.hidden)return
  84954. this.hidden = !0;
  84955. transitions.start(lerp.property(this.material , "opacity", 0, ()=>{//progress
  84956. this.dispatchEvent({type:'update' });
  84957. //viewer.dispatchEvent('content_changed')
  84958. }), duration,()=>{//done
  84959. this.dispatchEvent({type:'update', visible:false});
  84960. });
  84961. this.dispatchEvent({type:'update', visible:false});
  84962. setTimeout(()=>{
  84963. },duration);
  84964. }
  84965. show(duration = 300){
  84966. if(!Potree.Utils.getObjVisiByReason(this, 'force'))return
  84967. //console.log("show Reticule")
  84968. this.hidden = !1;
  84969. if(this.material.opacity <= 0){
  84970. transitions.start(lerp.property(this.material, "opacity", defaultOpacity, ()=>{//progress
  84971. this.dispatchEvent({type:'update' });
  84972. //viewer.dispatchEvent('content_changed')
  84973. }), duration,()=>{//done
  84974. this.dispatchEvent({type:'update', visible:false});
  84975. });
  84976. this.dispatchEvent({type:'update', visible:true});
  84977. }
  84978. }
  84979. //鼠标静止一段时间它就会消失
  84980. updateVisible(){
  84981. Date.now() - this.mouseLastMoveTime > 1500 && !this.hidden && this.hide();
  84982. }
  84983. updateScale(viewport){
  84984. let s, camera = viewport.camera;
  84985. if(camera.type == "OrthographicCamera"){
  84986. var sizeInfo = this.state.cross ? {width2d:500} : {minSize : 100, maxSize : 400, nearBound : 100 , farBound : 700};
  84987. s = math.getScaleForConstantSize($.extend( sizeInfo ,
  84988. {position:this.position, camera, resolution:viewport.resolution/* 2 */} ));
  84989. }else {
  84990. let n = camera.position.distanceTo(this.position);
  84991. if( n < 1 ){
  84992. if(this.state.cross ){ //测量时更精细些
  84993. s = 0.7 * n;
  84994. }else {
  84995. s = 1.1 * n;
  84996. }
  84997. }else {
  84998. if(this.state.cross ){
  84999. s = 0.4 + 0.3 * n; //n乘以的系数越高,其越不近大远小(大小越恒定)
  85000. }else {
  85001. s = 1 + 0.1 * n;
  85002. }
  85003. }
  85004. if(this.state.cross ){ //测量时更精细些
  85005. s /= viewer.images360.zoomLevel;
  85006. }
  85007. }
  85008. this.scale.set(s, s, s);
  85009. }
  85010. updateAtViewports(viewport){//当多个viewports时更新。更新大小等
  85011. if(viewport.name == 'magnifier' )return
  85012. if(this.orthoPos && this.hoverViewport && this.hoverViewport.name == 'mapViewport' && viewport != this.hoverViewport){
  85013. //若是在地图上更新,在其他viewport要隐藏。因为在地图上无法得知高度。
  85014. Potree.Utils.updateVisible(this, 'hoverMap', false);
  85015. return;
  85016. }
  85017. Potree.Utils.updateVisible(this, 'hoverMap', true);
  85018. if(viewport.name == 'mapViewport'){
  85019. Potree.Utils.setObjectLayers(this, "bothMapAndScene");
  85020. }else {//通常地图不显示reticule,只有在特殊编辑时才显示
  85021. Potree.Utils.setObjectLayers(this, 'sceneObjects');
  85022. }
  85023. var matrix = this.matrixMap.get(viewport);
  85024. if(!matrix){
  85025. this.updateScale(viewport);
  85026. this.updateMatrix();
  85027. //this.updateMatrixWorld()
  85028. this.matrixMap.set(viewport, this.matrix.clone());
  85029. }else {
  85030. this.matrix.copy(matrix);
  85031. //this.updateMatrixWorld()
  85032. }
  85033. }
  85034. updatePosition(intersect, viewport ){ //在地图(当地图融合到viewer时)和场景里都显示且完全相同(大小可能不同)
  85035. if (Potree.Utils.getObjVisiByReason(this, 'force')) {//没有被强制隐藏,如进入某个页面后强制不显示
  85036. if (!intersect /* || !intersect.point.normal */){
  85037. return //this.hide();
  85038. }
  85039. var atMap = !intersect.location;
  85040. let location = intersect.location || intersect.orthoIntersect.clone();
  85041. let normal;
  85042. this.orthoPos = atMap;
  85043. //地图上要瞬间变化 , 因为要使needRender为true很麻烦
  85044. this.show(atMap ? 0 : 300);
  85045. if(atMap){
  85046. normal = new Vector3(0,0,1);//地图无normal
  85047. location.setZ(0);//低于相机高度即可
  85048. this.direction = normal.clone();
  85049. }else {
  85050. /* if(intersect.point){
  85051. if(intersect.pointcloud){
  85052. normal = new THREE.Vector3().fromArray(intersect.point.normal ).applyMatrix4( intersect.pointcloud.rotateMatrix );
  85053. }else{//mesh
  85054. normal = new THREE.Vector3().copy(intersect.point.normal).applyQuaternion(intersect.object.quaternion)
  85055. }
  85056. }else{
  85057. normal = intersect.normal //when showPanos
  85058. } */
  85059. normal = intersect.normal;
  85060. if(normal){
  85061. let ratio = /* Potree.settings.useDepthTex ? 1 : */ 0.2;
  85062. this.direction = this.direction.multiplyScalar(1-ratio);
  85063. this.direction.add(normal.clone().multiplyScalar(ratio));
  85064. }
  85065. //this.direction = normal.clone() //改为瞬间变化,否则刚hover上某个点时看起来不太对
  85066. }
  85067. this.position.copy(location);/* .add(normal.clone().multiplyScalar(.01)); */
  85068. this.updateMatrix(); //lookAt之前要保证得到matrix
  85069. this.lookAt(this.position.clone().add(this.direction));
  85070. this.hoverViewport = viewport; //记录下最近一次hover过的viewport
  85071. this.updateScale(viewport);
  85072. {//存储matrix,节省计算
  85073. this.updateMatrix();
  85074. //this.updateMatrixWorld()
  85075. this.matrixMap.clear();//重新计算
  85076. this.matrixMap.set(viewport, this.matrix.clone());
  85077. //别处会updateMatrixWorld
  85078. }
  85079. this.dispatchEvent({type:'update'});
  85080. //为什么navvis在校准数据集时每个viewport里reticule的朝向都刚好垂直于屏幕,似乎限定在了一定范围内,还是在pick时就只pick范围内的点?
  85081. }
  85082. }
  85083. //navvis在地图等地方看reticule是有厚度的
  85084. /* updateMatrixWorld(force){
  85085. console.log('updateMatrixWorld', force)
  85086. super.updateMatrixWorld(force)
  85087. } */
  85088. }
  85089. var OBJLoader = ( function () {
  85090. // o object_name | g group_name
  85091. var object_pattern = /^[og]\s*(.+)?/;
  85092. // mtllib file_reference
  85093. var material_library_pattern = /^mtllib /;
  85094. // usemtl material_name
  85095. var material_use_pattern = /^usemtl /;
  85096. // usemap map_name
  85097. var map_use_pattern = /^usemap /;
  85098. var vA = new Vector3();
  85099. var vB = new Vector3();
  85100. var vC = new Vector3();
  85101. var ab = new Vector3();
  85102. var cb = new Vector3();
  85103. function ParserState() {
  85104. var state = {
  85105. objects: [],
  85106. object: {},
  85107. vertices: [],
  85108. normals: [],
  85109. colors: [],
  85110. uvs: [],
  85111. materials: {},
  85112. materialLibraries: [],
  85113. startObject: function ( name, fromDeclaration ) {
  85114. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  85115. // file. We need to use it for the first parsed g/o to keep things in sync.
  85116. if ( this.object && this.object.fromDeclaration === false ) {
  85117. this.object.name = name;
  85118. this.object.fromDeclaration = ( fromDeclaration !== false );
  85119. return;
  85120. }
  85121. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  85122. if ( this.object && typeof this.object._finalize === 'function' ) {
  85123. this.object._finalize( true );
  85124. }
  85125. this.object = {
  85126. name: name || '',
  85127. fromDeclaration: ( fromDeclaration !== false ),
  85128. geometry: {
  85129. vertices: [],
  85130. normals: [],
  85131. colors: [],
  85132. uvs: [],
  85133. hasUVIndices: false
  85134. },
  85135. materials: [],
  85136. smooth: true,
  85137. startMaterial: function ( name, libraries ) {
  85138. var previous = this._finalize( false );
  85139. // New usemtl declaration overwrites an inherited material, except if faces were declared
  85140. // after the material, then it must be preserved for proper MultiMaterial continuation.
  85141. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  85142. this.materials.splice( previous.index, 1 );
  85143. }
  85144. var material = {
  85145. index: this.materials.length,
  85146. name: name || '',
  85147. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  85148. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  85149. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  85150. groupEnd: - 1,
  85151. groupCount: - 1,
  85152. inherited: false,
  85153. clone: function ( index ) {
  85154. var cloned = {
  85155. index: ( typeof index === 'number' ? index : this.index ),
  85156. name: this.name,
  85157. mtllib: this.mtllib,
  85158. smooth: this.smooth,
  85159. groupStart: 0,
  85160. groupEnd: - 1,
  85161. groupCount: - 1,
  85162. inherited: false
  85163. };
  85164. cloned.clone = this.clone.bind( cloned );
  85165. return cloned;
  85166. }
  85167. };
  85168. this.materials.push( material );
  85169. return material;
  85170. },
  85171. currentMaterial: function () {
  85172. if ( this.materials.length > 0 ) {
  85173. return this.materials[ this.materials.length - 1 ];
  85174. }
  85175. return undefined;
  85176. },
  85177. _finalize: function ( end ) {
  85178. var lastMultiMaterial = this.currentMaterial();
  85179. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  85180. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  85181. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  85182. lastMultiMaterial.inherited = false;
  85183. }
  85184. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  85185. if ( end && this.materials.length > 1 ) {
  85186. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  85187. if ( this.materials[ mi ].groupCount <= 0 ) {
  85188. this.materials.splice( mi, 1 );
  85189. }
  85190. }
  85191. }
  85192. // Guarantee at least one empty material, this makes the creation later more straight forward.
  85193. if ( end && this.materials.length === 0 ) {
  85194. this.materials.push( {
  85195. name: '',
  85196. smooth: this.smooth
  85197. } );
  85198. }
  85199. return lastMultiMaterial;
  85200. }
  85201. };
  85202. // Inherit previous objects material.
  85203. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  85204. // If a usemtl declaration is encountered while this new object is being parsed, it will
  85205. // overwrite the inherited material. Exception being that there was already face declarations
  85206. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  85207. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  85208. var declared = previousMaterial.clone( 0 );
  85209. declared.inherited = true;
  85210. this.object.materials.push( declared );
  85211. }
  85212. this.objects.push( this.object );
  85213. },
  85214. finalize: function () {
  85215. if ( this.object && typeof this.object._finalize === 'function' ) {
  85216. this.object._finalize( true );
  85217. }
  85218. },
  85219. parseVertexIndex: function ( value, len ) {
  85220. var index = parseInt( value, 10 );
  85221. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  85222. },
  85223. parseNormalIndex: function ( value, len ) {
  85224. var index = parseInt( value, 10 );
  85225. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  85226. },
  85227. parseUVIndex: function ( value, len ) {
  85228. var index = parseInt( value, 10 );
  85229. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  85230. },
  85231. addVertex: function ( a, b, c ) {
  85232. var src = this.vertices;
  85233. var dst = this.object.geometry.vertices;
  85234. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  85235. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  85236. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  85237. },
  85238. addVertexPoint: function ( a ) {
  85239. var src = this.vertices;
  85240. var dst = this.object.geometry.vertices;
  85241. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  85242. },
  85243. addVertexLine: function ( a ) {
  85244. var src = this.vertices;
  85245. var dst = this.object.geometry.vertices;
  85246. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  85247. },
  85248. addNormal: function ( a, b, c ) {
  85249. var src = this.normals;
  85250. var dst = this.object.geometry.normals;
  85251. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  85252. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  85253. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  85254. },
  85255. addFaceNormal: function ( a, b, c ) {
  85256. var src = this.vertices;
  85257. var dst = this.object.geometry.normals;
  85258. vA.fromArray( src, a );
  85259. vB.fromArray( src, b );
  85260. vC.fromArray( src, c );
  85261. cb.subVectors( vC, vB );
  85262. ab.subVectors( vA, vB );
  85263. cb.cross( ab );
  85264. cb.normalize();
  85265. dst.push( cb.x, cb.y, cb.z );
  85266. dst.push( cb.x, cb.y, cb.z );
  85267. dst.push( cb.x, cb.y, cb.z );
  85268. },
  85269. addColor: function ( a, b, c ) {
  85270. var src = this.colors;
  85271. var dst = this.object.geometry.colors;
  85272. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  85273. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  85274. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  85275. },
  85276. addUV: function ( a, b, c ) {
  85277. var src = this.uvs;
  85278. var dst = this.object.geometry.uvs;
  85279. dst.push( src[ a + 0 ], src[ a + 1 ] );
  85280. dst.push( src[ b + 0 ], src[ b + 1 ] );
  85281. dst.push( src[ c + 0 ], src[ c + 1 ] );
  85282. },
  85283. addDefaultUV: function () {
  85284. var dst = this.object.geometry.uvs;
  85285. dst.push( 0, 0 );
  85286. dst.push( 0, 0 );
  85287. dst.push( 0, 0 );
  85288. },
  85289. addUVLine: function ( a ) {
  85290. var src = this.uvs;
  85291. var dst = this.object.geometry.uvs;
  85292. dst.push( src[ a + 0 ], src[ a + 1 ] );
  85293. },
  85294. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  85295. var vLen = this.vertices.length;
  85296. var ia = this.parseVertexIndex( a, vLen );
  85297. var ib = this.parseVertexIndex( b, vLen );
  85298. var ic = this.parseVertexIndex( c, vLen );
  85299. this.addVertex( ia, ib, ic );
  85300. this.addColor( ia, ib, ic );
  85301. // normals
  85302. if ( na !== undefined && na !== '' ) {
  85303. var nLen = this.normals.length;
  85304. ia = this.parseNormalIndex( na, nLen );
  85305. ib = this.parseNormalIndex( nb, nLen );
  85306. ic = this.parseNormalIndex( nc, nLen );
  85307. this.addNormal( ia, ib, ic );
  85308. } else {
  85309. this.addFaceNormal( ia, ib, ic );
  85310. }
  85311. // uvs
  85312. if ( ua !== undefined && ua !== '' ) {
  85313. var uvLen = this.uvs.length;
  85314. ia = this.parseUVIndex( ua, uvLen );
  85315. ib = this.parseUVIndex( ub, uvLen );
  85316. ic = this.parseUVIndex( uc, uvLen );
  85317. this.addUV( ia, ib, ic );
  85318. this.object.geometry.hasUVIndices = true;
  85319. } else {
  85320. // add placeholder values (for inconsistent face definitions)
  85321. this.addDefaultUV();
  85322. }
  85323. },
  85324. addPointGeometry: function ( vertices ) {
  85325. this.object.geometry.type = 'Points';
  85326. var vLen = this.vertices.length;
  85327. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  85328. var index = this.parseVertexIndex( vertices[ vi ], vLen );
  85329. this.addVertexPoint( index );
  85330. this.addColor( index );
  85331. }
  85332. },
  85333. addLineGeometry: function ( vertices, uvs ) {
  85334. this.object.geometry.type = 'Line';
  85335. var vLen = this.vertices.length;
  85336. var uvLen = this.uvs.length;
  85337. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  85338. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  85339. }
  85340. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  85341. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  85342. }
  85343. }
  85344. };
  85345. state.startObject( '', false );
  85346. return state;
  85347. }
  85348. //
  85349. function OBJLoader( manager ) {
  85350. Loader.call( this, manager );
  85351. this.materials = null;
  85352. }
  85353. OBJLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  85354. constructor: OBJLoader,
  85355. load: function ( url, onLoad, onProgress, onError ) {
  85356. var scope = this;
  85357. var loader = new FileLoader( this.manager );
  85358. loader.setPath( this.path );
  85359. loader.setRequestHeader( this.requestHeader );
  85360. loader.setWithCredentials( this.withCredentials );
  85361. loader.load( url, function ( text , total ) {// xzw add total
  85362. try {
  85363. onLoad( scope.parse( text ) , total );
  85364. } catch ( e ) {
  85365. if ( onError ) {
  85366. onError( e );
  85367. } else {
  85368. console.error( e );
  85369. }
  85370. scope.manager.itemError( url );
  85371. }
  85372. }, onProgress, onError );
  85373. },
  85374. setMaterials: function ( materials ) {
  85375. this.materials = materials;
  85376. return this;
  85377. },
  85378. parse: function ( text ) {
  85379. var state = new ParserState();
  85380. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  85381. // This is faster than String.split with regex that splits on both
  85382. text = text.replace( /\r\n/g, '\n' );
  85383. }
  85384. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  85385. // join lines separated by a line continuation character (\)
  85386. text = text.replace( /\\\n/g, '' );
  85387. }
  85388. var lines = text.split( '\n' );
  85389. var line = '', lineFirstChar = '';
  85390. var lineLength = 0;
  85391. var result = [];
  85392. // Faster to just trim left side of the line. Use if available.
  85393. var trimLeft = ( typeof ''.trimLeft === 'function' );
  85394. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  85395. line = lines[ i ];
  85396. line = trimLeft ? line.trimLeft() : line.trim();
  85397. lineLength = line.length;
  85398. if ( lineLength === 0 ) continue;
  85399. lineFirstChar = line.charAt( 0 );
  85400. // @todo invoke passed in handler if any
  85401. if ( lineFirstChar === '#' ) continue;
  85402. if ( lineFirstChar === 'v' ) {
  85403. var data = line.split( /\s+/ );
  85404. switch ( data[ 0 ] ) {
  85405. case 'v':
  85406. state.vertices.push(
  85407. parseFloat( data[ 1 ] ),
  85408. parseFloat( data[ 2 ] ),
  85409. parseFloat( data[ 3 ] )
  85410. );
  85411. if ( data.length >= 7 ) {
  85412. state.colors.push(
  85413. parseFloat( data[ 4 ] ),
  85414. parseFloat( data[ 5 ] ),
  85415. parseFloat( data[ 6 ] )
  85416. );
  85417. } else {
  85418. // if no colors are defined, add placeholders so color and vertex indices match
  85419. state.colors.push( undefined, undefined, undefined );
  85420. }
  85421. break;
  85422. case 'vn':
  85423. state.normals.push(
  85424. parseFloat( data[ 1 ] ),
  85425. parseFloat( data[ 2 ] ),
  85426. parseFloat( data[ 3 ] )
  85427. );
  85428. break;
  85429. case 'vt':
  85430. state.uvs.push(
  85431. parseFloat( data[ 1 ] ),
  85432. parseFloat( data[ 2 ] )
  85433. );
  85434. break;
  85435. }
  85436. } else if ( lineFirstChar === 'f' ) {
  85437. var lineData = line.substr( 1 ).trim();
  85438. var vertexData = lineData.split( /\s+/ );
  85439. var faceVertices = [];
  85440. // Parse the face vertex data into an easy to work with format
  85441. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  85442. var vertex = vertexData[ j ];
  85443. if ( vertex.length > 0 ) {
  85444. var vertexParts = vertex.split( '/' );
  85445. faceVertices.push( vertexParts );
  85446. }
  85447. }
  85448. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  85449. var v1 = faceVertices[ 0 ];
  85450. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  85451. var v2 = faceVertices[ j ];
  85452. var v3 = faceVertices[ j + 1 ];
  85453. state.addFace(
  85454. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  85455. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  85456. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  85457. );
  85458. }
  85459. } else if ( lineFirstChar === 'l' ) {
  85460. var lineParts = line.substring( 1 ).trim().split( ' ' );
  85461. var lineVertices = [], lineUVs = [];
  85462. if ( line.indexOf( '/' ) === - 1 ) {
  85463. lineVertices = lineParts;
  85464. } else {
  85465. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  85466. var parts = lineParts[ li ].split( '/' );
  85467. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  85468. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  85469. }
  85470. }
  85471. state.addLineGeometry( lineVertices, lineUVs );
  85472. } else if ( lineFirstChar === 'p' ) {
  85473. var lineData = line.substr( 1 ).trim();
  85474. var pointData = lineData.split( ' ' );
  85475. state.addPointGeometry( pointData );
  85476. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  85477. // o object_name
  85478. // or
  85479. // g group_name
  85480. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  85481. // var name = result[ 0 ].substr( 1 ).trim();
  85482. var name = ( ' ' + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  85483. state.startObject( name );
  85484. } else if ( material_use_pattern.test( line ) ) {
  85485. // material
  85486. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  85487. } else if ( material_library_pattern.test( line ) ) {
  85488. // mtl file
  85489. state.materialLibraries.push( line.substring( 7 ).trim() );
  85490. } else if ( map_use_pattern.test( line ) ) {
  85491. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  85492. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  85493. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  85494. } else if ( lineFirstChar === 's' ) {
  85495. result = line.split( ' ' );
  85496. // smooth shading
  85497. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  85498. // but does not define a usemtl for each face set.
  85499. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  85500. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  85501. // where explicit usemtl defines geometry groups.
  85502. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  85503. /*
  85504. * http://paulbourke.net/dataformats/obj/
  85505. * or
  85506. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  85507. *
  85508. * From chapter "Grouping" Syntax explanation "s group_number":
  85509. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  85510. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  85511. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  85512. * than 0."
  85513. */
  85514. if ( result.length > 1 ) {
  85515. var value = result[ 1 ].trim().toLowerCase();
  85516. state.object.smooth = ( value !== '0' && value !== 'off' );
  85517. } else {
  85518. // ZBrush can produce "s" lines #11707
  85519. state.object.smooth = true;
  85520. }
  85521. var material = state.object.currentMaterial();
  85522. if ( material ) material.smooth = state.object.smooth;
  85523. } else {
  85524. // Handle null terminated files without exception
  85525. if ( line === '\0' ) continue;
  85526. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  85527. }
  85528. }
  85529. state.finalize();
  85530. var container = new Group();
  85531. container.materialLibraries = [].concat( state.materialLibraries );
  85532. var hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  85533. if ( hasPrimitives === true ) {
  85534. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  85535. var object = state.objects[ i ];
  85536. var geometry = object.geometry;
  85537. var materials = object.materials;
  85538. var isLine = ( geometry.type === 'Line' );
  85539. var isPoints = ( geometry.type === 'Points' );
  85540. var hasVertexColors = false;
  85541. // Skip o/g line declarations that did not follow with any faces
  85542. if ( geometry.vertices.length === 0 ) continue;
  85543. var buffergeometry = new BufferGeometry();
  85544. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) );
  85545. if ( geometry.normals.length > 0 ) {
  85546. buffergeometry.setAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) );
  85547. }
  85548. if ( geometry.colors.length > 0 ) {
  85549. hasVertexColors = true;
  85550. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) );
  85551. }
  85552. if ( geometry.hasUVIndices === true ) {
  85553. buffergeometry.setAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) );
  85554. }
  85555. // Create materials
  85556. var createdMaterials = [];
  85557. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  85558. var sourceMaterial = materials[ mi ];
  85559. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  85560. var material = state.materials[ materialHash ];
  85561. if ( this.materials !== null ) {
  85562. material = this.materials.create( sourceMaterial.name );
  85563. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  85564. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) {
  85565. var materialLine = new LineBasicMaterial();
  85566. Material.prototype.copy.call( materialLine, material );
  85567. materialLine.color.copy( material.color );
  85568. material = materialLine;
  85569. } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) {
  85570. var materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } );
  85571. Material.prototype.copy.call( materialPoints, material );
  85572. materialPoints.color.copy( material.color );
  85573. materialPoints.map = material.map;
  85574. material = materialPoints;
  85575. }
  85576. }
  85577. if ( material === undefined ) {
  85578. if ( isLine ) {
  85579. material = new LineBasicMaterial();
  85580. } else if ( isPoints ) {
  85581. material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  85582. } else {
  85583. material = new MeshPhongMaterial();
  85584. }
  85585. material.name = sourceMaterial.name;
  85586. material.flatShading = sourceMaterial.smooth ? false : true;
  85587. material.vertexColors = hasVertexColors;
  85588. state.materials[ materialHash ] = material;
  85589. }
  85590. createdMaterials.push( material );
  85591. }
  85592. // Create mesh
  85593. var mesh;
  85594. if ( createdMaterials.length > 1 ) {
  85595. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  85596. var sourceMaterial = materials[ mi ];
  85597. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  85598. }
  85599. if ( isLine ) {
  85600. mesh = new LineSegments( buffergeometry, createdMaterials );
  85601. } else if ( isPoints ) {
  85602. mesh = new Points( buffergeometry, createdMaterials );
  85603. } else {
  85604. mesh = new Mesh( buffergeometry, createdMaterials );
  85605. }
  85606. } else {
  85607. if ( isLine ) {
  85608. mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] );
  85609. } else if ( isPoints ) {
  85610. mesh = new Points( buffergeometry, createdMaterials[ 0 ] );
  85611. } else {
  85612. mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] );
  85613. }
  85614. }
  85615. mesh.name = object.name;
  85616. container.add( mesh );
  85617. }
  85618. } else {
  85619. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  85620. if ( state.vertices.length > 0 ) {
  85621. var material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  85622. var buffergeometry = new BufferGeometry();
  85623. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( state.vertices, 3 ) );
  85624. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  85625. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( state.colors, 3 ) );
  85626. material.vertexColors = true;
  85627. }
  85628. var points = new Points( buffergeometry, material );
  85629. container.add( points );
  85630. }
  85631. }
  85632. return container;
  85633. }
  85634. } );
  85635. return OBJLoader;
  85636. } )();
  85637. /**
  85638. * Loads a Wavefront .mtl file specifying materials
  85639. */
  85640. var MTLLoader = function ( manager ) {
  85641. Loader.call( this, manager );
  85642. };
  85643. MTLLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  85644. constructor: MTLLoader,
  85645. /**
  85646. * Loads and parses a MTL asset from a URL.
  85647. *
  85648. * @param {String} url - URL to the MTL file.
  85649. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  85650. * @param {Function} [onProgress] - Callback for download progress.
  85651. * @param {Function} [onError] - Callback for download errors.
  85652. *
  85653. * @see setPath setResourcePath
  85654. *
  85655. * @note In order for relative texture references to resolve correctly
  85656. * you must call setResourcePath() explicitly prior to load.
  85657. */
  85658. load: function ( url, onLoad, onProgress, onError ) {
  85659. var scope = this;
  85660. var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  85661. var loader = new FileLoader( this.manager );
  85662. loader.setPath( this.path );
  85663. loader.setRequestHeader( this.requestHeader );
  85664. loader.setWithCredentials( this.withCredentials );
  85665. loader.load( url, function ( text ) {
  85666. try {
  85667. onLoad( scope.parse( text, path ) );
  85668. } catch ( e ) {
  85669. if ( onError ) {
  85670. onError( e );
  85671. } else {
  85672. console.error( e );
  85673. }
  85674. scope.manager.itemError( url );
  85675. }
  85676. }, onProgress, onError );
  85677. },
  85678. setMaterialOptions: function ( value ) {
  85679. this.materialOptions = value;
  85680. return this;
  85681. },
  85682. /**
  85683. * Parses a MTL file.
  85684. *
  85685. * @param {String} text - Content of MTL file
  85686. * @return {MTLLoader.MaterialCreator}
  85687. *
  85688. * @see setPath setResourcePath
  85689. *
  85690. * @note In order for relative texture references to resolve correctly
  85691. * you must call setResourcePath() explicitly prior to parse.
  85692. */
  85693. parse: function ( text, path ) {
  85694. var lines = text.split( '\n' );
  85695. var info = {};
  85696. var delimiter_pattern = /\s+/;
  85697. var materialsInfo = {};
  85698. for ( var i = 0; i < lines.length; i ++ ) {
  85699. var line = lines[ i ];
  85700. line = line.trim();
  85701. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  85702. // Blank line or comment ignore
  85703. continue;
  85704. }
  85705. var pos = line.indexOf( ' ' );
  85706. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  85707. key = key.toLowerCase();
  85708. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  85709. value = value.trim();
  85710. if ( key === 'newmtl' ) {
  85711. // New material
  85712. info = { name: value };
  85713. materialsInfo[ value ] = info;
  85714. } else {
  85715. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  85716. var ss = value.split( delimiter_pattern, 3 );
  85717. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  85718. } else {
  85719. info[ key ] = value;
  85720. }
  85721. }
  85722. }
  85723. var materialCreator = new MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  85724. materialCreator.setCrossOrigin( this.crossOrigin );
  85725. materialCreator.setManager( this.manager );
  85726. materialCreator.setMaterials( materialsInfo );
  85727. return materialCreator;
  85728. }
  85729. } );
  85730. /**
  85731. * Create a new MTLLoader.MaterialCreator
  85732. * @param baseUrl - Url relative to which textures are loaded
  85733. * @param options - Set of options on how to construct the materials
  85734. * side: Which side to apply the material
  85735. * FrontSide (default), THREE.BackSide, THREE.DoubleSide
  85736. * wrap: What type of wrapping to apply for textures
  85737. * RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  85738. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  85739. * Default: false, assumed to be already normalized
  85740. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  85741. * Default: false
  85742. * @constructor
  85743. */
  85744. MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  85745. this.baseUrl = baseUrl || '';
  85746. this.options = options;
  85747. this.materialsInfo = {};
  85748. this.materials = {};
  85749. this.materialsArray = [];
  85750. this.nameLookup = {};
  85751. this.side = ( this.options && this.options.side ) ? this.options.side : FrontSide;
  85752. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : RepeatWrapping;
  85753. };
  85754. MTLLoader.MaterialCreator.prototype = {
  85755. constructor: MTLLoader.MaterialCreator,
  85756. crossOrigin: 'anonymous',
  85757. setCrossOrigin: function ( value ) {
  85758. this.crossOrigin = value;
  85759. return this;
  85760. },
  85761. setManager: function ( value ) {
  85762. this.manager = value;
  85763. },
  85764. setMaterials: function ( materialsInfo ) {
  85765. this.materialsInfo = this.convert( materialsInfo );
  85766. this.materials = {};
  85767. this.materialsArray = [];
  85768. this.nameLookup = {};
  85769. },
  85770. convert: function ( materialsInfo ) {
  85771. if ( ! this.options ) return materialsInfo;
  85772. var converted = {};
  85773. for ( var mn in materialsInfo ) {
  85774. // Convert materials info into normalized form based on options
  85775. var mat = materialsInfo[ mn ];
  85776. var covmat = {};
  85777. converted[ mn ] = covmat;
  85778. for ( var prop in mat ) {
  85779. var save = true;
  85780. var value = mat[ prop ];
  85781. var lprop = prop.toLowerCase();
  85782. switch ( lprop ) {
  85783. case 'kd':
  85784. case 'ka':
  85785. case 'ks':
  85786. // Diffuse color (color under white light) using RGB values
  85787. if ( this.options && this.options.normalizeRGB ) {
  85788. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  85789. }
  85790. if ( this.options && this.options.ignoreZeroRGBs ) {
  85791. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  85792. // ignore
  85793. save = false;
  85794. }
  85795. }
  85796. break;
  85797. default:
  85798. break;
  85799. }
  85800. if ( save ) {
  85801. covmat[ lprop ] = value;
  85802. }
  85803. }
  85804. }
  85805. return converted;
  85806. },
  85807. preload: function () {
  85808. for ( var mn in this.materialsInfo ) {
  85809. this.create( mn );
  85810. }
  85811. },
  85812. getIndex: function ( materialName ) {
  85813. return this.nameLookup[ materialName ];
  85814. },
  85815. getAsArray: function () {
  85816. var index = 0;
  85817. for ( var mn in this.materialsInfo ) {
  85818. this.materialsArray[ index ] = this.create( mn );
  85819. this.nameLookup[ mn ] = index;
  85820. index ++;
  85821. }
  85822. return this.materialsArray;
  85823. },
  85824. create: function ( materialName ) {
  85825. if ( this.materials[ materialName ] === undefined ) {
  85826. this.createMaterial_( materialName );
  85827. }
  85828. return this.materials[ materialName ];
  85829. },
  85830. createMaterial_: function ( materialName ) {
  85831. // Create material
  85832. var scope = this;
  85833. var mat = this.materialsInfo[ materialName ];
  85834. var params = {
  85835. name: materialName,
  85836. side: this.side
  85837. };
  85838. function resolveURL( baseUrl, url ) {
  85839. if ( typeof url !== 'string' || url === '' )
  85840. return '';
  85841. // Absolute URL
  85842. if ( /^https?:\/\//i.test( url ) ) return url;
  85843. return baseUrl + url;
  85844. }
  85845. function setMapForType( mapType, value ) {
  85846. if ( params[ mapType ] ) return; // Keep the first encountered texture
  85847. var texParams = scope.getTextureParams( value, params );
  85848. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  85849. map.repeat.copy( texParams.scale );
  85850. map.offset.copy( texParams.offset );
  85851. map.wrapS = scope.wrap;
  85852. map.wrapT = scope.wrap;
  85853. params[ mapType ] = map;
  85854. }
  85855. for ( var prop in mat ) {
  85856. var value = mat[ prop ];
  85857. var n;
  85858. if ( value === '' ) continue;
  85859. switch ( prop.toLowerCase() ) {
  85860. // Ns is material specular exponent
  85861. case 'kd':
  85862. // Diffuse color (color under white light) using RGB values
  85863. params.color = new Color().fromArray( value );
  85864. break;
  85865. case 'ks':
  85866. // Specular color (color when light is reflected from shiny surface) using RGB values
  85867. //params.specular = new Color().fromArray( value );
  85868. //console.log('specular',value)
  85869. break;
  85870. case 'ke':
  85871. // Emissive using RGB values
  85872. params.emissive = new Color().fromArray( value );
  85873. break;
  85874. case 'map_kd':
  85875. // Diffuse texture map
  85876. setMapForType( 'map', value );
  85877. break;
  85878. case 'map_ks':
  85879. // Specular map
  85880. setMapForType( 'specularMap', value );
  85881. break;
  85882. case 'map_ke':
  85883. // Emissive map
  85884. setMapForType( 'emissiveMap', value );
  85885. break;
  85886. case 'norm':
  85887. setMapForType( 'normalMap', value );
  85888. break;
  85889. case 'map_bump':
  85890. case 'bump':
  85891. // Bump texture map
  85892. setMapForType( 'bumpMap', value );
  85893. break;
  85894. case 'map_d':
  85895. // Alpha map
  85896. setMapForType( 'alphaMap', value );
  85897. params.transparent = true;
  85898. break;
  85899. case 'ns':
  85900. // The specular exponent (defines the focus of the specular highlight)
  85901. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  85902. //params.shininess = parseFloat( value );
  85903. //console.log('shininess',value)
  85904. break;
  85905. case 'd':
  85906. n = parseFloat( value );
  85907. if ( n < 1 ) {
  85908. params.opacity = n;
  85909. params.transparent = true;
  85910. }
  85911. break;
  85912. case 'tr':
  85913. n = parseFloat( value );
  85914. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  85915. if ( n > 0 ) {
  85916. params.opacity = 1 - n;
  85917. params.transparent = true;
  85918. }
  85919. break;
  85920. default:
  85921. break;
  85922. }
  85923. }
  85924. this.materials[ materialName ] = new MeshStandardMaterial( params );//MeshPhongMaterial( params );
  85925. return this.materials[ materialName ];
  85926. },
  85927. getTextureParams: function ( value, matParams ) {
  85928. var texParams = {
  85929. scale: new Vector2( 1, 1 ),
  85930. offset: new Vector2( 0, 0 )
  85931. };
  85932. var items = value.split( /\s+/ );
  85933. var pos;
  85934. pos = items.indexOf( '-bm' );
  85935. if ( pos >= 0 ) {
  85936. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  85937. items.splice( pos, 2 );
  85938. }
  85939. pos = items.indexOf( '-s' );
  85940. if ( pos >= 0 ) {
  85941. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  85942. items.splice( pos, 4 ); // we expect 3 parameters here!
  85943. }
  85944. pos = items.indexOf( '-o' );
  85945. if ( pos >= 0 ) {
  85946. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  85947. items.splice( pos, 4 ); // we expect 3 parameters here!
  85948. }
  85949. texParams.url = items.join( ' ' ).trim();
  85950. return texParams;
  85951. },
  85952. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  85953. var texture;
  85954. var manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  85955. var loader = manager.getHandler( url );
  85956. if ( loader === null ) {
  85957. loader = new TextureLoader( manager );
  85958. }
  85959. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  85960. texture = loader.load( url, onLoad, onProgress, onError );
  85961. if ( mapping !== undefined ) texture.mapping = mapping;
  85962. return texture;
  85963. }
  85964. };
  85965. //2022.11.11 copyfrom : https://unpkg.com/three@0.146.0/examples/jsm/loaders/DRACOLoader.js
  85966. const _taskCache = new WeakMap();
  85967. class DRACOLoader extends Loader {
  85968. constructor( manager ) {
  85969. super( manager );
  85970. this.decoderPath = '';
  85971. this.decoderConfig = {};
  85972. this.decoderBinary = null;
  85973. this.decoderPending = null;
  85974. this.workerLimit = 4;
  85975. this.workerPool = [];
  85976. this.workerNextTaskID = 1;
  85977. this.workerSourceURL = '';
  85978. this.defaultAttributeIDs = {
  85979. position: 'POSITION',
  85980. normal: 'NORMAL',
  85981. color: 'COLOR',
  85982. uv: 'TEX_COORD'
  85983. };
  85984. this.defaultAttributeTypes = {
  85985. position: 'Float32Array',
  85986. normal: 'Float32Array',
  85987. color: 'Float32Array',
  85988. uv: 'Float32Array'
  85989. };
  85990. }
  85991. setDecoderPath( path ) {
  85992. this.decoderPath = path;
  85993. return this;
  85994. }
  85995. setDecoderConfig( config ) {
  85996. this.decoderConfig = config;
  85997. return this;
  85998. }
  85999. setWorkerLimit( workerLimit ) {
  86000. this.workerLimit = workerLimit;
  86001. return this;
  86002. }
  86003. load( url, onLoad, onProgress, onError ) {
  86004. const loader = new FileLoader( this.manager );
  86005. loader.setPath( this.path );
  86006. loader.setResponseType( 'arraybuffer' );
  86007. loader.setRequestHeader( this.requestHeader );
  86008. loader.setWithCredentials( this.withCredentials );
  86009. loader.load( url, ( buffer ) => {
  86010. this.decodeDracoFile( buffer, onLoad ).catch( onError );
  86011. }, onProgress, onError );
  86012. }
  86013. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes ) {
  86014. const taskConfig = {
  86015. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  86016. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  86017. useUniqueIDs: !! attributeIDs
  86018. };
  86019. return this.decodeGeometry( buffer, taskConfig ).then( callback );
  86020. }
  86021. decodeGeometry( buffer, taskConfig ) {
  86022. const taskKey = JSON.stringify( taskConfig );
  86023. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  86024. // again from this thread.
  86025. if ( _taskCache.has( buffer ) ) {
  86026. const cachedTask = _taskCache.get( buffer );
  86027. if ( cachedTask.key === taskKey ) {
  86028. return cachedTask.promise;
  86029. } else if ( buffer.byteLength === 0 ) {
  86030. // Technically, it would be possible to wait for the previous task to complete,
  86031. // transfer the buffer back, and decode again with the second configuration. That
  86032. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  86033. // different ways, so this is left unimplemented.
  86034. throw new Error(
  86035. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  86036. 'settings. Buffer has already been transferred.'
  86037. );
  86038. }
  86039. }
  86040. //
  86041. let worker;
  86042. const taskID = this.workerNextTaskID ++;
  86043. const taskCost = buffer.byteLength;
  86044. // Obtain a worker and assign a task, and construct a geometry instance
  86045. // when the task completes.
  86046. const geometryPending = this._getWorker( taskID, taskCost )
  86047. .then( ( _worker ) => {
  86048. worker = _worker;
  86049. return new Promise( ( resolve, reject ) => {
  86050. worker._callbacks[ taskID ] = { resolve, reject };
  86051. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  86052. // this.debug();
  86053. } );
  86054. } )
  86055. .then( ( message ) => this._createGeometry( message.geometry ) );
  86056. // Remove task from the task list.
  86057. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  86058. geometryPending
  86059. .catch( () => true )
  86060. .then( () => {
  86061. if ( worker && taskID ) {
  86062. this._releaseTask( worker, taskID );
  86063. // this.debug();
  86064. }
  86065. } );
  86066. // Cache the task result.
  86067. _taskCache.set( buffer, {
  86068. key: taskKey,
  86069. promise: geometryPending
  86070. } );
  86071. return geometryPending;
  86072. }
  86073. _createGeometry( geometryData ) {
  86074. const geometry = new BufferGeometry();
  86075. if ( geometryData.index ) {
  86076. geometry.setIndex( new BufferAttribute( geometryData.index.array, 1 ) );
  86077. }
  86078. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  86079. const attribute = geometryData.attributes[ i ];
  86080. const name = attribute.name;
  86081. const array = attribute.array;
  86082. const itemSize = attribute.itemSize;
  86083. geometry.setAttribute( name, new BufferAttribute( array, itemSize ) );
  86084. }
  86085. return geometry;
  86086. }
  86087. _loadLibrary( url, responseType ) {
  86088. const loader = new FileLoader( this.manager );
  86089. loader.setPath( this.decoderPath );
  86090. loader.setResponseType( responseType );
  86091. loader.setWithCredentials( this.withCredentials );
  86092. return new Promise( ( resolve, reject ) => {
  86093. loader.load( url, resolve, undefined, reject );
  86094. } );
  86095. }
  86096. preload() {
  86097. this._initDecoder();
  86098. return this;
  86099. }
  86100. _initDecoder() {
  86101. if ( this.decoderPending ) return this.decoderPending;
  86102. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  86103. const librariesPending = [];
  86104. if ( useJS ) {
  86105. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  86106. } else {
  86107. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  86108. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  86109. }
  86110. this.decoderPending = Promise.all( librariesPending )
  86111. .then( ( libraries ) => {
  86112. const jsContent = libraries[ 0 ];
  86113. if ( ! useJS ) {
  86114. this.decoderConfig.wasmBinary = libraries[ 1 ];
  86115. }
  86116. const fn = DRACOWorker.toString();
  86117. const body = [
  86118. '/* draco decoder */',
  86119. jsContent,
  86120. '',
  86121. '/* worker */',
  86122. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  86123. ].join( '\n' );
  86124. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  86125. } );
  86126. return this.decoderPending;
  86127. }
  86128. _getWorker( taskID, taskCost ) {
  86129. return this._initDecoder().then( () => {
  86130. if ( this.workerPool.length < this.workerLimit ) {
  86131. const worker = new Worker( this.workerSourceURL );
  86132. worker._callbacks = {};
  86133. worker._taskCosts = {};
  86134. worker._taskLoad = 0;
  86135. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  86136. worker.onmessage = function ( e ) {
  86137. const message = e.data;
  86138. switch ( message.type ) {
  86139. case 'decode':
  86140. worker._callbacks[ message.id ].resolve( message );
  86141. break;
  86142. case 'error':
  86143. worker._callbacks[ message.id ].reject( message );
  86144. break;
  86145. default:
  86146. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  86147. }
  86148. };
  86149. this.workerPool.push( worker );
  86150. } else {
  86151. this.workerPool.sort( function ( a, b ) {
  86152. return a._taskLoad > b._taskLoad ? - 1 : 1;
  86153. } );
  86154. }
  86155. const worker = this.workerPool[ this.workerPool.length - 1 ];
  86156. worker._taskCosts[ taskID ] = taskCost;
  86157. worker._taskLoad += taskCost;
  86158. return worker;
  86159. } );
  86160. }
  86161. _releaseTask( worker, taskID ) {
  86162. worker._taskLoad -= worker._taskCosts[ taskID ];
  86163. delete worker._callbacks[ taskID ];
  86164. delete worker._taskCosts[ taskID ];
  86165. }
  86166. debug() {
  86167. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  86168. }
  86169. dispose() {
  86170. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  86171. this.workerPool[ i ].terminate();
  86172. }
  86173. this.workerPool.length = 0;
  86174. return this;
  86175. }
  86176. }
  86177. /* WEB WORKER */
  86178. function DRACOWorker() {
  86179. let decoderConfig;
  86180. let decoderPending;
  86181. onmessage = function ( e ) {
  86182. const message = e.data;
  86183. switch ( message.type ) {
  86184. case 'init':
  86185. decoderConfig = message.decoderConfig;
  86186. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  86187. decoderConfig.onModuleLoaded = function ( draco ) {
  86188. // Module is Promise-like. Wrap before resolving to avoid loop.
  86189. resolve( { draco: draco } );
  86190. };
  86191. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  86192. } );
  86193. break;
  86194. case 'decode':
  86195. const buffer = message.buffer;
  86196. const taskConfig = message.taskConfig;
  86197. decoderPending.then( ( module ) => {
  86198. const draco = module.draco;
  86199. const decoder = new draco.Decoder();
  86200. const decoderBuffer = new draco.DecoderBuffer();
  86201. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  86202. try {
  86203. const geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  86204. const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  86205. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  86206. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  86207. } catch ( error ) {
  86208. console.error( error );
  86209. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  86210. } finally {
  86211. draco.destroy( decoderBuffer );
  86212. draco.destroy( decoder );
  86213. }
  86214. } );
  86215. break;
  86216. }
  86217. };
  86218. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  86219. const attributeIDs = taskConfig.attributeIDs;
  86220. const attributeTypes = taskConfig.attributeTypes;
  86221. let dracoGeometry;
  86222. let decodingStatus;
  86223. const geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  86224. if ( geometryType === draco.TRIANGULAR_MESH ) {
  86225. dracoGeometry = new draco.Mesh();
  86226. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  86227. } else if ( geometryType === draco.POINT_CLOUD ) {
  86228. dracoGeometry = new draco.PointCloud();
  86229. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  86230. } else {
  86231. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  86232. }
  86233. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  86234. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  86235. }
  86236. const geometry = { index: null, attributes: [] };
  86237. // Gather all vertex attributes.
  86238. for ( const attributeName in attributeIDs ) {
  86239. const attributeType = self[ attributeTypes[ attributeName ] ];
  86240. let attribute;
  86241. let attributeID;
  86242. // A Draco file may be created with default vertex attributes, whose attribute IDs
  86243. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  86244. // a Draco file may contain a custom set of attributes, identified by known unique
  86245. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  86246. if ( taskConfig.useUniqueIDs ) {
  86247. attributeID = attributeIDs[ attributeName ];
  86248. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  86249. } else {
  86250. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  86251. if ( attributeID === - 1 ) continue;
  86252. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  86253. }
  86254. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  86255. }
  86256. // Add index.
  86257. if ( geometryType === draco.TRIANGULAR_MESH ) {
  86258. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  86259. }
  86260. draco.destroy( dracoGeometry );
  86261. return geometry;
  86262. }
  86263. function decodeIndex( draco, decoder, dracoGeometry ) {
  86264. const numFaces = dracoGeometry.num_faces();
  86265. const numIndices = numFaces * 3;
  86266. const byteLength = numIndices * 4;
  86267. const ptr = draco._malloc( byteLength );
  86268. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  86269. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  86270. draco._free( ptr );
  86271. return { array: index, itemSize: 1 };
  86272. }
  86273. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  86274. const numComponents = attribute.num_components();
  86275. const numPoints = dracoGeometry.num_points();
  86276. const numValues = numPoints * numComponents;
  86277. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  86278. const dataType = getDracoDataType( draco, attributeType );
  86279. const ptr = draco._malloc( byteLength );
  86280. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  86281. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  86282. draco._free( ptr );
  86283. return {
  86284. name: attributeName,
  86285. array: array,
  86286. itemSize: numComponents
  86287. };
  86288. }
  86289. function getDracoDataType( draco, attributeType ) {
  86290. switch ( attributeType ) {
  86291. case Float32Array: return draco.DT_FLOAT32;
  86292. case Int8Array: return draco.DT_INT8;
  86293. case Int16Array: return draco.DT_INT16;
  86294. case Int32Array: return draco.DT_INT32;
  86295. case Uint8Array: return draco.DT_UINT8;
  86296. case Uint16Array: return draco.DT_UINT16;
  86297. case Uint32Array: return draco.DT_UINT32;
  86298. }
  86299. }
  86300. }
  86301. /**
  86302. * @author Deepkolos / https://github.com/deepkolos
  86303. */
  86304. //用于KTX2Loader
  86305. class WorkerPool$1 {
  86306. constructor( pool = 4 ) {
  86307. this.pool = pool;
  86308. this.queue = [];
  86309. this.workers = [];
  86310. this.workersResolve = [];
  86311. this.workerStatus = 0;
  86312. }
  86313. _initWorker( workerId ) {
  86314. if ( ! this.workers[ workerId ] ) {
  86315. const worker = this.workerCreator();
  86316. worker.addEventListener( 'message', this._onMessage.bind( this, workerId ) );
  86317. this.workers[ workerId ] = worker;
  86318. }
  86319. }
  86320. _getIdleWorker() {
  86321. for ( let i = 0; i < this.pool; i ++ )
  86322. if ( ! ( this.workerStatus & ( 1 << i ) ) ) return i;
  86323. return - 1;
  86324. }
  86325. _onMessage( workerId, msg ) {
  86326. const resolve = this.workersResolve[ workerId ];
  86327. resolve && resolve( msg );
  86328. if ( this.queue.length ) {
  86329. const { resolve, msg, transfer } = this.queue.shift();
  86330. this.workersResolve[ workerId ] = resolve;
  86331. this.workers[ workerId ].postMessage( msg, transfer );
  86332. } else {
  86333. this.workerStatus ^= 1 << workerId;
  86334. }
  86335. }
  86336. setWorkerCreator( workerCreator ) {
  86337. this.workerCreator = workerCreator;
  86338. }
  86339. setWorkerLimit( pool ) {
  86340. this.pool = pool;
  86341. }
  86342. postMessage( msg, transfer ) {
  86343. return new Promise( ( resolve ) => {
  86344. const workerId = this._getIdleWorker();
  86345. if ( workerId !== - 1 ) {
  86346. this._initWorker( workerId );
  86347. this.workerStatus |= 1 << workerId;
  86348. this.workersResolve[ workerId ] = resolve;
  86349. this.workers[ workerId ].postMessage( msg, transfer );
  86350. } else {
  86351. this.queue.push( { resolve, msg, transfer } );
  86352. }
  86353. } );
  86354. }
  86355. dispose() {
  86356. this.workers.forEach( ( worker ) => worker.terminate() );
  86357. this.workersResolve.length = 0;
  86358. this.workers.length = 0;
  86359. this.queue.length = 0;
  86360. this.workerStatus = 0;
  86361. }
  86362. }
  86363. const t=0,e$1=1,n$1=2,i$1=3,s=0,a$1=0,r=2,o$1=0,l$1=1,f=160,U$1=161,c$2=162,h$2=163,_$1=0,p=1,g=0,y=1,x$2=2,u$2=3,b$1=4,d=5,m=6,w$2=7,D=8,B=9,L=10,A=11,k=12,v=13,S$1=14,I=15,O=16,T$1=17,V=18,E=0,F=1,P=2,C=3,z=4,M$1=5,W=6,N=7,H=8,K=9,X=10,j=11,R=0,Y=1,q=2,G=13,J=14,Q=15,Z=128,$$1=64,tt=32,et=16,nt=0,it=1,st=2,at=3,rt=4,ot=5,lt=6,ft=7,Ut=8,ct=9,ht=10,_t=13,pt=14,gt=15,yt=16,xt=17,ut=20,bt=21,dt=22,mt=23,wt=24,Dt=27,Bt=28,Lt=29,At=30,kt=31,vt=34,St=35,It=36,Ot=37,Tt=38,Vt=41,Et=42,Ft=43,Pt=44,Ct=45,zt=48,Mt=49,Wt=50,Nt=58,Ht=59,Kt=62,Xt=63,jt=64,Rt=65,Yt=68,qt=69,Gt=70,Jt=71,Qt=74,Zt=75,$t=76,te=77,ee=78,ne=81,ie=82,se=83,ae=84,re=85,oe=88,le=89,fe=90,Ue=91,ce=92,he=95,_e=96,pe=97,ge=98,ye=99,xe=100,ue=101,be=102,de=103,me=104,we=105,De=106,Be=107,Le=108,Ae=109,ke=110,ve=111,Se=112,Ie=113,Oe=114,Te=115,Ve=116,Ee=117,Fe=118,Pe=119,Ce=120,ze=121,Me=122,We=123,Ne=124,He=125,Ke=126,Xe=127,je=128,Re=129,Ye=130,qe=131,Ge=132,Je=133,Qe=134,Ze=135,$e=136,tn=137,en=138,nn=139,sn=140,an=141,rn=142,on=143,ln=144,fn=145,Un=146,cn=147,hn=148,_n=149,pn=150,gn=151,yn=152,xn=153,un=154,bn=155,dn=156,mn=157,wn=158,Dn=159,Bn=160,Ln=161,An=162,kn=163,vn=164,Sn=165,In=166,On=167,Tn=168,Vn=169,En=170,Fn=171,Pn=172,Cn=173,zn=174,Mn=175,Wn=176,Nn=177,Hn=178,Kn=179,Xn=180,jn=181,Rn=182,Yn=183,qn=184,Gn=1000156007,Jn=1000156008,Qn=1000156009,Zn=1000156010,$n=1000156011,ti=1000156017,ei=1000156018,ni=1000156019,ii=1000156020,si=1000156021,ai=1000054e3,ri=1000054001,oi=1000054002,li=1000054003,fi=1000054004,Ui=1000054005,ci=1000054006,hi=1000054007,_i=1000066e3,pi=1000066001,gi=1000066002,yi=1000066003,xi=1000066004,ui=1000066005,bi=1000066006,di=1000066007,mi=1000066008,wi=1000066009,Di=1000066010,Bi=1000066011,Li=1000066012,Ai=1000066013,ki=100034e4,vi=1000340001;class Si{constructor(){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=[{vendorId:0,descriptorType:0,descriptorBlockSize:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null;}}class Ii{constructor(t,e,n,i){this._dataView=new DataView(t.buffer,t.byteOffset+e,n),this._littleEndian=i,this._offset=0;}_nextUint8(){const t=this._dataView.getUint8(this._offset);return this._offset+=1,t}_nextUint16(){const t=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,t}_nextUint32(){const t=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,t}_nextUint64(){const t=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,t}_nextInt32(){const t=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,t}_skip(t){return this._offset+=t,this}_scan(t,e=0){const n=this._offset;let i=0;for(;this._dataView.getUint8(this._offset)!==e&&i<t;)i++,this._offset++;return i<t&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,i)}}const Oi=new Uint8Array([0]),Ti=[171,75,84,88,32,50,48,187,13,10,26,10];function Vi(t){return "undefined"!=typeof TextEncoder?(new TextEncoder).encode(t):Buffer.from(t)}function Ei(t){return "undefined"!=typeof TextDecoder?(new TextDecoder).decode(t):Buffer.from(t).toString("utf8")}function Fi(t){let e=0;for(const n of t)e+=n.byteLength;const n=new Uint8Array(e);let i=0;for(const e of t)n.set(new Uint8Array(e),i),i+=e.byteLength;return n}function Pi(t){const e=new Uint8Array(t.buffer,t.byteOffset,Ti.length);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.");const n=new Si,i=17*Uint32Array.BYTES_PER_ELEMENT,s=new Ii(t,Ti.length,i,!0);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();const a=s._nextUint32();n.supercompressionScheme=s._nextUint32();const r=s._nextUint32(),o=s._nextUint32(),l=s._nextUint32(),f=s._nextUint32(),U=s._nextUint64(),c=s._nextUint64(),h=new Ii(t,Ti.length+i,3*a*8,!0);for(let e=0;e<a;e++)n.levels.push({levelData:new Uint8Array(t.buffer,t.byteOffset+h._nextUint64(),h._nextUint64()),uncompressedByteLength:h._nextUint64()});const _=new Ii(t,r,o,!0),p={vendorId:_._skip(4)._nextUint16(),descriptorType:_._nextUint16(),versionNumber:_._nextUint16(),descriptorBlockSize:_._nextUint16(),colorModel:_._nextUint8(),colorPrimaries:_._nextUint8(),transferFunction:_._nextUint8(),flags:_._nextUint8(),texelBlockDimension:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],bytesPlane:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],samples:[]},g=(p.descriptorBlockSize/4-6)/4;for(let t=0;t<g;t++){const e={bitOffset:_._nextUint16(),bitLength:_._nextUint8(),channelType:_._nextUint8(),samplePosition:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],sampleLower:-Infinity,sampleUpper:Infinity};64&e.channelType?(e.sampleLower=_._nextInt32(),e.sampleUpper=_._nextInt32()):(e.sampleLower=_._nextUint32(),e.sampleUpper=_._nextUint32()),p.samples[t]=e;}n.dataFormatDescriptor.length=0,n.dataFormatDescriptor.push(p);const y=new Ii(t,l,f,!0);for(;y._offset<f;){const t=y._nextUint32(),e=y._scan(t),i=Ei(e),s=y._scan(t-e.byteLength);n.keyValue[i]=i.match(/^ktx/i)?Ei(s):s,y._offset%4&&y._skip(4-y._offset%4);}if(c<=0)return n;const x=new Ii(t,U,c,!0),u=x._nextUint16(),b=x._nextUint16(),d=x._nextUint32(),m=x._nextUint32(),w=x._nextUint32(),D=x._nextUint32(),B=[];for(let t=0;t<a;t++)B.push({imageFlags:x._nextUint32(),rgbSliceByteOffset:x._nextUint32(),rgbSliceByteLength:x._nextUint32(),alphaSliceByteOffset:x._nextUint32(),alphaSliceByteLength:x._nextUint32()});const L=U+x._offset,A=L+d,k=A+m,v=k+w,S=new Uint8Array(t.buffer,t.byteOffset+L,d),I=new Uint8Array(t.buffer,t.byteOffset+A,m),O=new Uint8Array(t.buffer,t.byteOffset+k,w),T=new Uint8Array(t.buffer,t.byteOffset+v,D);return n.globalData={endpointCount:u,selectorCount:b,imageDescs:B,endpointsData:S,selectorsData:I,tablesData:O,extendedData:T},n}function Ci(){return (Ci=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i]);}return t}).apply(this,arguments)}const zi={keepWriter:!1};function Mi(t,e={}){e=Ci({},zi,e);let n=new ArrayBuffer(0);if(t.globalData){const e=new ArrayBuffer(20+5*t.globalData.imageDescs.length*4),i=new DataView(e);i.setUint16(0,t.globalData.endpointCount,!0),i.setUint16(2,t.globalData.selectorCount,!0),i.setUint32(4,t.globalData.endpointsData.byteLength,!0),i.setUint32(8,t.globalData.selectorsData.byteLength,!0),i.setUint32(12,t.globalData.tablesData.byteLength,!0),i.setUint32(16,t.globalData.extendedData.byteLength,!0);for(let e=0;e<t.globalData.imageDescs.length;e++){const n=t.globalData.imageDescs[e];i.setUint32(20+5*e*4+0,n.imageFlags,!0),i.setUint32(20+5*e*4+4,n.rgbSliceByteOffset,!0),i.setUint32(20+5*e*4+8,n.rgbSliceByteLength,!0),i.setUint32(20+5*e*4+12,n.alphaSliceByteOffset,!0),i.setUint32(20+5*e*4+16,n.alphaSliceByteLength,!0);}n=Fi([e,t.globalData.endpointsData,t.globalData.selectorsData,t.globalData.tablesData,t.globalData.extendedData]);}const i=[];let s=t.keyValue;e.keepWriter||(s=Ci({},t.keyValue,{KTXwriter:"KTX-Parse v0.3.1"}));for(const t in s){const e=s[t],n=Vi(t),a="string"==typeof e?Vi(e):e,r=n.byteLength+1+a.byteLength+1,o=r%4?4-r%4:0;i.push(Fi([new Uint32Array([r]),n,Oi,a,Oi,new Uint8Array(o).fill(0)]));}const a=Fi(i);if(1!==t.dataFormatDescriptor.length||0!==t.dataFormatDescriptor[0].descriptorType)throw new Error("Only BASICFORMAT Data Format Descriptor output supported.");const r=t.dataFormatDescriptor[0],o=new ArrayBuffer(28+16*r.samples.length),l=new DataView(o),f=24+16*r.samples.length;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`.");l.setUint8(16,r.texelBlockDimension[0]),l.setUint8(17,r.texelBlockDimension[1]),l.setUint8(18,r.texelBlockDimension[2]),l.setUint8(19,r.texelBlockDimension[3]);for(let t=0;t<8;t++)l.setUint8(20+t,r.bytesPlane[t]);for(let t=0;t<r.samples.length;t++){const e=r.samples[t],n=28+16*t;if(e.channelID)throw new Error("channelID has been renamed to channelType.");l.setUint16(n+0,e.bitOffset,!0),l.setUint8(n+2,e.bitLength),l.setUint8(n+3,e.channelType),l.setUint8(n+4,e.samplePosition[0]),l.setUint8(n+5,e.samplePosition[1]),l.setUint8(n+6,e.samplePosition[2]),l.setUint8(n+7,e.samplePosition[3]),64&e.channelType?(l.setInt32(n+8,e.sampleLower,!0),l.setInt32(n+12,e.sampleUpper,!0)):(l.setUint32(n+8,e.sampleLower,!0),l.setUint32(n+12,e.sampleUpper,!0));}const U=Ti.length+68+3*t.levels.length*8,c=U+o.byteLength;let h=n.byteLength>0?c+a.byteLength:0;h%8&&(h+=8-h%8);const _=[],p=new DataView(new ArrayBuffer(3*t.levels.length*8));let g=(h||c+a.byteLength)+n.byteLength;for(let e=0;e<t.levels.length;e++){const n=t.levels[e];_.push(n.levelData),p.setBigUint64(24*e+0,BigInt(g),!0),p.setBigUint64(24*e+8,BigInt(n.levelData.byteLength),!0),p.setBigUint64(24*e+16,BigInt(n.uncompressedByteLength),!0),g+=n.levelData.byteLength;}const y=new ArrayBuffer(68),x=new DataView(y);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,..._]))}
  86364. /**
  86365. * @author Don McCurdy / https://www.donmccurdy.com
  86366. */
  86367. let init, instance, heap;
  86368. const importObject = {
  86369. env: {
  86370. emscripten_notify_memory_growth: function ( index ) {
  86371. heap = new Uint8Array( instance.exports.memory.buffer );
  86372. }
  86373. }
  86374. };
  86375. /**
  86376. * ZSTD (Zstandard) decoder.
  86377. *
  86378. * Compiled from https://github.com/facebook/zstd/tree/dev/contrib/single_file_libs, with the
  86379. * following steps:
  86380. *
  86381. * ```
  86382. * ./combine.sh -r ../../lib -o zstddeclib.c zstddeclib-in.c
  86383. * 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
  86384. * base64 zstddec.wasm > zstddec.txt
  86385. * ```
  86386. *
  86387. * The base64 string written to `zstddec.txt` is embedded as the `wasm` variable at the bottom
  86388. * of this file. The rest of this file is written by hand, in order to avoid an additional JS
  86389. * wrapper generated by Emscripten.
  86390. */
  86391. class ZSTDDecoder {
  86392. init () {
  86393. if ( ! init ) {
  86394. init = fetch( 'data:application/wasm;base64,' + wasm )
  86395. .then( ( response ) => response.arrayBuffer() )
  86396. .then( ( arrayBuffer ) => WebAssembly.instantiate( arrayBuffer, importObject ) )
  86397. .then( ( result ) => {
  86398. instance = result.instance;
  86399. importObject.env.emscripten_notify_memory_growth( 0 ); // initialize heap.
  86400. });
  86401. }
  86402. return init;
  86403. }
  86404. decode ( array, uncompressedSize = 0 ) {
  86405. // Write compressed data into WASM memory.
  86406. const compressedSize = array.byteLength;
  86407. const compressedPtr = instance.exports.malloc( compressedSize );
  86408. heap.set( array, compressedPtr );
  86409. // Decompress into WASM memory.
  86410. uncompressedSize = uncompressedSize || Number( instance.exports.ZSTD_findDecompressedSize( compressedPtr, compressedSize ) );
  86411. const uncompressedPtr = instance.exports.malloc( uncompressedSize );
  86412. const actualSize = instance.exports.ZSTD_decompress( uncompressedPtr, uncompressedSize, compressedPtr, compressedSize );
  86413. // Read decompressed data and free WASM memory.
  86414. const dec = heap.slice( uncompressedPtr, uncompressedPtr + actualSize );
  86415. instance.exports.free( compressedPtr );
  86416. instance.exports.free( uncompressedPtr );
  86417. return dec;
  86418. }
  86419. }
  86420. /**
  86421. * BSD License
  86422. *
  86423. * For Zstandard software
  86424. *
  86425. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. All rights reserved.
  86426. *
  86427. * Redistribution and use in source and binary forms, with or without modification,
  86428. * are permitted provided that the following conditions are met:
  86429. *
  86430. * * Redistributions of source code must retain the above copyright notice, this
  86431. * list of conditions and the following disclaimer.
  86432. *
  86433. * * Redistributions in binary form must reproduce the above copyright notice,
  86434. * this list of conditions and the following disclaimer in the documentation
  86435. * and/or other materials provided with the distribution.
  86436. *
  86437. * * Neither the name Facebook nor the names of its contributors may be used to
  86438. * endorse or promote products derived from this software without specific
  86439. * prior written permission.
  86440. *
  86441. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  86442. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  86443. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  86444. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  86445. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  86446. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  86447. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  86448. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  86449. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  86450. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  86451. */
  86452. const 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';
  86453. /**
  86454. * Loader for KTX 2.0 GPU Texture containers.
  86455. *
  86456. * KTX 2.0 is a container format for various GPU texture formats. The loader
  86457. * supports Basis Universal GPU textures, which can be quickly transcoded to
  86458. * a wide variety of GPU texture compression formats, as well as some
  86459. * uncompressed DataTexture and Data3DTexture formats.
  86460. *
  86461. * References:
  86462. * - KTX: http://github.khronos.org/KTX-Specification/
  86463. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  86464. */
  86465. const _taskCache$1 = new WeakMap();
  86466. let _activeLoaders = 0;
  86467. let _zstd;
  86468. class KTX2Loader extends Loader {
  86469. constructor( manager ) {
  86470. super( manager );
  86471. this.transcoderPath = '';
  86472. this.transcoderBinary = null;
  86473. this.transcoderPending = null;
  86474. this.workerPool = new WorkerPool$1();
  86475. this.workerSourceURL = '';
  86476. this.workerConfig = null;
  86477. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  86478. console.warn(
  86479. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  86480. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  86481. );
  86482. }
  86483. }
  86484. setTranscoderPath( path ) {
  86485. this.transcoderPath = path;
  86486. return this;
  86487. }
  86488. setWorkerLimit( num ) {
  86489. this.workerPool.setWorkerLimit( num );
  86490. return this;
  86491. }
  86492. detectSupport( renderer ) {
  86493. this.workerConfig = {
  86494. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  86495. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  86496. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  86497. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  86498. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  86499. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  86500. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  86501. };
  86502. if ( renderer.capabilities.isWebGL2 ) {
  86503. // https://github.com/mrdoob/three.js/pull/22928
  86504. this.workerConfig.etc1Supported = false;
  86505. }
  86506. return this;
  86507. }
  86508. init() {
  86509. if ( ! this.transcoderPending ) {
  86510. // Load transcoder wrapper.
  86511. const jsLoader = new FileLoader( this.manager );
  86512. jsLoader.setPath( this.transcoderPath );
  86513. jsLoader.setWithCredentials( this.withCredentials );
  86514. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  86515. // Load transcoder WASM binary.
  86516. const binaryLoader = new FileLoader( this.manager );
  86517. binaryLoader.setPath( this.transcoderPath );
  86518. binaryLoader.setResponseType( 'arraybuffer' );
  86519. binaryLoader.setWithCredentials( this.withCredentials );
  86520. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  86521. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  86522. .then( ( [ jsContent, binaryContent ] ) => {
  86523. const fn = KTX2Loader.BasisWorker.toString();
  86524. const body = [
  86525. '/* constants */',
  86526. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  86527. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  86528. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  86529. '/* basis_transcoder.js */',
  86530. jsContent,
  86531. '/* worker */',
  86532. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  86533. ].join( '\n' );
  86534. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  86535. this.transcoderBinary = binaryContent;
  86536. this.workerPool.setWorkerCreator( () => {
  86537. const worker = new Worker( this.workerSourceURL );
  86538. const transcoderBinary = this.transcoderBinary.slice( 0 );
  86539. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  86540. return worker;
  86541. } );
  86542. } );
  86543. if ( _activeLoaders > 0 ) {
  86544. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  86545. console.warn(
  86546. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  86547. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  86548. );
  86549. }
  86550. _activeLoaders ++;
  86551. }
  86552. return this.transcoderPending;
  86553. }
  86554. load( url, onLoad, onProgress, onError ) {
  86555. if ( this.workerConfig === null ) {
  86556. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  86557. }
  86558. const loader = new FileLoader( this.manager );
  86559. loader.setResponseType( 'arraybuffer' );
  86560. loader.setWithCredentials( this.withCredentials );
  86561. loader.load( url, ( buffer ) => {
  86562. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  86563. // again from this thread.
  86564. if ( _taskCache$1.has( buffer ) ) {
  86565. const cachedTask = _taskCache$1.get( buffer );
  86566. return cachedTask.promise.then( onLoad ).catch( onError );
  86567. }
  86568. this._createTexture( buffer )
  86569. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  86570. .catch( onError );
  86571. }, onProgress, onError );
  86572. }
  86573. _createTextureFrom( transcodeResult, container ) {
  86574. const { mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags } = transcodeResult;
  86575. if ( type === 'error' ) return Promise.reject( error );
  86576. const texture = container.layerCount > 1
  86577. ? new CompressedArrayTexture( mipmaps, width, height, container.layerCount, format, UnsignedByteType )
  86578. : new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  86579. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  86580. texture.magFilter = LinearFilter;
  86581. texture.generateMipmaps = false;
  86582. texture.needsUpdate = true;
  86583. texture.encoding = dfdTransferFn === x$2 ? sRGBEncoding : LinearEncoding;
  86584. texture.premultiplyAlpha = !! ( dfdFlags & p );
  86585. return texture;
  86586. }
  86587. /**
  86588. * @param {ArrayBuffer} buffer
  86589. * @param {object?} config
  86590. * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
  86591. */
  86592. async _createTexture( buffer, config = {} ) {
  86593. const container = Pi( new Uint8Array( buffer ) );
  86594. if ( container.vkFormat !== nt ) {
  86595. return createDataTexture( container );
  86596. }
  86597. //
  86598. const taskConfig = config;
  86599. const texturePending = this.init().then( () => {
  86600. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  86601. } ).then( ( e ) => this._createTextureFrom( e.data, container ) );
  86602. // Cache the task result.
  86603. _taskCache$1.set( buffer, { promise: texturePending } );
  86604. return texturePending;
  86605. }
  86606. dispose() {
  86607. this.workerPool.dispose();
  86608. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  86609. _activeLoaders --;
  86610. return this;
  86611. }
  86612. }
  86613. /* CONSTANTS */
  86614. KTX2Loader.BasisFormat = {
  86615. ETC1S: 0,
  86616. UASTC_4x4: 1,
  86617. };
  86618. KTX2Loader.TranscoderFormat = {
  86619. ETC1: 0,
  86620. ETC2: 1,
  86621. BC1: 2,
  86622. BC3: 3,
  86623. BC4: 4,
  86624. BC5: 5,
  86625. BC7_M6_OPAQUE_ONLY: 6,
  86626. BC7_M5: 7,
  86627. PVRTC1_4_RGB: 8,
  86628. PVRTC1_4_RGBA: 9,
  86629. ASTC_4x4: 10,
  86630. ATC_RGB: 11,
  86631. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  86632. RGBA32: 13,
  86633. RGB565: 14,
  86634. BGR565: 15,
  86635. RGBA4444: 16,
  86636. };
  86637. KTX2Loader.EngineFormat = {
  86638. RGBAFormat: RGBAFormat,
  86639. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  86640. RGBA_BPTC_Format: RGBA_BPTC_Format,
  86641. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  86642. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  86643. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  86644. RGB_ETC1_Format: RGB_ETC1_Format,
  86645. RGB_ETC2_Format: RGB_ETC2_Format,
  86646. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  86647. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  86648. };
  86649. /* WEB WORKER */
  86650. KTX2Loader.BasisWorker = function () {
  86651. let config;
  86652. let transcoderPending;
  86653. let BasisModule;
  86654. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  86655. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  86656. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  86657. self.addEventListener( 'message', function ( e ) {
  86658. const message = e.data;
  86659. switch ( message.type ) {
  86660. case 'init':
  86661. config = message.config;
  86662. init( message.transcoderBinary );
  86663. break;
  86664. case 'transcode':
  86665. transcoderPending.then( () => {
  86666. try {
  86667. const { width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags } = transcode( message.buffer );
  86668. const buffers = [];
  86669. for ( let i = 0; i < mipmaps.length; ++ i ) {
  86670. buffers.push( mipmaps[ i ].data.buffer );
  86671. }
  86672. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags }, buffers );
  86673. } catch ( error ) {
  86674. console.error( error );
  86675. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  86676. }
  86677. } );
  86678. break;
  86679. }
  86680. } );
  86681. function init( wasmBinary ) {
  86682. transcoderPending = new Promise( ( resolve ) => {
  86683. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  86684. BASIS( BasisModule ); // eslint-disable-line no-undef
  86685. } ).then( () => {
  86686. BasisModule.initializeBasis();
  86687. if ( BasisModule.KTX2File === undefined ) {
  86688. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  86689. }
  86690. } );
  86691. }
  86692. function transcode( buffer ) {
  86693. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  86694. function cleanup() {
  86695. ktx2File.close();
  86696. ktx2File.delete();
  86697. }
  86698. if ( ! ktx2File.isValid() ) {
  86699. cleanup();
  86700. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  86701. }
  86702. const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  86703. const width = ktx2File.getWidth();
  86704. const height = ktx2File.getHeight();
  86705. const layers = ktx2File.getLayers() || 1;
  86706. const levels = ktx2File.getLevels();
  86707. const hasAlpha = ktx2File.getHasAlpha();
  86708. const dfdTransferFn = ktx2File.getDFDTransferFunc();
  86709. const dfdFlags = ktx2File.getDFDFlags();
  86710. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  86711. if ( ! width || ! height || ! levels ) {
  86712. cleanup();
  86713. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  86714. }
  86715. if ( ! ktx2File.startTranscoding() ) {
  86716. cleanup();
  86717. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  86718. }
  86719. const mipmaps = [];
  86720. for ( let mip = 0; mip < levels; mip ++ ) {
  86721. const layerMips = [];
  86722. let mipWidth, mipHeight;
  86723. for ( let layer = 0; layer < layers; layer ++ ) {
  86724. const levelInfo = ktx2File.getImageLevelInfo( mip, layer, 0 );
  86725. mipWidth = levelInfo.origWidth;
  86726. mipHeight = levelInfo.origHeight;
  86727. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
  86728. const status = ktx2File.transcodeImage(
  86729. dst,
  86730. mip,
  86731. layer,
  86732. 0,
  86733. transcoderFormat,
  86734. 0,
  86735. - 1,
  86736. - 1,
  86737. );
  86738. if ( ! status ) {
  86739. cleanup();
  86740. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  86741. }
  86742. layerMips.push( dst );
  86743. }
  86744. mipmaps.push( { data: concat( layerMips ), width: mipWidth, height: mipHeight } );
  86745. }
  86746. cleanup();
  86747. return { width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags };
  86748. }
  86749. //
  86750. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  86751. // device capabilities, and texture dimensions. The list below ranks the formats separately
  86752. // for ETC1S and UASTC.
  86753. //
  86754. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  86755. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  86756. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  86757. const FORMAT_OPTIONS = [
  86758. {
  86759. if: 'astcSupported',
  86760. basisFormat: [ BasisFormat.UASTC_4x4 ],
  86761. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  86762. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  86763. priorityETC1S: Infinity,
  86764. priorityUASTC: 1,
  86765. needsPowerOfTwo: false,
  86766. },
  86767. {
  86768. if: 'bptcSupported',
  86769. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  86770. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  86771. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  86772. priorityETC1S: 3,
  86773. priorityUASTC: 2,
  86774. needsPowerOfTwo: false,
  86775. },
  86776. {
  86777. if: 'dxtSupported',
  86778. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  86779. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  86780. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  86781. priorityETC1S: 4,
  86782. priorityUASTC: 5,
  86783. needsPowerOfTwo: false,
  86784. },
  86785. {
  86786. if: 'etc2Supported',
  86787. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  86788. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  86789. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  86790. priorityETC1S: 1,
  86791. priorityUASTC: 3,
  86792. needsPowerOfTwo: false,
  86793. },
  86794. {
  86795. if: 'etc1Supported',
  86796. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  86797. transcoderFormat: [ TranscoderFormat.ETC1 ],
  86798. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  86799. priorityETC1S: 2,
  86800. priorityUASTC: 4,
  86801. needsPowerOfTwo: false,
  86802. },
  86803. {
  86804. if: 'pvrtcSupported',
  86805. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  86806. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  86807. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  86808. priorityETC1S: 5,
  86809. priorityUASTC: 6,
  86810. needsPowerOfTwo: true,
  86811. },
  86812. ];
  86813. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  86814. return a.priorityETC1S - b.priorityETC1S;
  86815. } );
  86816. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  86817. return a.priorityUASTC - b.priorityUASTC;
  86818. } );
  86819. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  86820. let transcoderFormat;
  86821. let engineFormat;
  86822. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  86823. for ( let i = 0; i < options.length; i ++ ) {
  86824. const opt = options[ i ];
  86825. if ( ! config[ opt.if ] ) continue;
  86826. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  86827. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  86828. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  86829. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  86830. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  86831. return { transcoderFormat, engineFormat };
  86832. }
  86833. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  86834. transcoderFormat = TranscoderFormat.RGBA32;
  86835. engineFormat = EngineFormat.RGBAFormat;
  86836. return { transcoderFormat, engineFormat };
  86837. }
  86838. function isPowerOfTwo( value ) {
  86839. if ( value <= 2 ) return true;
  86840. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  86841. }
  86842. /** Concatenates N byte arrays. */
  86843. function concat( arrays ) {
  86844. let totalByteLength = 0;
  86845. for ( const array of arrays ) {
  86846. totalByteLength += array.byteLength;
  86847. }
  86848. const result = new Uint8Array( totalByteLength );
  86849. let byteOffset = 0;
  86850. for ( const array of arrays ) {
  86851. result.set( array, byteOffset );
  86852. byteOffset += array.byteLength;
  86853. }
  86854. return result;
  86855. }
  86856. };
  86857. //
  86858. // DataTexture and Data3DTexture parsing.
  86859. const FORMAT_MAP = {
  86860. [ Ae ]: RGBAFormat,
  86861. [ pe ]: RGBAFormat,
  86862. [ Ot ]: RGBAFormat,
  86863. [ Ft ]: RGBAFormat,
  86864. [ de ]: RGFormat,
  86865. [ se ]: RGFormat,
  86866. [ yt ]: RGFormat,
  86867. [ dt ]: RGFormat,
  86868. [ xe ]: RedFormat,
  86869. [ $t ]: RedFormat,
  86870. [ gt ]: RedFormat,
  86871. [ ct ]: RedFormat,
  86872. };
  86873. const TYPE_MAP = {
  86874. [ Ae ]: FloatType,
  86875. [ pe ]: HalfFloatType,
  86876. [ Ot ]: UnsignedByteType,
  86877. [ Ft ]: UnsignedByteType,
  86878. [ de ]: FloatType,
  86879. [ se ]: HalfFloatType,
  86880. [ yt ]: UnsignedByteType,
  86881. [ dt ]: UnsignedByteType,
  86882. [ xe ]: FloatType,
  86883. [ $t ]: HalfFloatType,
  86884. [ gt ]: UnsignedByteType,
  86885. [ ct ]: UnsignedByteType,
  86886. };
  86887. const ENCODING_MAP = {
  86888. [ Ft ]: sRGBEncoding,
  86889. [ dt ]: sRGBEncoding,
  86890. [ gt ]: sRGBEncoding,
  86891. };
  86892. async function createDataTexture( container ) {
  86893. const { vkFormat, pixelWidth, pixelHeight, pixelDepth } = container;
  86894. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  86895. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat.' );
  86896. }
  86897. const level = container.levels[ 0 ];
  86898. let levelData;
  86899. let view;
  86900. if ( container.supercompressionScheme === t ) {
  86901. levelData = level.levelData;
  86902. } else if ( container.supercompressionScheme === n$1 ) {
  86903. if ( ! _zstd ) {
  86904. _zstd = new Promise( async ( resolve ) => {
  86905. const zstd = new ZSTDDecoder();
  86906. await zstd.init();
  86907. resolve( zstd );
  86908. } );
  86909. }
  86910. levelData = ( await _zstd ).decode( level.levelData, level.uncompressedByteLength );
  86911. } else {
  86912. throw new Error( 'THREE.KTX2Loader: Unsupported supercompressionScheme.' );
  86913. }
  86914. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  86915. view = new Float32Array(
  86916. levelData.buffer,
  86917. levelData.byteOffset,
  86918. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  86919. );
  86920. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  86921. view = new Uint16Array(
  86922. levelData.buffer,
  86923. levelData.byteOffset,
  86924. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  86925. );
  86926. } else {
  86927. view = levelData;
  86928. }
  86929. //
  86930. const texture = pixelDepth === 0
  86931. ? new DataTexture( view, pixelWidth, pixelHeight )
  86932. : new Data3DTexture( view, pixelWidth, pixelHeight, pixelDepth );
  86933. texture.type = TYPE_MAP[ vkFormat ];
  86934. texture.format = FORMAT_MAP[ vkFormat ];
  86935. texture.encoding = ENCODING_MAP[ vkFormat ] || LinearEncoding;
  86936. texture.needsUpdate = true;
  86937. //
  86938. return Promise.resolve( texture );
  86939. }
  86940. // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
  86941. // Copyright (C) 2016-2020, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  86942. var MeshoptDecoder = (function() {
  86943. "use strict";
  86944. // Built with clang version 11.0.0 (https://github.com/llvm/llvm-project.git 0160ad802e899c2922bc9b29564080c22eb0908c)
  86945. // Built from meshoptimizer 0.14
  86946. 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";
  86947. 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";
  86948. // Uses bulk-memory and simd extensions
  86949. 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]);
  86950. // Used to unpack wasm
  86951. 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]);
  86952. if (typeof WebAssembly !== 'object') {
  86953. // This module requires WebAssembly to function
  86954. return {
  86955. supported: false,
  86956. };
  86957. }
  86958. var wasm = wasm_base;
  86959. if (WebAssembly.validate(detector)) {
  86960. wasm = wasm_simd;
  86961. console.log("Warning: meshopt_decoder is using experimental SIMD support");
  86962. }
  86963. var instance;
  86964. var promise =
  86965. WebAssembly.instantiate(unpack(wasm), {})
  86966. .then(function(result) {
  86967. instance = result.instance;
  86968. instance.exports.__wasm_call_ctors();
  86969. });
  86970. function unpack(data) {
  86971. var result = new Uint8Array(data.length);
  86972. for (var i = 0; i < data.length; ++i) {
  86973. var ch = data.charCodeAt(i);
  86974. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  86975. }
  86976. var write = 0;
  86977. for (var i = 0; i < data.length; ++i) {
  86978. result[write++] = (result[i] < 60) ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  86979. }
  86980. return result.buffer.slice(0, write);
  86981. }
  86982. function decode(fun, target, count, size, source, filter) {
  86983. var sbrk = instance.exports.sbrk;
  86984. var count4 = (count + 3) & ~3; // pad for SIMD filter
  86985. var tp = sbrk(count4 * size);
  86986. var sp = sbrk(source.length);
  86987. var heap = new Uint8Array(instance.exports.memory.buffer);
  86988. heap.set(source, sp);
  86989. var res = fun(tp, count, size, sp, source.length);
  86990. if (res == 0 && filter) {
  86991. filter(tp, count4, size);
  86992. }
  86993. target.set(heap.subarray(tp, tp + count * size));
  86994. sbrk(tp - sbrk(0));
  86995. if (res != 0) {
  86996. throw new Error("Malformed buffer data: " + res);
  86997. }
  86998. };
  86999. var filters = {
  87000. // legacy index-based enums for glTF
  87001. 0: "",
  87002. 1: "meshopt_decodeFilterOct",
  87003. 2: "meshopt_decodeFilterQuat",
  87004. 3: "meshopt_decodeFilterExp",
  87005. // string-based enums for glTF
  87006. NONE: "",
  87007. OCTAHEDRAL: "meshopt_decodeFilterOct",
  87008. QUATERNION: "meshopt_decodeFilterQuat",
  87009. EXPONENTIAL: "meshopt_decodeFilterExp",
  87010. };
  87011. var decoders = {
  87012. // legacy index-based enums for glTF
  87013. 0: "meshopt_decodeVertexBuffer",
  87014. 1: "meshopt_decodeIndexBuffer",
  87015. 2: "meshopt_decodeIndexSequence",
  87016. // string-based enums for glTF
  87017. ATTRIBUTES: "meshopt_decodeVertexBuffer",
  87018. TRIANGLES: "meshopt_decodeIndexBuffer",
  87019. INDICES: "meshopt_decodeIndexSequence",
  87020. };
  87021. return {
  87022. ready: promise,
  87023. supported: true,
  87024. decodeVertexBuffer: function(target, count, size, source, filter) {
  87025. decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
  87026. },
  87027. decodeIndexBuffer: function(target, count, size, source) {
  87028. decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
  87029. },
  87030. decodeIndexSequence: function(target, count, size, source) {
  87031. decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
  87032. },
  87033. decodeGltfBuffer: function(target, count, size, source, mode, filter) {
  87034. decode(instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
  87035. }
  87036. };
  87037. })();
  87038. var DDSLoader = function ( manager ) {
  87039. CompressedTextureLoader.call( this, manager );
  87040. };
  87041. DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prototype ), {
  87042. constructor: DDSLoader,
  87043. parse: function ( buffer, loadMipmaps ) {
  87044. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  87045. // Adapted from @toji's DDS utils
  87046. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  87047. // All values and structures referenced from:
  87048. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87049. var DDS_MAGIC = 0x20534444;
  87050. // var DDSD_CAPS = 0x1;
  87051. // var DDSD_HEIGHT = 0x2;
  87052. // var DDSD_WIDTH = 0x4;
  87053. // var DDSD_PITCH = 0x8;
  87054. // var DDSD_PIXELFORMAT = 0x1000;
  87055. var DDSD_MIPMAPCOUNT = 0x20000;
  87056. // var DDSD_LINEARSIZE = 0x80000;
  87057. // var DDSD_DEPTH = 0x800000;
  87058. // var DDSCAPS_COMPLEX = 0x8;
  87059. // var DDSCAPS_MIPMAP = 0x400000;
  87060. // var DDSCAPS_TEXTURE = 0x1000;
  87061. var DDSCAPS2_CUBEMAP = 0x200;
  87062. var DDSCAPS2_CUBEMAP_POSITIVEX = 0x400;
  87063. var DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800;
  87064. var DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000;
  87065. var DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000;
  87066. var DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000;
  87067. var DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000;
  87068. // var DDSCAPS2_VOLUME = 0x200000;
  87069. // var DDPF_ALPHAPIXELS = 0x1;
  87070. // var DDPF_ALPHA = 0x2;
  87071. var DDPF_FOURCC = 0x4;
  87072. // var DDPF_RGB = 0x40;
  87073. // var DDPF_YUV = 0x200;
  87074. // var DDPF_LUMINANCE = 0x20000;
  87075. function fourCCToInt32( value ) {
  87076. return value.charCodeAt( 0 ) +
  87077. ( value.charCodeAt( 1 ) << 8 ) +
  87078. ( value.charCodeAt( 2 ) << 16 ) +
  87079. ( value.charCodeAt( 3 ) << 24 );
  87080. }
  87081. function int32ToFourCC( value ) {
  87082. return String.fromCharCode(
  87083. value & 0xff,
  87084. ( value >> 8 ) & 0xff,
  87085. ( value >> 16 ) & 0xff,
  87086. ( value >> 24 ) & 0xff
  87087. );
  87088. }
  87089. function loadARGBMip( buffer, dataOffset, width, height ) {
  87090. var dataLength = width * height * 4;
  87091. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  87092. var byteArray = new Uint8Array( dataLength );
  87093. var dst = 0;
  87094. var src = 0;
  87095. for ( var y = 0; y < height; y ++ ) {
  87096. for ( var x = 0; x < width; x ++ ) {
  87097. var b = srcBuffer[ src ]; src ++;
  87098. var g = srcBuffer[ src ]; src ++;
  87099. var r = srcBuffer[ src ]; src ++;
  87100. var a = srcBuffer[ src ]; src ++;
  87101. byteArray[ dst ] = r; dst ++; //r
  87102. byteArray[ dst ] = g; dst ++; //g
  87103. byteArray[ dst ] = b; dst ++; //b
  87104. byteArray[ dst ] = a; dst ++; //a
  87105. }
  87106. }
  87107. return byteArray;
  87108. }
  87109. var FOURCC_DXT1 = fourCCToInt32( 'DXT1' );
  87110. var FOURCC_DXT3 = fourCCToInt32( 'DXT3' );
  87111. var FOURCC_DXT5 = fourCCToInt32( 'DXT5' );
  87112. var FOURCC_ETC1 = fourCCToInt32( 'ETC1' );
  87113. var headerLengthInt = 31; // The header length in 32 bit ints
  87114. // Offsets into the header array
  87115. var off_magic = 0;
  87116. var off_size = 1;
  87117. var off_flags = 2;
  87118. var off_height = 3;
  87119. var off_width = 4;
  87120. var off_mipmapCount = 7;
  87121. var off_pfFlags = 20;
  87122. var off_pfFourCC = 21;
  87123. var off_RGBBitCount = 22;
  87124. var off_RBitMask = 23;
  87125. var off_GBitMask = 24;
  87126. var off_BBitMask = 25;
  87127. var off_ABitMask = 26;
  87128. // var off_caps = 27;
  87129. var off_caps2 = 28;
  87130. // var off_caps3 = 29;
  87131. // var off_caps4 = 30;
  87132. // Parse header
  87133. var header = new Int32Array( buffer, 0, headerLengthInt );
  87134. if ( header[ off_magic ] !== DDS_MAGIC ) {
  87135. console.error( 'THREE.DDSLoader.parse: Invalid magic number in DDS header.' );
  87136. return dds;
  87137. }
  87138. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  87139. console.error( 'THREE.DDSLoader.parse: Unsupported format, must contain a FourCC code.' );
  87140. return dds;
  87141. }
  87142. var blockBytes;
  87143. var fourCC = header[ off_pfFourCC ];
  87144. var isRGBAUncompressed = false;
  87145. switch ( fourCC ) {
  87146. case FOURCC_DXT1:
  87147. blockBytes = 8;
  87148. dds.format = RGB_S3TC_DXT1_Format;
  87149. break;
  87150. case FOURCC_DXT3:
  87151. blockBytes = 16;
  87152. dds.format = RGBA_S3TC_DXT3_Format;
  87153. break;
  87154. case FOURCC_DXT5:
  87155. blockBytes = 16;
  87156. dds.format = RGBA_S3TC_DXT5_Format$1;
  87157. break;
  87158. case FOURCC_ETC1:
  87159. blockBytes = 8;
  87160. dds.format = RGB_ETC1_Format;
  87161. break;
  87162. default:
  87163. if ( header[ off_RGBBitCount ] === 32
  87164. && header[ off_RBitMask ] & 0xff0000
  87165. && header[ off_GBitMask ] & 0xff00
  87166. && header[ off_BBitMask ] & 0xff
  87167. && header[ off_ABitMask ] & 0xff000000 ) {
  87168. isRGBAUncompressed = true;
  87169. blockBytes = 64;
  87170. dds.format = RGBAFormat;
  87171. } else {
  87172. console.error( 'THREE.DDSLoader.parse: Unsupported FourCC code ', int32ToFourCC( fourCC ) );
  87173. return dds;
  87174. }
  87175. }
  87176. dds.mipmapCount = 1;
  87177. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  87178. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  87179. }
  87180. var caps2 = header[ off_caps2 ];
  87181. dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false;
  87182. if ( dds.isCubemap && (
  87183. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEX ) ||
  87184. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX ) ||
  87185. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEY ) ||
  87186. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY ) ||
  87187. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ ) ||
  87188. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ )
  87189. ) ) {
  87190. console.error( 'THREE.DDSLoader.parse: Incomplete cubemap faces' );
  87191. return dds;
  87192. }
  87193. dds.width = header[ off_width ];
  87194. dds.height = header[ off_height ];
  87195. var dataOffset = header[ off_size ] + 4;
  87196. // Extract mipmaps buffers
  87197. var faces = dds.isCubemap ? 6 : 1;
  87198. for ( var face = 0; face < faces; face ++ ) {
  87199. var width = dds.width;
  87200. var height = dds.height;
  87201. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  87202. if ( isRGBAUncompressed ) {
  87203. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  87204. var dataLength = byteArray.length;
  87205. } else {
  87206. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  87207. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  87208. }
  87209. var mipmap = { 'data': byteArray, 'width': width, 'height': height };
  87210. dds.mipmaps.push( mipmap );
  87211. dataOffset += dataLength;
  87212. width = Math.max( width >> 1, 1 );
  87213. height = Math.max( height >> 1, 1 );
  87214. }
  87215. }
  87216. return dds;
  87217. }
  87218. } );
  87219. //xzw add:----
  87220. let unknownExtensions = {};
  87221. let oldSet = MeshBasicMaterial.prototype.setValues;
  87222. MeshBasicMaterial.prototype.setValues = function(values){
  87223. return oldSet.call(this,values)
  87224. };
  87225. class GLTFLoader extends Loader {
  87226. constructor( manager, renderer, urlPrefix ) {
  87227. super( manager );
  87228. //xzw add:
  87229. this.dracoLoader = new DRACOLoader;
  87230. this.ktx2Loader = new KTX2Loader;
  87231. this.meshoptDecoder = MeshoptDecoder;
  87232. this.ddsLoader = new DDSLoader; //这个没测过
  87233. //路径相对于index.html
  87234. this.dracoLoader.setDecoderPath( urlPrefix + 'three.js/loaders/draco/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/draco/gltf/' 版本可升级 */); //这两个路径可以自己改。在laser的环境也要放一份这个路径
  87235. this.ktx2Loader.setTranscoderPath(urlPrefix + 'three.js/loaders/basic/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/basis/' 版本可升级 */).detectSupport( renderer );
  87236. this.pluginCallbacks = [];
  87237. this.register( function ( parser ) {
  87238. return new GLTFMaterialsClearcoatExtension( parser );
  87239. } );
  87240. this.register( function ( parser ) {
  87241. return new GLTFTextureBasisUExtension( parser );
  87242. } );
  87243. this.register( function ( parser ) {
  87244. return new GLTFTextureWebPExtension( parser );
  87245. } );
  87246. this.register( function ( parser ) {
  87247. return new GLTFMaterialsSheenExtension( parser );
  87248. } );
  87249. this.register( function ( parser ) {
  87250. return new GLTFMaterialsTransmissionExtension( parser );
  87251. } );
  87252. this.register( function ( parser ) {
  87253. return new GLTFMaterialsVolumeExtension( parser );
  87254. } );
  87255. this.register( function ( parser ) {
  87256. return new GLTFMaterialsIorExtension( parser );
  87257. } );
  87258. this.register( function ( parser ) {
  87259. return new GLTFMaterialsEmissiveStrengthExtension( parser );
  87260. } );
  87261. this.register( function ( parser ) {
  87262. return new GLTFMaterialsSpecularExtension( parser );
  87263. } );
  87264. this.register( function ( parser ) {
  87265. return new GLTFMaterialsIridescenceExtension( parser );
  87266. } );
  87267. this.register( function ( parser ) {
  87268. return new GLTFLightsExtension( parser );
  87269. } );
  87270. this.register( function ( parser ) {
  87271. return new GLTFMeshoptCompression( parser );
  87272. } );
  87273. this.register( function ( parser ) {
  87274. return new GLTFMeshGpuInstancing( parser );
  87275. } );
  87276. }
  87277. load( url, onLoad, onProgress, onError ) {
  87278. const scope = this;
  87279. let resourcePath;
  87280. if ( this.resourcePath !== '' ) {
  87281. resourcePath = this.resourcePath;
  87282. } else if ( this.path !== '' ) {
  87283. resourcePath = this.path;
  87284. } else {
  87285. resourcePath = LoaderUtils.extractUrlBase( url );
  87286. }
  87287. // Tells the LoadingManager to track an extra item, which resolves after
  87288. // the model is fully loaded. This means the count of items loaded will
  87289. // be incorrect, but ensures manager.onLoad() does not fire early.
  87290. this.manager.itemStart( url );
  87291. const _onError = function ( e ) {
  87292. if ( onError ) {
  87293. onError( e );
  87294. } else {
  87295. console.error( e );
  87296. }
  87297. scope.manager.itemError( url );
  87298. scope.manager.itemEnd( url );
  87299. };
  87300. const loader = new FileLoader( this.manager );
  87301. loader.setPath( this.path );
  87302. loader.setResponseType( 'arraybuffer' );
  87303. loader.setRequestHeader( this.requestHeader );
  87304. loader.setWithCredentials( this.withCredentials );
  87305. loader.load( url, function ( data ) {
  87306. try {
  87307. scope.parse( data, resourcePath, function ( gltf ) {
  87308. onLoad( gltf );
  87309. scope.manager.itemEnd( url );
  87310. }, _onError );
  87311. } catch ( e ) {
  87312. _onError( e );
  87313. }
  87314. }, onProgress, _onError );
  87315. }
  87316. setDRACOLoader( dracoLoader ) {
  87317. this.dracoLoader = dracoLoader;
  87318. return this;
  87319. }
  87320. setDDSLoader() {
  87321. throw new Error(
  87322. 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".'
  87323. );
  87324. }
  87325. setKTX2Loader( ktx2Loader ) {
  87326. this.ktx2Loader = ktx2Loader;
  87327. return this;
  87328. }
  87329. setMeshoptDecoder( meshoptDecoder ) {
  87330. this.meshoptDecoder = meshoptDecoder;
  87331. return this;
  87332. }
  87333. register( callback ) {
  87334. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  87335. this.pluginCallbacks.push( callback );
  87336. }
  87337. return this;
  87338. }
  87339. unregister( callback ) {
  87340. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  87341. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  87342. }
  87343. return this;
  87344. }
  87345. parse( data, path, onLoad, onError ) {
  87346. let json;
  87347. const extensions = {};
  87348. const plugins = {};
  87349. if ( typeof data === 'string' ) {
  87350. json = JSON.parse( data );
  87351. } else if ( data instanceof ArrayBuffer ) {
  87352. const magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  87353. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  87354. try {
  87355. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  87356. } catch ( error ) {
  87357. if ( onError ) onError( error );
  87358. return;
  87359. }
  87360. json = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content );
  87361. } else {
  87362. json = JSON.parse( LoaderUtils.decodeText( new Uint8Array( data ) ) );
  87363. }
  87364. } else {
  87365. json = data;
  87366. }
  87367. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  87368. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  87369. return;
  87370. }
  87371. const parser = new GLTFParser( json, {
  87372. path: path || this.resourcePath || '',
  87373. crossOrigin: this.crossOrigin,
  87374. requestHeader: this.requestHeader,
  87375. manager: this.manager,
  87376. ktx2Loader: this.ktx2Loader,
  87377. meshoptDecoder: this.meshoptDecoder
  87378. } );
  87379. parser.fileLoader.setRequestHeader( this.requestHeader );
  87380. for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {
  87381. const plugin = this.pluginCallbacks[ i ]( parser );
  87382. plugins[ plugin.name ] = plugin;
  87383. // Workaround to avoid determining as unknown extension
  87384. // in addUnknownExtensionsToUserData().
  87385. // Remove this workaround if we move all the existing
  87386. // extension handlers to plugin system
  87387. extensions[ plugin.name ] = true;
  87388. }
  87389. if ( json.extensionsUsed ) {
  87390. for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {
  87391. const extensionName = json.extensionsUsed[ i ];
  87392. const extensionsRequired = json.extensionsRequired || [];
  87393. switch ( extensionName ) {
  87394. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  87395. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  87396. break;
  87397. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  87398. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  87399. break;
  87400. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  87401. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  87402. break;
  87403. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  87404. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  87405. break;
  87406. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  87407. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  87408. break;
  87409. default:
  87410. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  87411. if(!unknownExtensions[extensionName]){
  87412. console.warn( 'GLTFLoader: Unknown extension "' + extensionName + '".' ,'使用默认的KHR_materials_unlit材质' );
  87413. unknownExtensions[extensionName] = 1;
  87414. }
  87415. //xzw add: 默认
  87416. json.extensionsRequired = 'KHR_materials_unlit';
  87417. json.materials = [{
  87418. extensions: {KHR_materials_unlit: {}},
  87419. pbrMetallicRoughness:{
  87420. baseColorFactor:[1, 1, 1, 1],
  87421. baseColorTexture: {index: 0, texCoord: 0},
  87422. metallicFactor: 0,
  87423. roughnessFactor: 0.5,
  87424. }
  87425. }];
  87426. extensions[ json.extensionsRequired ] = new GLTFMaterialsUnlitExtension();
  87427. }
  87428. /*
  87429. 如原先:
  87430. json.materials = KHR_techniques_webgl:{
  87431. technique: 0,
  87432. values:{u_diffuse:{index: 0,texCoord: 0}}
  87433. }
  87434. */
  87435. }
  87436. }
  87437. }
  87438. parser.setExtensions( extensions );
  87439. parser.setPlugins( plugins );
  87440. parser.parse( onLoad, onError );
  87441. }
  87442. parseAsync( data, path ) {
  87443. const scope = this;
  87444. return new Promise( function ( resolve, reject ) {
  87445. scope.parse( data, path, resolve, reject );
  87446. } );
  87447. }
  87448. }
  87449. /* GLTFREGISTRY */
  87450. function GLTFRegistry() {
  87451. let objects = {};
  87452. return {
  87453. get: function ( key ) {
  87454. return objects[ key ];
  87455. },
  87456. add: function ( key, object ) {
  87457. objects[ key ] = object;
  87458. },
  87459. remove: function ( key ) {
  87460. delete objects[ key ];
  87461. },
  87462. removeAll: function () {
  87463. objects = {};
  87464. }
  87465. };
  87466. }
  87467. /*********************************/
  87468. /********** EXTENSIONS ***********/
  87469. /*********************************/
  87470. const EXTENSIONS = {
  87471. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  87472. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  87473. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  87474. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  87475. KHR_MATERIALS_IOR: 'KHR_materials_ior',
  87476. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  87477. KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
  87478. KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
  87479. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  87480. KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
  87481. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  87482. KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
  87483. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  87484. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  87485. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  87486. KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
  87487. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  87488. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  87489. EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'
  87490. };
  87491. /**
  87492. * Punctual Lights Extension
  87493. *
  87494. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  87495. */
  87496. class GLTFLightsExtension {
  87497. constructor( parser ) {
  87498. this.parser = parser;
  87499. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  87500. // Object3D instance caches
  87501. this.cache = { refs: {}, uses: {} };
  87502. }
  87503. _markDefs() {
  87504. const parser = this.parser;
  87505. const nodeDefs = this.parser.json.nodes || [];
  87506. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  87507. const nodeDef = nodeDefs[ nodeIndex ];
  87508. if ( nodeDef.extensions
  87509. && nodeDef.extensions[ this.name ]
  87510. && nodeDef.extensions[ this.name ].light !== undefined ) {
  87511. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  87512. }
  87513. }
  87514. }
  87515. _loadLight( lightIndex ) {
  87516. const parser = this.parser;
  87517. const cacheKey = 'light:' + lightIndex;
  87518. let dependency = parser.cache.get( cacheKey );
  87519. if ( dependency ) return dependency;
  87520. const json = parser.json;
  87521. const extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  87522. const lightDefs = extensions.lights || [];
  87523. const lightDef = lightDefs[ lightIndex ];
  87524. let lightNode;
  87525. const color = new Color( 0xffffff );
  87526. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  87527. const range = lightDef.range !== undefined ? lightDef.range : 0;
  87528. switch ( lightDef.type ) {
  87529. case 'directional':
  87530. lightNode = new DirectionalLight( color );
  87531. lightNode.target.position.set( 0, 0, - 1 );
  87532. lightNode.add( lightNode.target );
  87533. break;
  87534. case 'point':
  87535. lightNode = new PointLight( color );
  87536. lightNode.distance = range;
  87537. break;
  87538. case 'spot':
  87539. lightNode = new SpotLight( color );
  87540. lightNode.distance = range;
  87541. // Handle spotlight properties.
  87542. lightDef.spot = lightDef.spot || {};
  87543. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  87544. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  87545. lightNode.angle = lightDef.spot.outerConeAngle;
  87546. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  87547. lightNode.target.position.set( 0, 0, - 1 );
  87548. lightNode.add( lightNode.target );
  87549. break;
  87550. default:
  87551. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  87552. }
  87553. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  87554. // here, because node-level parsing will only override position if explicitly specified.
  87555. lightNode.position.set( 0, 0, 0 );
  87556. lightNode.decay = 2;
  87557. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  87558. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  87559. dependency = Promise.resolve( lightNode );
  87560. parser.cache.add( cacheKey, dependency );
  87561. return dependency;
  87562. }
  87563. createNodeAttachment( nodeIndex ) {
  87564. const self = this;
  87565. const parser = this.parser;
  87566. const json = parser.json;
  87567. const nodeDef = json.nodes[ nodeIndex ];
  87568. const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  87569. const lightIndex = lightDef.light;
  87570. if ( lightIndex === undefined ) return null;
  87571. return this._loadLight( lightIndex ).then( function ( light ) {
  87572. return parser._getNodeRef( self.cache, lightIndex, light );
  87573. } );
  87574. }
  87575. }
  87576. /**
  87577. * Unlit Materials Extension
  87578. *
  87579. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  87580. */
  87581. class GLTFMaterialsUnlitExtension {
  87582. constructor() {
  87583. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  87584. }
  87585. getMaterialType() {
  87586. return MeshBasicMaterial;
  87587. }
  87588. extendParams( materialParams, materialDef, parser ) {
  87589. const pending = [];
  87590. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  87591. materialParams.opacity = 1.0;
  87592. const metallicRoughness = materialDef.pbrMetallicRoughness;
  87593. if ( metallicRoughness ) {
  87594. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  87595. const array = metallicRoughness.baseColorFactor;
  87596. materialParams.color.fromArray( array );
  87597. materialParams.opacity = array[ 3 ];
  87598. }
  87599. if ( metallicRoughness.baseColorTexture !== undefined ) {
  87600. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding ) );
  87601. }
  87602. }
  87603. return Promise.all( pending );
  87604. }
  87605. }
  87606. /**
  87607. * Materials Emissive Strength Extension
  87608. *
  87609. * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
  87610. */
  87611. class GLTFMaterialsEmissiveStrengthExtension {
  87612. constructor( parser ) {
  87613. this.parser = parser;
  87614. this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
  87615. }
  87616. extendMaterialParams( materialIndex, materialParams ) {
  87617. const parser = this.parser;
  87618. const materialDef = parser.json.materials[ materialIndex ];
  87619. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  87620. return Promise.resolve();
  87621. }
  87622. const emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength;
  87623. if ( emissiveStrength !== undefined ) {
  87624. materialParams.emissiveIntensity = emissiveStrength;
  87625. }
  87626. return Promise.resolve();
  87627. }
  87628. }
  87629. /**
  87630. * Clearcoat Materials Extension
  87631. *
  87632. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  87633. */
  87634. class GLTFMaterialsClearcoatExtension {
  87635. constructor( parser ) {
  87636. this.parser = parser;
  87637. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  87638. }
  87639. getMaterialType( materialIndex ) {
  87640. const parser = this.parser;
  87641. const materialDef = parser.json.materials[ materialIndex ];
  87642. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  87643. return MeshPhysicalMaterial;
  87644. }
  87645. extendMaterialParams( materialIndex, materialParams ) {
  87646. const parser = this.parser;
  87647. const materialDef = parser.json.materials[ materialIndex ];
  87648. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  87649. return Promise.resolve();
  87650. }
  87651. const pending = [];
  87652. const extension = materialDef.extensions[ this.name ];
  87653. if ( extension.clearcoatFactor !== undefined ) {
  87654. materialParams.clearcoat = extension.clearcoatFactor;
  87655. }
  87656. if ( extension.clearcoatTexture !== undefined ) {
  87657. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  87658. }
  87659. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  87660. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  87661. }
  87662. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  87663. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  87664. }
  87665. if ( extension.clearcoatNormalTexture !== undefined ) {
  87666. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  87667. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  87668. const scale = extension.clearcoatNormalTexture.scale;
  87669. materialParams.clearcoatNormalScale = new Vector2( scale, scale );
  87670. }
  87671. }
  87672. return Promise.all( pending );
  87673. }
  87674. }
  87675. /**
  87676. * Iridescence Materials Extension
  87677. *
  87678. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
  87679. */
  87680. class GLTFMaterialsIridescenceExtension {
  87681. constructor( parser ) {
  87682. this.parser = parser;
  87683. this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
  87684. }
  87685. getMaterialType( materialIndex ) {
  87686. const parser = this.parser;
  87687. const materialDef = parser.json.materials[ materialIndex ];
  87688. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  87689. return MeshPhysicalMaterial;
  87690. }
  87691. extendMaterialParams( materialIndex, materialParams ) {
  87692. const parser = this.parser;
  87693. const materialDef = parser.json.materials[ materialIndex ];
  87694. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  87695. return Promise.resolve();
  87696. }
  87697. const pending = [];
  87698. const extension = materialDef.extensions[ this.name ];
  87699. if ( extension.iridescenceFactor !== undefined ) {
  87700. materialParams.iridescence = extension.iridescenceFactor;
  87701. }
  87702. if ( extension.iridescenceTexture !== undefined ) {
  87703. pending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) );
  87704. }
  87705. if ( extension.iridescenceIor !== undefined ) {
  87706. materialParams.iridescenceIOR = extension.iridescenceIor;
  87707. }
  87708. if ( materialParams.iridescenceThicknessRange === undefined ) {
  87709. materialParams.iridescenceThicknessRange = [ 100, 400 ];
  87710. }
  87711. if ( extension.iridescenceThicknessMinimum !== undefined ) {
  87712. materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum;
  87713. }
  87714. if ( extension.iridescenceThicknessMaximum !== undefined ) {
  87715. materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum;
  87716. }
  87717. if ( extension.iridescenceThicknessTexture !== undefined ) {
  87718. pending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) );
  87719. }
  87720. return Promise.all( pending );
  87721. }
  87722. }
  87723. /**
  87724. * Sheen Materials Extension
  87725. *
  87726. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
  87727. */
  87728. class GLTFMaterialsSheenExtension {
  87729. constructor( parser ) {
  87730. this.parser = parser;
  87731. this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
  87732. }
  87733. getMaterialType( materialIndex ) {
  87734. const parser = this.parser;
  87735. const materialDef = parser.json.materials[ materialIndex ];
  87736. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  87737. return MeshPhysicalMaterial;
  87738. }
  87739. extendMaterialParams( materialIndex, materialParams ) {
  87740. const parser = this.parser;
  87741. const materialDef = parser.json.materials[ materialIndex ];
  87742. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  87743. return Promise.resolve();
  87744. }
  87745. const pending = [];
  87746. materialParams.sheenColor = new Color( 0, 0, 0 );
  87747. materialParams.sheenRoughness = 0;
  87748. materialParams.sheen = 1;
  87749. const extension = materialDef.extensions[ this.name ];
  87750. if ( extension.sheenColorFactor !== undefined ) {
  87751. materialParams.sheenColor.fromArray( extension.sheenColorFactor );
  87752. }
  87753. if ( extension.sheenRoughnessFactor !== undefined ) {
  87754. materialParams.sheenRoughness = extension.sheenRoughnessFactor;
  87755. }
  87756. if ( extension.sheenColorTexture !== undefined ) {
  87757. pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, sRGBEncoding ) );
  87758. }
  87759. if ( extension.sheenRoughnessTexture !== undefined ) {
  87760. pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );
  87761. }
  87762. return Promise.all( pending );
  87763. }
  87764. }
  87765. /**
  87766. * Transmission Materials Extension
  87767. *
  87768. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  87769. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  87770. */
  87771. class GLTFMaterialsTransmissionExtension {
  87772. constructor( parser ) {
  87773. this.parser = parser;
  87774. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  87775. }
  87776. getMaterialType( materialIndex ) {
  87777. const parser = this.parser;
  87778. const materialDef = parser.json.materials[ materialIndex ];
  87779. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  87780. return MeshPhysicalMaterial;
  87781. }
  87782. extendMaterialParams( materialIndex, materialParams ) {
  87783. const parser = this.parser;
  87784. const materialDef = parser.json.materials[ materialIndex ];
  87785. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  87786. return Promise.resolve();
  87787. }
  87788. const pending = [];
  87789. const extension = materialDef.extensions[ this.name ];
  87790. if ( extension.transmissionFactor !== undefined ) {
  87791. materialParams.transmission = extension.transmissionFactor;
  87792. }
  87793. if ( extension.transmissionTexture !== undefined ) {
  87794. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  87795. }
  87796. return Promise.all( pending );
  87797. }
  87798. }
  87799. /**
  87800. * Materials Volume Extension
  87801. *
  87802. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  87803. */
  87804. class GLTFMaterialsVolumeExtension {
  87805. constructor( parser ) {
  87806. this.parser = parser;
  87807. this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
  87808. }
  87809. getMaterialType( materialIndex ) {
  87810. const parser = this.parser;
  87811. const materialDef = parser.json.materials[ materialIndex ];
  87812. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  87813. return MeshPhysicalMaterial;
  87814. }
  87815. extendMaterialParams( materialIndex, materialParams ) {
  87816. const parser = this.parser;
  87817. const materialDef = parser.json.materials[ materialIndex ];
  87818. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  87819. return Promise.resolve();
  87820. }
  87821. const pending = [];
  87822. const extension = materialDef.extensions[ this.name ];
  87823. materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
  87824. if ( extension.thicknessTexture !== undefined ) {
  87825. pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );
  87826. }
  87827. materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
  87828. const colorArray = extension.attenuationColor || [ 1, 1, 1 ];
  87829. materialParams.attenuationColor = new Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
  87830. return Promise.all( pending );
  87831. }
  87832. }
  87833. /**
  87834. * Materials ior Extension
  87835. *
  87836. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  87837. */
  87838. class GLTFMaterialsIorExtension {
  87839. constructor( parser ) {
  87840. this.parser = parser;
  87841. this.name = EXTENSIONS.KHR_MATERIALS_IOR;
  87842. }
  87843. getMaterialType( materialIndex ) {
  87844. const parser = this.parser;
  87845. const materialDef = parser.json.materials[ materialIndex ];
  87846. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  87847. return MeshPhysicalMaterial;
  87848. }
  87849. extendMaterialParams( materialIndex, materialParams ) {
  87850. const parser = this.parser;
  87851. const materialDef = parser.json.materials[ materialIndex ];
  87852. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  87853. return Promise.resolve();
  87854. }
  87855. const extension = materialDef.extensions[ this.name ];
  87856. materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
  87857. return Promise.resolve();
  87858. }
  87859. }
  87860. /**
  87861. * Materials specular Extension
  87862. *
  87863. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  87864. */
  87865. class GLTFMaterialsSpecularExtension {
  87866. constructor( parser ) {
  87867. this.parser = parser;
  87868. this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
  87869. }
  87870. getMaterialType( materialIndex ) {
  87871. const parser = this.parser;
  87872. const materialDef = parser.json.materials[ materialIndex ];
  87873. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  87874. return MeshPhysicalMaterial;
  87875. }
  87876. extendMaterialParams( materialIndex, materialParams ) {
  87877. const parser = this.parser;
  87878. const materialDef = parser.json.materials[ materialIndex ];
  87879. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  87880. return Promise.resolve();
  87881. }
  87882. const pending = [];
  87883. const extension = materialDef.extensions[ this.name ];
  87884. materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
  87885. if ( extension.specularTexture !== undefined ) {
  87886. pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );
  87887. }
  87888. const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];
  87889. materialParams.specularColor = new Color( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
  87890. if ( extension.specularColorTexture !== undefined ) {
  87891. pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, sRGBEncoding ) );
  87892. }
  87893. return Promise.all( pending );
  87894. }
  87895. }
  87896. /**
  87897. * BasisU Texture Extension
  87898. *
  87899. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  87900. */
  87901. class GLTFTextureBasisUExtension {
  87902. constructor( parser ) {
  87903. this.parser = parser;
  87904. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  87905. }
  87906. loadTexture( textureIndex ) {
  87907. const parser = this.parser;
  87908. const json = parser.json;
  87909. const textureDef = json.textures[ textureIndex ];
  87910. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  87911. return null;
  87912. }
  87913. const extension = textureDef.extensions[ this.name ];
  87914. const loader = parser.options.ktx2Loader;
  87915. if ( ! loader ) {
  87916. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  87917. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  87918. } else {
  87919. // Assumes that the extension is optional and that a fallback texture is present
  87920. return null;
  87921. }
  87922. }
  87923. return parser.loadTextureImage( textureIndex, extension.source, loader );
  87924. }
  87925. }
  87926. /**
  87927. * WebP Texture Extension
  87928. *
  87929. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  87930. */
  87931. class GLTFTextureWebPExtension {
  87932. constructor( parser ) {
  87933. this.parser = parser;
  87934. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  87935. this.isSupported = null;
  87936. }
  87937. loadTexture( textureIndex ) {
  87938. const name = this.name;
  87939. const parser = this.parser;
  87940. const json = parser.json;
  87941. const textureDef = json.textures[ textureIndex ];
  87942. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  87943. return null;
  87944. }
  87945. const extension = textureDef.extensions[ name ];
  87946. const source = json.images[ extension.source ];
  87947. let loader = parser.textureLoader;
  87948. if ( source.uri ) {
  87949. const handler = parser.options.manager.getHandler( source.uri );
  87950. if ( handler !== null ) loader = handler;
  87951. }
  87952. return this.detectSupport().then( function ( isSupported ) {
  87953. if ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader );
  87954. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  87955. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  87956. }
  87957. // Fall back to PNG or JPEG.
  87958. return parser.loadTexture( textureIndex );
  87959. } );
  87960. }
  87961. detectSupport() {
  87962. if ( ! this.isSupported ) {
  87963. this.isSupported = new Promise( function ( resolve ) {
  87964. const image = new Image();
  87965. // Lossy test image. Support for lossy images doesn't guarantee support for all
  87966. // WebP images, unfortunately.
  87967. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  87968. image.onload = image.onerror = function () {
  87969. resolve( image.height === 1 );
  87970. };
  87971. } );
  87972. }
  87973. return this.isSupported;
  87974. }
  87975. }
  87976. /**
  87977. * meshopt BufferView Compression Extension
  87978. *
  87979. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  87980. */
  87981. class GLTFMeshoptCompression {
  87982. constructor( parser ) {
  87983. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  87984. this.parser = parser;
  87985. }
  87986. loadBufferView( index ) {
  87987. const json = this.parser.json;
  87988. const bufferView = json.bufferViews[ index ];
  87989. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  87990. const extensionDef = bufferView.extensions[ this.name ];
  87991. const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  87992. const decoder = this.parser.options.meshoptDecoder;
  87993. if ( ! decoder || ! decoder.supported ) {
  87994. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  87995. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  87996. } else {
  87997. // Assumes that the extension is optional and that fallback buffer data is present
  87998. return null;
  87999. }
  88000. }
  88001. return buffer.then( function ( res ) {
  88002. const byteOffset = extensionDef.byteOffset || 0;
  88003. const byteLength = extensionDef.byteLength || 0;
  88004. const count = extensionDef.count;
  88005. const stride = extensionDef.byteStride;
  88006. const source = new Uint8Array( res, byteOffset, byteLength );
  88007. if ( decoder.decodeGltfBufferAsync ) {
  88008. return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) {
  88009. return res.buffer;
  88010. } );
  88011. } else {
  88012. // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync
  88013. return decoder.ready.then( function () {
  88014. const result = new ArrayBuffer( count * stride );
  88015. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  88016. return result;
  88017. } );
  88018. }
  88019. } );
  88020. } else {
  88021. return null;
  88022. }
  88023. }
  88024. }
  88025. /**
  88026. * GPU Instancing Extension
  88027. *
  88028. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
  88029. *
  88030. */
  88031. class GLTFMeshGpuInstancing {
  88032. constructor( parser ) {
  88033. this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
  88034. this.parser = parser;
  88035. }
  88036. createNodeMesh( nodeIndex ) {
  88037. const json = this.parser.json;
  88038. const nodeDef = json.nodes[ nodeIndex ];
  88039. if ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] ||
  88040. nodeDef.mesh === undefined ) {
  88041. return null;
  88042. }
  88043. const meshDef = json.meshes[ nodeDef.mesh ];
  88044. // No Points or Lines + Instancing support yet
  88045. for ( const primitive of meshDef.primitives ) {
  88046. if ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&
  88047. primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&
  88048. primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&
  88049. primitive.mode !== undefined ) {
  88050. return null;
  88051. }
  88052. }
  88053. const extensionDef = nodeDef.extensions[ this.name ];
  88054. const attributesDef = extensionDef.attributes;
  88055. // @TODO: Can we support InstancedMesh + SkinnedMesh?
  88056. const pending = [];
  88057. const attributes = {};
  88058. for ( const key in attributesDef ) {
  88059. pending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => {
  88060. attributes[ key ] = accessor;
  88061. return attributes[ key ];
  88062. } ) );
  88063. }
  88064. if ( pending.length < 1 ) {
  88065. return null;
  88066. }
  88067. pending.push( this.parser.createNodeMesh( nodeIndex ) );
  88068. return Promise.all( pending ).then( results => {
  88069. const nodeObject = results.pop();
  88070. const meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ];
  88071. const count = results[ 0 ].count; // All attribute counts should be same
  88072. const instancedMeshes = [];
  88073. for ( const mesh of meshes ) {
  88074. // Temporal variables
  88075. const m = new Matrix4();
  88076. const p = new Vector3();
  88077. const q = new Quaternion();
  88078. const s = new Vector3( 1, 1, 1 );
  88079. const instancedMesh = new InstancedMesh( mesh.geometry, mesh.material, count );
  88080. for ( let i = 0; i < count; i ++ ) {
  88081. if ( attributes.TRANSLATION ) {
  88082. p.fromBufferAttribute( attributes.TRANSLATION, i );
  88083. }
  88084. if ( attributes.ROTATION ) {
  88085. q.fromBufferAttribute( attributes.ROTATION, i );
  88086. }
  88087. if ( attributes.SCALE ) {
  88088. s.fromBufferAttribute( attributes.SCALE, i );
  88089. }
  88090. instancedMesh.setMatrixAt( i, m.compose( p, q, s ) );
  88091. }
  88092. // Add instance attributes to the geometry, excluding TRS.
  88093. for ( const attributeName in attributes ) {
  88094. if ( attributeName !== 'TRANSLATION' &&
  88095. attributeName !== 'ROTATION' &&
  88096. attributeName !== 'SCALE' ) {
  88097. mesh.geometry.setAttribute( attributeName, attributes[ attributeName ] );
  88098. }
  88099. }
  88100. // Just in case
  88101. Object3D.prototype.copy.call( instancedMesh, mesh );
  88102. // https://github.com/mrdoob/three.js/issues/18334
  88103. instancedMesh.frustumCulled = false;
  88104. this.parser.assignFinalMaterial( instancedMesh );
  88105. instancedMeshes.push( instancedMesh );
  88106. }
  88107. if ( nodeObject.isGroup ) {
  88108. nodeObject.clear();
  88109. nodeObject.add( ... instancedMeshes );
  88110. return nodeObject;
  88111. }
  88112. return instancedMeshes[ 0 ];
  88113. } );
  88114. }
  88115. }
  88116. /* BINARY EXTENSION */
  88117. const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  88118. const BINARY_EXTENSION_HEADER_LENGTH = 12;
  88119. const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  88120. class GLTFBinaryExtension {
  88121. constructor( data ) {
  88122. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  88123. this.content = null;
  88124. this.body = null;
  88125. const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  88126. this.header = {
  88127. magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  88128. version: headerView.getUint32( 4, true ),
  88129. length: headerView.getUint32( 8, true )
  88130. };
  88131. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  88132. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  88133. } else if ( this.header.version < 2.0 ) {
  88134. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  88135. }
  88136. const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
  88137. const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  88138. let chunkIndex = 0;
  88139. while ( chunkIndex < chunkContentsLength ) {
  88140. const chunkLength = chunkView.getUint32( chunkIndex, true );
  88141. chunkIndex += 4;
  88142. const chunkType = chunkView.getUint32( chunkIndex, true );
  88143. chunkIndex += 4;
  88144. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  88145. const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  88146. this.content = LoaderUtils.decodeText( contentArray );
  88147. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  88148. const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  88149. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  88150. }
  88151. // Clients must ignore chunks with unknown types.
  88152. chunkIndex += chunkLength;
  88153. }
  88154. if ( this.content === null ) {
  88155. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  88156. }
  88157. }
  88158. }
  88159. /**
  88160. * DRACO Mesh Compression Extension
  88161. *
  88162. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  88163. */
  88164. class GLTFDracoMeshCompressionExtension {
  88165. constructor( json, dracoLoader ) {
  88166. if ( ! dracoLoader ) {
  88167. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  88168. }
  88169. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  88170. this.json = json;
  88171. this.dracoLoader = dracoLoader;
  88172. this.dracoLoader.preload();
  88173. }
  88174. decodePrimitive( primitive, parser ) {
  88175. const json = this.json;
  88176. const dracoLoader = this.dracoLoader;
  88177. const bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  88178. const gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  88179. const threeAttributeMap = {};
  88180. const attributeNormalizedMap = {};
  88181. const attributeTypeMap = {};
  88182. for ( const attributeName in gltfAttributeMap ) {
  88183. const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  88184. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  88185. }
  88186. for ( const attributeName in primitive.attributes ) {
  88187. const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  88188. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  88189. const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  88190. const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  88191. attributeTypeMap[ threeAttributeName ] = componentType.name;
  88192. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  88193. }
  88194. }
  88195. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  88196. return new Promise( function ( resolve ) {
  88197. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  88198. for ( const attributeName in geometry.attributes ) {
  88199. const attribute = geometry.attributes[ attributeName ];
  88200. const normalized = attributeNormalizedMap[ attributeName ];
  88201. if ( normalized !== undefined ) attribute.normalized = normalized;
  88202. }
  88203. resolve( geometry );
  88204. }, threeAttributeMap, attributeTypeMap );
  88205. } );
  88206. } );
  88207. }
  88208. }
  88209. /**
  88210. * Texture Transform Extension
  88211. *
  88212. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  88213. */
  88214. class GLTFTextureTransformExtension {
  88215. constructor() {
  88216. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  88217. }
  88218. extendTexture( texture, transform ) {
  88219. if ( transform.texCoord !== undefined ) {
  88220. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  88221. }
  88222. if ( transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined ) {
  88223. // See https://github.com/mrdoob/three.js/issues/21819.
  88224. return texture;
  88225. }
  88226. texture = texture.clone();
  88227. if ( transform.offset !== undefined ) {
  88228. texture.offset.fromArray( transform.offset );
  88229. }
  88230. if ( transform.rotation !== undefined ) {
  88231. texture.rotation = transform.rotation;
  88232. }
  88233. if ( transform.scale !== undefined ) {
  88234. texture.repeat.fromArray( transform.scale );
  88235. }
  88236. texture.needsUpdate = true;
  88237. return texture;
  88238. }
  88239. }
  88240. /**
  88241. * Specular-Glossiness Extension
  88242. *
  88243. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness
  88244. */
  88245. /**
  88246. * A sub class of StandardMaterial with some of the functionality
  88247. * changed via the `onBeforeCompile` callback
  88248. * @pailhead
  88249. */
  88250. class GLTFMeshStandardSGMaterial extends MeshStandardMaterial {
  88251. constructor( params ) {
  88252. super();
  88253. this.isGLTFSpecularGlossinessMaterial = true;
  88254. //various chunks that need replacing
  88255. const specularMapParsFragmentChunk = [
  88256. '#ifdef USE_SPECULARMAP',
  88257. ' uniform sampler2D specularMap;',
  88258. '#endif'
  88259. ].join( '\n' );
  88260. const glossinessMapParsFragmentChunk = [
  88261. '#ifdef USE_GLOSSINESSMAP',
  88262. ' uniform sampler2D glossinessMap;',
  88263. '#endif'
  88264. ].join( '\n' );
  88265. const specularMapFragmentChunk = [
  88266. 'vec3 specularFactor = specular;',
  88267. '#ifdef USE_SPECULARMAP',
  88268. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  88269. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  88270. ' specularFactor *= texelSpecular.rgb;',
  88271. '#endif'
  88272. ].join( '\n' );
  88273. const glossinessMapFragmentChunk = [
  88274. 'float glossinessFactor = glossiness;',
  88275. '#ifdef USE_GLOSSINESSMAP',
  88276. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  88277. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  88278. ' glossinessFactor *= texelGlossiness.a;',
  88279. '#endif'
  88280. ].join( '\n' );
  88281. const lightPhysicalFragmentChunk = [
  88282. 'PhysicalMaterial material;',
  88283. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  88284. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  88285. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  88286. 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  88287. 'material.roughness += geometryRoughness;',
  88288. 'material.roughness = min( material.roughness, 1.0 );',
  88289. 'material.specularColor = specularFactor;',
  88290. ].join( '\n' );
  88291. const uniforms = {
  88292. specular: { value: new Color().setHex( 0xffffff ) },
  88293. glossiness: { value: 1 },
  88294. specularMap: { value: null },
  88295. glossinessMap: { value: null }
  88296. };
  88297. this._extraUniforms = uniforms;
  88298. this.onBeforeCompile = function ( shader ) {
  88299. for ( const uniformName in uniforms ) {
  88300. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  88301. }
  88302. shader.fragmentShader = shader.fragmentShader
  88303. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  88304. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  88305. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  88306. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  88307. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  88308. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  88309. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  88310. };
  88311. Object.defineProperties( this, {
  88312. specular: {
  88313. get: function () {
  88314. return uniforms.specular.value;
  88315. },
  88316. set: function ( v ) {
  88317. uniforms.specular.value = v;
  88318. }
  88319. },
  88320. specularMap: {
  88321. get: function () {
  88322. return uniforms.specularMap.value;
  88323. },
  88324. set: function ( v ) {
  88325. uniforms.specularMap.value = v;
  88326. if ( v ) {
  88327. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  88328. } else {
  88329. delete this.defines.USE_SPECULARMAP;
  88330. }
  88331. }
  88332. },
  88333. glossiness: {
  88334. get: function () {
  88335. return uniforms.glossiness.value;
  88336. },
  88337. set: function ( v ) {
  88338. uniforms.glossiness.value = v;
  88339. }
  88340. },
  88341. glossinessMap: {
  88342. get: function () {
  88343. return uniforms.glossinessMap.value;
  88344. },
  88345. set: function ( v ) {
  88346. uniforms.glossinessMap.value = v;
  88347. if ( v ) {
  88348. this.defines.USE_GLOSSINESSMAP = '';
  88349. this.defines.USE_UV = '';
  88350. } else {
  88351. delete this.defines.USE_GLOSSINESSMAP;
  88352. delete this.defines.USE_UV;
  88353. }
  88354. }
  88355. }
  88356. } );
  88357. delete this.metalness;
  88358. delete this.roughness;
  88359. delete this.metalnessMap;
  88360. delete this.roughnessMap;
  88361. this.setValues( params );
  88362. }
  88363. copy( source ) {
  88364. super.copy( source );
  88365. this.specularMap = source.specularMap;
  88366. this.specular.copy( source.specular );
  88367. this.glossinessMap = source.glossinessMap;
  88368. this.glossiness = source.glossiness;
  88369. delete this.metalness;
  88370. delete this.roughness;
  88371. delete this.metalnessMap;
  88372. delete this.roughnessMap;
  88373. return this;
  88374. }
  88375. }
  88376. class GLTFMaterialsPbrSpecularGlossinessExtension {
  88377. constructor() {
  88378. this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS;
  88379. this.specularGlossinessParams = [
  88380. 'color',
  88381. 'map',
  88382. 'lightMap',
  88383. 'lightMapIntensity',
  88384. 'aoMap',
  88385. 'aoMapIntensity',
  88386. 'emissive',
  88387. 'emissiveIntensity',
  88388. 'emissiveMap',
  88389. 'bumpMap',
  88390. 'bumpScale',
  88391. 'normalMap',
  88392. 'normalMapType',
  88393. 'displacementMap',
  88394. 'displacementScale',
  88395. 'displacementBias',
  88396. 'specularMap',
  88397. 'specular',
  88398. 'glossinessMap',
  88399. 'glossiness',
  88400. 'alphaMap',
  88401. 'envMap',
  88402. 'envMapIntensity'
  88403. ];
  88404. }
  88405. getMaterialType() {
  88406. return GLTFMeshStandardSGMaterial;
  88407. }
  88408. extendParams( materialParams, materialDef, parser ) {
  88409. const pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  88410. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  88411. materialParams.opacity = 1.0;
  88412. const pending = [];
  88413. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  88414. const array = pbrSpecularGlossiness.diffuseFactor;
  88415. materialParams.color.fromArray( array );
  88416. materialParams.opacity = array[ 3 ];
  88417. }
  88418. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  88419. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture, sRGBEncoding ) );
  88420. }
  88421. materialParams.emissive = new Color( 0.0, 0.0, 0.0 );
  88422. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  88423. materialParams.specular = new Color( 1.0, 1.0, 1.0 );
  88424. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  88425. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  88426. }
  88427. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  88428. const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  88429. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  88430. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef, sRGBEncoding ) );
  88431. }
  88432. return Promise.all( pending );
  88433. }
  88434. createMaterial( materialParams ) {
  88435. const material = new GLTFMeshStandardSGMaterial( materialParams );
  88436. material.fog = true;
  88437. material.color = materialParams.color;
  88438. material.map = materialParams.map === undefined ? null : materialParams.map;
  88439. material.lightMap = null;
  88440. material.lightMapIntensity = 1.0;
  88441. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  88442. material.aoMapIntensity = 1.0;
  88443. material.emissive = materialParams.emissive;
  88444. material.emissiveIntensity = materialParams.emissiveIntensity === undefined ? 1.0 : materialParams.emissiveIntensity;
  88445. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  88446. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  88447. material.bumpScale = 1;
  88448. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  88449. material.normalMapType = TangentSpaceNormalMap;
  88450. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  88451. material.displacementMap = null;
  88452. material.displacementScale = 1;
  88453. material.displacementBias = 0;
  88454. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  88455. material.specular = materialParams.specular;
  88456. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  88457. material.glossiness = materialParams.glossiness;
  88458. material.alphaMap = null;
  88459. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  88460. material.envMapIntensity = 1.0;
  88461. return material;
  88462. }
  88463. }
  88464. /**
  88465. * Mesh Quantization Extension
  88466. *
  88467. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  88468. */
  88469. class GLTFMeshQuantizationExtension {
  88470. constructor() {
  88471. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  88472. }
  88473. }
  88474. /*********************************/
  88475. /********** INTERPOLATION ********/
  88476. /*********************************/
  88477. // Spline Interpolation
  88478. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  88479. class GLTFCubicSplineInterpolant extends Interpolant {
  88480. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  88481. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  88482. }
  88483. copySampleValue_( index ) {
  88484. // Copies a sample value to the result buffer. See description of glTF
  88485. // CUBICSPLINE values layout in interpolate_() function below.
  88486. const result = this.resultBuffer,
  88487. values = this.sampleValues,
  88488. valueSize = this.valueSize,
  88489. offset = index * valueSize * 3 + valueSize;
  88490. for ( let i = 0; i !== valueSize; i ++ ) {
  88491. result[ i ] = values[ offset + i ];
  88492. }
  88493. return result;
  88494. }
  88495. interpolate_( i1, t0, t, t1 ) {
  88496. const result = this.resultBuffer;
  88497. const values = this.sampleValues;
  88498. const stride = this.valueSize;
  88499. const stride2 = stride * 2;
  88500. const stride3 = stride * 3;
  88501. const td = t1 - t0;
  88502. const p = ( t - t0 ) / td;
  88503. const pp = p * p;
  88504. const ppp = pp * p;
  88505. const offset1 = i1 * stride3;
  88506. const offset0 = offset1 - stride3;
  88507. const s2 = - 2 * ppp + 3 * pp;
  88508. const s3 = ppp - pp;
  88509. const s0 = 1 - s2;
  88510. const s1 = s3 - pp + p;
  88511. // Layout of keyframe output values for CUBICSPLINE animations:
  88512. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  88513. for ( let i = 0; i !== stride; i ++ ) {
  88514. const p0 = values[ offset0 + i + stride ]; // splineVertex_k
  88515. const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  88516. const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  88517. const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  88518. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  88519. }
  88520. return result;
  88521. }
  88522. }
  88523. const _q = new Quaternion();
  88524. class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
  88525. interpolate_( i1, t0, t, t1 ) {
  88526. const result = super.interpolate_( i1, t0, t, t1 );
  88527. _q.fromArray( result ).normalize().toArray( result );
  88528. return result;
  88529. }
  88530. }
  88531. /*********************************/
  88532. /********** INTERNALS ************/
  88533. /*********************************/
  88534. /* CONSTANTS */
  88535. const WEBGL_CONSTANTS = {
  88536. FLOAT: 5126,
  88537. //FLOAT_MAT2: 35674,
  88538. FLOAT_MAT3: 35675,
  88539. FLOAT_MAT4: 35676,
  88540. FLOAT_VEC2: 35664,
  88541. FLOAT_VEC3: 35665,
  88542. FLOAT_VEC4: 35666,
  88543. LINEAR: 9729,
  88544. REPEAT: 10497,
  88545. SAMPLER_2D: 35678,
  88546. POINTS: 0,
  88547. LINES: 1,
  88548. LINE_LOOP: 2,
  88549. LINE_STRIP: 3,
  88550. TRIANGLES: 4,
  88551. TRIANGLE_STRIP: 5,
  88552. TRIANGLE_FAN: 6,
  88553. UNSIGNED_BYTE: 5121,
  88554. UNSIGNED_SHORT: 5123
  88555. };
  88556. const WEBGL_COMPONENT_TYPES = {
  88557. 5120: Int8Array,
  88558. 5121: Uint8Array,
  88559. 5122: Int16Array,
  88560. 5123: Uint16Array,
  88561. 5125: Uint32Array,
  88562. 5126: Float32Array
  88563. };
  88564. const WEBGL_FILTERS = {
  88565. 9728: NearestFilter,
  88566. 9729: LinearFilter,
  88567. 9984: NearestMipmapNearestFilter,
  88568. 9985: LinearMipmapNearestFilter,
  88569. 9986: NearestMipmapLinearFilter,
  88570. 9987: LinearMipmapLinearFilter
  88571. };
  88572. const WEBGL_WRAPPINGS = {
  88573. 33071: ClampToEdgeWrapping,
  88574. 33648: MirroredRepeatWrapping,
  88575. 10497: RepeatWrapping
  88576. };
  88577. const WEBGL_TYPE_SIZES = {
  88578. 'SCALAR': 1,
  88579. 'VEC2': 2,
  88580. 'VEC3': 3,
  88581. 'VEC4': 4,
  88582. 'MAT2': 4,
  88583. 'MAT3': 9,
  88584. 'MAT4': 16
  88585. };
  88586. const ATTRIBUTES = {
  88587. POSITION: 'position',
  88588. NORMAL: 'normal',
  88589. TANGENT: 'tangent',
  88590. TEXCOORD_0: 'uv',
  88591. TEXCOORD_1: 'uv2',
  88592. COLOR_0: 'color',
  88593. WEIGHTS_0: 'skinWeight',
  88594. JOINTS_0: 'skinIndex',
  88595. };
  88596. const PATH_PROPERTIES = {
  88597. scale: 'scale',
  88598. translation: 'position',
  88599. rotation: 'quaternion',
  88600. weights: 'morphTargetInfluences'
  88601. };
  88602. const INTERPOLATION = {
  88603. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  88604. // keyframe track will be initialized with a default interpolation type, then modified.
  88605. LINEAR: InterpolateLinear,
  88606. STEP: InterpolateDiscrete
  88607. };
  88608. const ALPHA_MODES = {
  88609. OPAQUE: 'OPAQUE',
  88610. MASK: 'MASK',
  88611. BLEND: 'BLEND'
  88612. };
  88613. /**
  88614. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  88615. */
  88616. function createDefaultMaterial( cache ) {
  88617. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  88618. cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( {
  88619. color: 0xFFFFFF,
  88620. emissive: 0x000000,
  88621. metalness: 1,
  88622. roughness: 1,
  88623. transparent: false,
  88624. depthTest: true,
  88625. side: FrontSide
  88626. } );
  88627. }
  88628. return cache[ 'DefaultMaterial' ];
  88629. }
  88630. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  88631. // Add unknown glTF extensions to an object's userData.
  88632. for ( const name in objectDef.extensions ) {
  88633. if ( knownExtensions[ name ] === undefined ) {
  88634. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  88635. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  88636. }
  88637. }
  88638. }
  88639. /**
  88640. * @param {Object3D|Material|BufferGeometry} object
  88641. * @param {GLTF.definition} gltfDef
  88642. */
  88643. function assignExtrasToUserData( object, gltfDef ) {
  88644. if ( gltfDef.extras !== undefined ) {
  88645. if ( typeof gltfDef.extras === 'object' ) {
  88646. Object.assign( object.userData, gltfDef.extras );
  88647. } else {
  88648. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  88649. }
  88650. }
  88651. }
  88652. /**
  88653. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  88654. *
  88655. * @param {BufferGeometry} geometry
  88656. * @param {Array<GLTF.Target>} targets
  88657. * @param {GLTFParser} parser
  88658. * @return {Promise<BufferGeometry>}
  88659. */
  88660. function addMorphTargets( geometry, targets, parser ) {
  88661. let hasMorphPosition = false;
  88662. let hasMorphNormal = false;
  88663. let hasMorphColor = false;
  88664. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  88665. const target = targets[ i ];
  88666. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  88667. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  88668. if ( target.COLOR_0 !== undefined ) hasMorphColor = true;
  88669. if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;
  88670. }
  88671. if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );
  88672. const pendingPositionAccessors = [];
  88673. const pendingNormalAccessors = [];
  88674. const pendingColorAccessors = [];
  88675. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  88676. const target = targets[ i ];
  88677. if ( hasMorphPosition ) {
  88678. const pendingAccessor = target.POSITION !== undefined
  88679. ? parser.getDependency( 'accessor', target.POSITION )
  88680. : geometry.attributes.position;
  88681. pendingPositionAccessors.push( pendingAccessor );
  88682. }
  88683. if ( hasMorphNormal ) {
  88684. const pendingAccessor = target.NORMAL !== undefined
  88685. ? parser.getDependency( 'accessor', target.NORMAL )
  88686. : geometry.attributes.normal;
  88687. pendingNormalAccessors.push( pendingAccessor );
  88688. }
  88689. if ( hasMorphColor ) {
  88690. const pendingAccessor = target.COLOR_0 !== undefined
  88691. ? parser.getDependency( 'accessor', target.COLOR_0 )
  88692. : geometry.attributes.color;
  88693. pendingColorAccessors.push( pendingAccessor );
  88694. }
  88695. }
  88696. return Promise.all( [
  88697. Promise.all( pendingPositionAccessors ),
  88698. Promise.all( pendingNormalAccessors ),
  88699. Promise.all( pendingColorAccessors )
  88700. ] ).then( function ( accessors ) {
  88701. const morphPositions = accessors[ 0 ];
  88702. const morphNormals = accessors[ 1 ];
  88703. const morphColors = accessors[ 2 ];
  88704. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  88705. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  88706. if ( hasMorphColor ) geometry.morphAttributes.color = morphColors;
  88707. geometry.morphTargetsRelative = true;
  88708. return geometry;
  88709. } );
  88710. }
  88711. /**
  88712. * @param {Mesh} mesh
  88713. * @param {GLTF.Mesh} meshDef
  88714. */
  88715. function updateMorphTargets( mesh, meshDef ) {
  88716. mesh.updateMorphTargets();
  88717. if ( meshDef.weights !== undefined ) {
  88718. for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  88719. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  88720. }
  88721. }
  88722. // .extras has user-defined data, so check that .extras.targetNames is an array.
  88723. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  88724. const targetNames = meshDef.extras.targetNames;
  88725. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  88726. mesh.morphTargetDictionary = {};
  88727. for ( let i = 0, il = targetNames.length; i < il; i ++ ) {
  88728. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  88729. }
  88730. } else {
  88731. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  88732. }
  88733. }
  88734. }
  88735. function createPrimitiveKey( primitiveDef ) {
  88736. const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  88737. let geometryKey;
  88738. if ( dracoExtension ) {
  88739. geometryKey = 'draco:' + dracoExtension.bufferView
  88740. + ':' + dracoExtension.indices
  88741. + ':' + createAttributesKey( dracoExtension.attributes );
  88742. } else {
  88743. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  88744. }
  88745. return geometryKey;
  88746. }
  88747. function createAttributesKey( attributes ) {
  88748. let attributesKey = '';
  88749. const keys = Object.keys( attributes ).sort();
  88750. for ( let i = 0, il = keys.length; i < il; i ++ ) {
  88751. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  88752. }
  88753. return attributesKey;
  88754. }
  88755. function getNormalizedComponentScale( constructor ) {
  88756. // Reference:
  88757. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
  88758. switch ( constructor ) {
  88759. case Int8Array:
  88760. return 1 / 127;
  88761. case Uint8Array:
  88762. return 1 / 255;
  88763. case Int16Array:
  88764. return 1 / 32767;
  88765. case Uint16Array:
  88766. return 1 / 65535;
  88767. default:
  88768. throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );
  88769. }
  88770. }
  88771. function getImageURIMimeType( uri ) {
  88772. if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg';
  88773. if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp';
  88774. return 'image/png';
  88775. }
  88776. /* GLTF PARSER */
  88777. class GLTFParser {
  88778. constructor( json = {}, options = {} ) {
  88779. this.json = json;
  88780. this.extensions = {};
  88781. this.plugins = {};
  88782. this.options = options;
  88783. // loader object cache
  88784. this.cache = new GLTFRegistry();
  88785. // associations between Three.js objects and glTF elements
  88786. this.associations = new Map();
  88787. // BufferGeometry caching
  88788. this.primitiveCache = {};
  88789. // Object3D instance caches
  88790. this.meshCache = { refs: {}, uses: {} };
  88791. this.cameraCache = { refs: {}, uses: {} };
  88792. this.lightCache = { refs: {}, uses: {} };
  88793. this.sourceCache = {};
  88794. this.textureCache = {};
  88795. // Track node names, to ensure no duplicates
  88796. this.nodeNamesUsed = {};
  88797. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  88798. // expensive work of uploading a texture to the GPU off the main thread.
  88799. const isSafari = /^((?!chrome|android).)*safari/i.test( navigator.userAgent ) === true;
  88800. const isFirefox = navigator.userAgent.indexOf( 'Firefox' ) > - 1;
  88801. const firefoxVersion = isFirefox ? navigator.userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1;
  88802. // if ( typeof createImageBitmap === 'undefined' || isSafari || ( isFirefox && firefoxVersion < 98 ) ) {
  88803. this.textureLoader = new TextureLoader( this.options.manager );
  88804. /*} else {
  88805. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,改用TextureLoader by xzw
  88806. this.textureLoader = new ImageBitmapLoader( this.options.manager );
  88807. }
  88808. */
  88809. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  88810. this.textureLoader.setRequestHeader( this.options.requestHeader );
  88811. this.fileLoader = new FileLoader( this.options.manager );
  88812. this.fileLoader.setResponseType( 'arraybuffer' );
  88813. if ( this.options.crossOrigin === 'use-credentials' ) {
  88814. this.fileLoader.setWithCredentials( true );
  88815. }
  88816. }
  88817. setExtensions( extensions ) {
  88818. this.extensions = extensions;
  88819. }
  88820. setPlugins( plugins ) {
  88821. this.plugins = plugins;
  88822. }
  88823. parse( onLoad, onError ) {
  88824. const parser = this;
  88825. const json = this.json;
  88826. const extensions = this.extensions;
  88827. // Clear the loader cache
  88828. this.cache.removeAll();
  88829. // Mark the special nodes/meshes in json for efficient parse
  88830. this._invokeAll( function ( ext ) {
  88831. return ext._markDefs && ext._markDefs();
  88832. } );
  88833. Promise.all( this._invokeAll( function ( ext ) {
  88834. return ext.beforeRoot && ext.beforeRoot();
  88835. } ) ).then( function () {
  88836. return Promise.all( [
  88837. parser.getDependencies( 'scene' ),
  88838. parser.getDependencies( 'animation' ),
  88839. parser.getDependencies( 'camera' ),
  88840. ] );
  88841. } ).then( function ( dependencies ) {
  88842. const result = {
  88843. scene: dependencies[ 0 ][ json.scene || 0 ],
  88844. scenes: dependencies[ 0 ],
  88845. animations: dependencies[ 1 ],
  88846. cameras: dependencies[ 2 ],
  88847. asset: json.asset,
  88848. parser: parser,
  88849. userData: {}
  88850. };
  88851. addUnknownExtensionsToUserData( extensions, result, json );
  88852. assignExtrasToUserData( result, json );
  88853. Promise.all( parser._invokeAll( function ( ext ) {
  88854. return ext.afterRoot && ext.afterRoot( result );
  88855. } ) ).then( function () {
  88856. onLoad( result );
  88857. } );
  88858. } ).catch( onError );
  88859. }
  88860. /**
  88861. * Marks the special nodes/meshes in json for efficient parse.
  88862. */
  88863. _markDefs() {
  88864. const nodeDefs = this.json.nodes || [];
  88865. const skinDefs = this.json.skins || [];
  88866. const meshDefs = this.json.meshes || [];
  88867. // Nothing in the node definition indicates whether it is a Bone or an
  88868. // Object3D. Use the skins' joint references to mark bones.
  88869. for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  88870. const joints = skinDefs[ skinIndex ].joints;
  88871. for ( let i = 0, il = joints.length; i < il; i ++ ) {
  88872. nodeDefs[ joints[ i ] ].isBone = true;
  88873. }
  88874. }
  88875. // Iterate over all nodes, marking references to shared resources,
  88876. // as well as skeleton joints.
  88877. for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  88878. const nodeDef = nodeDefs[ nodeIndex ];
  88879. if ( nodeDef.mesh !== undefined ) {
  88880. this._addNodeRef( this.meshCache, nodeDef.mesh );
  88881. // Nothing in the mesh definition indicates whether it is
  88882. // a SkinnedMesh or Mesh. Use the node's mesh reference
  88883. // to mark SkinnedMesh if node has skin.
  88884. if ( nodeDef.skin !== undefined ) {
  88885. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  88886. }
  88887. }
  88888. if ( nodeDef.camera !== undefined ) {
  88889. this._addNodeRef( this.cameraCache, nodeDef.camera );
  88890. }
  88891. }
  88892. }
  88893. /**
  88894. * Counts references to shared node / Object3D resources. These resources
  88895. * can be reused, or "instantiated", at multiple nodes in the scene
  88896. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  88897. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  88898. * Textures) can be reused directly and are not marked here.
  88899. *
  88900. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  88901. */
  88902. _addNodeRef( cache, index ) {
  88903. if ( index === undefined ) return;
  88904. if ( cache.refs[ index ] === undefined ) {
  88905. cache.refs[ index ] = cache.uses[ index ] = 0;
  88906. }
  88907. cache.refs[ index ] ++;
  88908. }
  88909. /** Returns a reference to a shared resource, cloning it if necessary. */
  88910. _getNodeRef( cache, index, object ) {
  88911. if ( cache.refs[ index ] <= 1 ) return object;
  88912. const ref = object.clone();
  88913. // Propagates mappings to the cloned object, prevents mappings on the
  88914. // original object from being lost.
  88915. const updateMappings = ( original, clone ) => {
  88916. const mappings = this.associations.get( original );
  88917. if ( mappings != null ) {
  88918. this.associations.set( clone, mappings );
  88919. }
  88920. for ( const [ i, child ] of original.children.entries() ) {
  88921. updateMappings( child, clone.children[ i ] );
  88922. }
  88923. };
  88924. updateMappings( object, ref );
  88925. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  88926. return ref;
  88927. }
  88928. _invokeOne( func ) {
  88929. const extensions = Object.values( this.plugins );
  88930. extensions.push( this );
  88931. for ( let i = 0; i < extensions.length; i ++ ) {
  88932. const result = func( extensions[ i ] );
  88933. if ( result ) return result;
  88934. }
  88935. return null;
  88936. }
  88937. _invokeAll( func ) {
  88938. const extensions = Object.values( this.plugins );
  88939. extensions.unshift( this );
  88940. const pending = [];
  88941. for ( let i = 0; i < extensions.length; i ++ ) {
  88942. const result = func( extensions[ i ] );
  88943. if ( result ) pending.push( result );
  88944. }
  88945. return pending;
  88946. }
  88947. /**
  88948. * Requests the specified dependency asynchronously, with caching.
  88949. * @param {string} type
  88950. * @param {number} index
  88951. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  88952. */
  88953. getDependency( type, index ) {
  88954. const cacheKey = type + ':' + index;
  88955. let dependency = this.cache.get( cacheKey );
  88956. if ( ! dependency ) {
  88957. switch ( type ) {
  88958. case 'scene':
  88959. dependency = this.loadScene( index );
  88960. break;
  88961. case 'node':
  88962. dependency = this.loadNode( index );
  88963. break;
  88964. case 'mesh':
  88965. dependency = this._invokeOne( function ( ext ) {
  88966. return ext.loadMesh && ext.loadMesh( index );
  88967. } );
  88968. break;
  88969. case 'accessor':
  88970. dependency = this.loadAccessor( index );
  88971. break;
  88972. case 'bufferView':
  88973. dependency = this._invokeOne( function ( ext ) {
  88974. return ext.loadBufferView && ext.loadBufferView( index );
  88975. } );
  88976. break;
  88977. case 'buffer':
  88978. dependency = this.loadBuffer( index );
  88979. break;
  88980. case 'material':
  88981. dependency = this._invokeOne( function ( ext ) {
  88982. return ext.loadMaterial && ext.loadMaterial( index );
  88983. } );
  88984. break;
  88985. case 'texture':
  88986. dependency = this._invokeOne( function ( ext ) {
  88987. return ext.loadTexture && ext.loadTexture( index );
  88988. } );
  88989. break;
  88990. case 'skin':
  88991. dependency = this.loadSkin( index );
  88992. break;
  88993. case 'animation':
  88994. dependency = this._invokeOne( function ( ext ) {
  88995. return ext.loadAnimation && ext.loadAnimation( index );
  88996. } );
  88997. break;
  88998. case 'camera':
  88999. dependency = this.loadCamera( index );
  89000. break;
  89001. default:
  89002. throw new Error( 'Unknown type: ' + type );
  89003. }
  89004. this.cache.add( cacheKey, dependency );
  89005. }
  89006. return dependency;
  89007. }
  89008. /**
  89009. * Requests all dependencies of the specified type asynchronously, with caching.
  89010. * @param {string} type
  89011. * @return {Promise<Array<Object>>}
  89012. */
  89013. getDependencies( type ) {
  89014. let dependencies = this.cache.get( type );
  89015. if ( ! dependencies ) {
  89016. const parser = this;
  89017. const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  89018. dependencies = Promise.all( defs.map( function ( def, index ) {
  89019. return parser.getDependency( type, index );
  89020. } ) );
  89021. this.cache.add( type, dependencies );
  89022. }
  89023. return dependencies;
  89024. }
  89025. /**
  89026. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  89027. * @param {number} bufferIndex
  89028. * @return {Promise<ArrayBuffer>}
  89029. */
  89030. loadBuffer( bufferIndex ) {
  89031. const bufferDef = this.json.buffers[ bufferIndex ];
  89032. const loader = this.fileLoader;
  89033. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  89034. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  89035. }
  89036. // If present, GLB container is required to be the first buffer.
  89037. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  89038. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  89039. }
  89040. const options = this.options;
  89041. return new Promise( function ( resolve, reject ) {
  89042. loader.load( LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  89043. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  89044. } );
  89045. } );
  89046. }
  89047. /**
  89048. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  89049. * @param {number} bufferViewIndex
  89050. * @return {Promise<ArrayBuffer>}
  89051. */
  89052. loadBufferView( bufferViewIndex ) {
  89053. const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  89054. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  89055. const byteLength = bufferViewDef.byteLength || 0;
  89056. const byteOffset = bufferViewDef.byteOffset || 0;
  89057. return buffer.slice( byteOffset, byteOffset + byteLength );
  89058. } );
  89059. }
  89060. /**
  89061. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  89062. * @param {number} accessorIndex
  89063. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  89064. */
  89065. loadAccessor( accessorIndex ) {
  89066. const parser = this;
  89067. const json = this.json;
  89068. const accessorDef = this.json.accessors[ accessorIndex ];
  89069. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  89070. // Ignore empty accessors, which may be used to declare runtime
  89071. // information about attributes coming from another source (e.g. Draco
  89072. // compression extension).
  89073. return Promise.resolve( null );
  89074. }
  89075. const pendingBufferViews = [];
  89076. if ( accessorDef.bufferView !== undefined ) {
  89077. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  89078. } else {
  89079. pendingBufferViews.push( null );
  89080. }
  89081. if ( accessorDef.sparse !== undefined ) {
  89082. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  89083. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  89084. }
  89085. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  89086. const bufferView = bufferViews[ 0 ];
  89087. const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  89088. const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  89089. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  89090. const elementBytes = TypedArray.BYTES_PER_ELEMENT;
  89091. const itemBytes = elementBytes * itemSize;
  89092. const byteOffset = accessorDef.byteOffset || 0;
  89093. const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  89094. const normalized = accessorDef.normalized === true;
  89095. let array, bufferAttribute;
  89096. // The buffer is not interleaved if the stride is the item size in bytes.
  89097. if ( byteStride && byteStride !== itemBytes ) {
  89098. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  89099. // This makes sure that IBA.count reflects accessor.count properly
  89100. const ibSlice = Math.floor( byteOffset / byteStride );
  89101. const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  89102. let ib = parser.cache.get( ibCacheKey );
  89103. if ( ! ib ) {
  89104. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  89105. // Integer parameters to IB/IBA are in array elements, not bytes.
  89106. ib = new InterleavedBuffer( array, byteStride / elementBytes );
  89107. parser.cache.add( ibCacheKey, ib );
  89108. }
  89109. bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  89110. } else {
  89111. if ( bufferView === null ) {
  89112. array = new TypedArray( accessorDef.count * itemSize );
  89113. } else {
  89114. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  89115. }
  89116. bufferAttribute = new BufferAttribute( array, itemSize, normalized );
  89117. }
  89118. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  89119. if ( accessorDef.sparse !== undefined ) {
  89120. const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  89121. const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  89122. const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  89123. const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  89124. const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  89125. const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  89126. if ( bufferView !== null ) {
  89127. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  89128. bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  89129. }
  89130. for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {
  89131. const index = sparseIndices[ i ];
  89132. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  89133. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  89134. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  89135. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  89136. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  89137. }
  89138. }
  89139. return bufferAttribute;
  89140. } );
  89141. }
  89142. /**
  89143. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  89144. * @param {number} textureIndex
  89145. * @return {Promise<THREE.Texture>}
  89146. */
  89147. loadTexture( textureIndex ) {
  89148. const json = this.json;
  89149. const options = this.options;
  89150. const textureDef = json.textures[ textureIndex ];
  89151. const sourceIndex = textureDef.source;
  89152. const sourceDef = json.images[ sourceIndex ];
  89153. let loader = this.textureLoader;
  89154. if ( sourceDef.uri ) {
  89155. const handler = options.manager.getHandler( sourceDef.uri );
  89156. if ( handler !== null ) loader = handler;
  89157. }
  89158. return this.loadTextureImage( textureIndex, sourceIndex, loader );
  89159. }
  89160. loadTextureImage( textureIndex, sourceIndex, loader ) {
  89161. const parser = this;
  89162. const json = this.json;
  89163. const textureDef = json.textures[ textureIndex ];
  89164. const sourceDef = json.images[ sourceIndex ];
  89165. const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler;
  89166. if ( this.textureCache[ cacheKey ] ) {
  89167. // See https://github.com/mrdoob/three.js/issues/21559.
  89168. return this.textureCache[ cacheKey ];
  89169. }
  89170. const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) {
  89171. texture.flipY = false;
  89172. texture.name = textureDef.name || sourceDef.name || '';
  89173. const samplers = json.samplers || {};
  89174. const sampler = samplers[ textureDef.sampler ] || {};
  89175. /* //xzw 删除设置,因为已经makeTexDontResize
  89176. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
  89177. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter;
  89178. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
  89179. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
  89180. */
  89181. parser.associations.set( texture, { textures: textureIndex } );
  89182. return texture;
  89183. } ).catch( function () {
  89184. return null;
  89185. } );
  89186. this.textureCache[ cacheKey ] = promise;
  89187. return promise;
  89188. }
  89189. loadImageSource( sourceIndex, loader ) {
  89190. const parser = this;
  89191. const json = this.json;
  89192. const options = this.options;
  89193. if ( this.sourceCache[ sourceIndex ] !== undefined ) {
  89194. return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() );
  89195. }
  89196. const sourceDef = json.images[ sourceIndex ];
  89197. const URL = self.URL || self.webkitURL;
  89198. let sourceURI = sourceDef.uri || '';
  89199. let isObjectURL = false;
  89200. if ( sourceDef.bufferView !== undefined ) {
  89201. // Load binary image data from bufferView, if provided.
  89202. sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {
  89203. isObjectURL = true;
  89204. const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } );
  89205. sourceURI = URL.createObjectURL( blob );
  89206. return sourceURI;
  89207. } );
  89208. } else if ( sourceDef.uri === undefined ) {
  89209. throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' );
  89210. }
  89211. const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  89212. return new Promise( function ( resolve, reject ) {
  89213. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,重新写贴图加载方式: xzw
  89214. parser.textureLoader.load(sourceURI, (tex)=>{
  89215. THREE.LinearMipmapLinearFilter; //原本:NearestMipMapNearestFilter 闪烁
  89216. //有一个block文件离远了有裂缝,只能使用LinearFilter,但是这样似乎更卡,且锯齿
  89217. /* tex.minFilter = THREE.LinearFilter
  89218. tex.generateMipmaps = false */
  89219. Potree.Utils.makeTexDontResize(tex);
  89220. //console.log(tex.image.width, tex.image.height)
  89221. resolve(tex);
  89222. });
  89223. return;
  89224. let onLoad = resolve;
  89225. if ( loader.isImageBitmapLoader === true ) {
  89226. onLoad = function ( imageBitmap ) {
  89227. const texture = new Texture( imageBitmap );
  89228. texture.needsUpdate = true;
  89229. resolve( texture );
  89230. };
  89231. }
  89232. loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  89233. } );
  89234. } ).then( function ( texture ) {
  89235. // Clean up resources and configure Texture.
  89236. if ( isObjectURL === true ) {
  89237. URL.revokeObjectURL( sourceURI );
  89238. }
  89239. texture.userData = {};//xzw add
  89240. texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri || sourceDef.mimeType );
  89241. return texture;
  89242. } ).catch( function ( error ) {
  89243. console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );
  89244. throw error;
  89245. } );
  89246. this.sourceCache[ sourceIndex ] = promise;
  89247. return promise;
  89248. }
  89249. /**
  89250. * Asynchronously assigns a texture to the given material parameters.
  89251. * @param {Object} materialParams
  89252. * @param {string} mapName
  89253. * @param {Object} mapDef
  89254. * @return {Promise<Texture>}
  89255. */
  89256. assignTexture( materialParams, mapName, mapDef, encoding ) {
  89257. const parser = this;
  89258. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  89259. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  89260. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  89261. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  89262. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  89263. }
  89264. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  89265. const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  89266. if ( transform ) {
  89267. const gltfReference = parser.associations.get( texture );
  89268. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  89269. parser.associations.set( texture, gltfReference );
  89270. }
  89271. }
  89272. if ( encoding !== undefined ) {
  89273. texture.encoding = encoding;
  89274. }
  89275. materialParams[ mapName ] = texture;
  89276. return texture;
  89277. } );
  89278. }
  89279. /**
  89280. * Assigns final material to a Mesh, Line, or Points instance. The instance
  89281. * already has a material (generated from the glTF material options alone)
  89282. * but reuse of the same glTF material may require multiple threejs materials
  89283. * to accommodate different primitive types, defines, etc. New materials will
  89284. * be created if necessary, and reused from a cache.
  89285. * @param {Object3D} mesh Mesh, Line, or Points instance.
  89286. */
  89287. assignFinalMaterial( mesh ) {
  89288. const geometry = mesh.geometry;
  89289. let material = mesh.material;
  89290. const useDerivativeTangents = geometry.attributes.tangent === undefined;
  89291. const useVertexColors = geometry.attributes.color !== undefined;
  89292. const useFlatShading = geometry.attributes.normal === undefined;
  89293. if ( mesh.isPoints ) {
  89294. const cacheKey = 'PointsMaterial:' + material.uuid;
  89295. let pointsMaterial = this.cache.get( cacheKey );
  89296. if ( ! pointsMaterial ) {
  89297. pointsMaterial = new PointsMaterial();
  89298. Material.prototype.copy.call( pointsMaterial, material );
  89299. pointsMaterial.color.copy( material.color );
  89300. pointsMaterial.map = material.map;
  89301. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  89302. this.cache.add( cacheKey, pointsMaterial );
  89303. }
  89304. material = pointsMaterial;
  89305. } else if ( mesh.isLine ) {
  89306. const cacheKey = 'LineBasicMaterial:' + material.uuid;
  89307. let lineMaterial = this.cache.get( cacheKey );
  89308. if ( ! lineMaterial ) {
  89309. lineMaterial = new LineBasicMaterial();
  89310. Material.prototype.copy.call( lineMaterial, material );
  89311. lineMaterial.color.copy( material.color );
  89312. this.cache.add( cacheKey, lineMaterial );
  89313. }
  89314. material = lineMaterial;
  89315. }
  89316. // Clone the material if it will be modified
  89317. if ( useDerivativeTangents || useVertexColors || useFlatShading ) {
  89318. let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  89319. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  89320. if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';
  89321. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  89322. if ( useFlatShading ) cacheKey += 'flat-shading:';
  89323. let cachedMaterial = this.cache.get( cacheKey );
  89324. if ( ! cachedMaterial ) {
  89325. cachedMaterial = material.clone();
  89326. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  89327. if ( useFlatShading ) cachedMaterial.flatShading = true;
  89328. if ( useDerivativeTangents ) {
  89329. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  89330. if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;
  89331. if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;
  89332. }
  89333. this.cache.add( cacheKey, cachedMaterial );
  89334. this.associations.set( cachedMaterial, this.associations.get( material ) );
  89335. }
  89336. material = cachedMaterial;
  89337. }
  89338. // workarounds for mesh and geometry
  89339. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  89340. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  89341. }
  89342. mesh.material = material;
  89343. }
  89344. getMaterialType( /* materialIndex */ ) {
  89345. return MeshStandardMaterial;
  89346. }
  89347. /**
  89348. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  89349. * @param {number} materialIndex
  89350. * @return {Promise<Material>}
  89351. */
  89352. loadMaterial( materialIndex ) {
  89353. const parser = this;
  89354. const json = this.json;
  89355. const extensions = this.extensions;
  89356. const materialDef = json.materials[ materialIndex ];
  89357. let materialType;
  89358. const materialParams = {};
  89359. const materialExtensions = materialDef.extensions || {};
  89360. const pending = [];
  89361. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  89362. const sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  89363. materialType = BasicMaterial;//sgExtension.getMaterialType(); //xzw 改
  89364. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  89365. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  89366. const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  89367. materialType = BasicMaterial;//kmuExtension.getMaterialType(); //xzw 改
  89368. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  89369. } else {
  89370. // Specification:
  89371. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  89372. const metallicRoughness = materialDef.pbrMetallicRoughness || {};
  89373. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  89374. materialParams.opacity = 1.0;
  89375. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  89376. const array = metallicRoughness.baseColorFactor;
  89377. materialParams.color.fromArray( array );
  89378. materialParams.opacity = array[ 3 ];
  89379. }
  89380. if ( metallicRoughness.baseColorTexture !== undefined ) {
  89381. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding ) );
  89382. }
  89383. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  89384. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  89385. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  89386. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  89387. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  89388. }
  89389. materialType = this._invokeOne( function ( ext ) {
  89390. return BasicMaterial//kmuExtension.getMaterialType(); //xzw 改
  89391. //return ext.getMaterialType && ext.getMaterialType( materialIndex );
  89392. } );
  89393. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  89394. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  89395. } ) ) );
  89396. }
  89397. if ( materialDef.doubleSided === true ) {
  89398. materialParams.side = DoubleSide;
  89399. }
  89400. const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  89401. if ( alphaMode === ALPHA_MODES.BLEND ) {
  89402. materialParams.transparent = true;
  89403. // See: https://github.com/mrdoob/three.js/issues/17706
  89404. materialParams.depthWrite = false;
  89405. } else {
  89406. materialParams.transparent = false;
  89407. if ( alphaMode === ALPHA_MODES.MASK ) {
  89408. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  89409. }
  89410. }
  89411. if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) {
  89412. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  89413. materialParams.normalScale = new Vector2( 1, 1 );
  89414. if ( materialDef.normalTexture.scale !== undefined ) {
  89415. const scale = materialDef.normalTexture.scale;
  89416. materialParams.normalScale.set( scale, scale );
  89417. }
  89418. }
  89419. if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) {
  89420. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  89421. if ( materialDef.occlusionTexture.strength !== undefined ) {
  89422. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  89423. }
  89424. }
  89425. if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) {
  89426. materialParams.emissive = new Color().fromArray( materialDef.emissiveFactor );
  89427. }
  89428. if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) {
  89429. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, sRGBEncoding ) );
  89430. }
  89431. return Promise.all( pending ).then( function () {
  89432. let material;
  89433. if ( materialType === GLTFMeshStandardSGMaterial ) {
  89434. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  89435. } else {
  89436. material = new materialType( materialParams );
  89437. }
  89438. if ( materialDef.name ) material.name = materialDef.name;
  89439. assignExtrasToUserData( material, materialDef );
  89440. parser.associations.set( material, { materials: materialIndex } );
  89441. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  89442. return material;
  89443. } );
  89444. }
  89445. /** When Object3D instances are targeted by animation, they need unique names. */
  89446. createUniqueName( originalName ) {
  89447. const sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' );
  89448. let name = sanitizedName;
  89449. for ( let i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  89450. name = sanitizedName + '_' + i;
  89451. }
  89452. this.nodeNamesUsed[ name ] = true;
  89453. return name;
  89454. }
  89455. /**
  89456. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  89457. *
  89458. * Creates BufferGeometries from primitives.
  89459. *
  89460. * @param {Array<GLTF.Primitive>} primitives
  89461. * @return {Promise<Array<BufferGeometry>>}
  89462. */
  89463. loadGeometries( primitives ) {
  89464. const parser = this;
  89465. const extensions = this.extensions;
  89466. const cache = this.primitiveCache;
  89467. function createDracoPrimitive( primitive ) {
  89468. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  89469. .decodePrimitive( primitive, parser )
  89470. .then( function ( geometry ) {
  89471. return addPrimitiveAttributes( geometry, primitive, parser );
  89472. } );
  89473. }
  89474. const pending = [];
  89475. for ( let i = 0, il = primitives.length; i < il; i ++ ) {
  89476. const primitive = primitives[ i ];
  89477. const cacheKey = createPrimitiveKey( primitive );
  89478. // See if we've already created this geometry
  89479. const cached = cache[ cacheKey ];
  89480. if ( cached ) {
  89481. // Use the cached geometry if it exists
  89482. pending.push( cached.promise );
  89483. } else {
  89484. let geometryPromise;
  89485. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  89486. // Use DRACO geometry if available
  89487. geometryPromise = createDracoPrimitive( primitive );
  89488. } else {
  89489. // Otherwise create a new geometry
  89490. geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser );
  89491. }
  89492. // Cache this geometry
  89493. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  89494. pending.push( geometryPromise );
  89495. }
  89496. }
  89497. return Promise.all( pending );
  89498. }
  89499. /**
  89500. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  89501. * @param {number} meshIndex
  89502. * @return {Promise<Group|Mesh|SkinnedMesh>}
  89503. */
  89504. loadMesh( meshIndex ) {
  89505. const parser = this;
  89506. const json = this.json;
  89507. const extensions = this.extensions;
  89508. const meshDef = json.meshes[ meshIndex ];
  89509. const primitives = meshDef.primitives;
  89510. const pending = [];
  89511. for ( let i = 0, il = primitives.length; i < il; i ++ ) {
  89512. const material = primitives[ i ].material === undefined
  89513. ? createDefaultMaterial( this.cache )
  89514. : this.getDependency( 'material', primitives[ i ].material );
  89515. pending.push( material );
  89516. }
  89517. pending.push( parser.loadGeometries( primitives ) );
  89518. return Promise.all( pending ).then( function ( results ) {
  89519. const materials = results.slice( 0, results.length - 1 );
  89520. const geometries = results[ results.length - 1 ];
  89521. const meshes = [];
  89522. for ( let i = 0, il = geometries.length; i < il; i ++ ) {
  89523. const geometry = geometries[ i ];
  89524. const primitive = primitives[ i ];
  89525. // 1. create Mesh
  89526. let mesh;
  89527. const material = materials[ i ];
  89528. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  89529. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  89530. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  89531. primitive.mode === undefined ) {
  89532. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  89533. mesh = meshDef.isSkinnedMesh === true
  89534. ? new SkinnedMesh( geometry, material )
  89535. : new Mesh( geometry, material );
  89536. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  89537. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  89538. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  89539. mesh.normalizeSkinWeights();
  89540. }
  89541. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  89542. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleStripDrawMode );
  89543. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  89544. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleFanDrawMode );
  89545. }
  89546. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  89547. mesh = new LineSegments( geometry, material );
  89548. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  89549. mesh = new Line( geometry, material );
  89550. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  89551. mesh = new LineLoop( geometry, material );
  89552. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  89553. mesh = new Points( geometry, material );
  89554. } else {
  89555. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  89556. }
  89557. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  89558. updateMorphTargets( mesh, meshDef );
  89559. }
  89560. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  89561. assignExtrasToUserData( mesh, meshDef );
  89562. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  89563. parser.assignFinalMaterial( mesh );
  89564. meshes.push( mesh );
  89565. }
  89566. for ( let i = 0, il = meshes.length; i < il; i ++ ) {
  89567. parser.associations.set( meshes[ i ], {
  89568. meshes: meshIndex,
  89569. primitives: i
  89570. } );
  89571. }
  89572. if ( meshes.length === 1 ) {
  89573. return meshes[ 0 ];
  89574. }
  89575. const group = new Group();
  89576. parser.associations.set( group, { meshes: meshIndex } );
  89577. for ( let i = 0, il = meshes.length; i < il; i ++ ) {
  89578. group.add( meshes[ i ] );
  89579. }
  89580. return group;
  89581. } );
  89582. }
  89583. /**
  89584. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  89585. * @param {number} cameraIndex
  89586. * @return {Promise<THREE.Camera>}
  89587. */
  89588. loadCamera( cameraIndex ) {
  89589. let camera;
  89590. const cameraDef = this.json.cameras[ cameraIndex ];
  89591. const params = cameraDef[ cameraDef.type ];
  89592. if ( ! params ) {
  89593. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  89594. return;
  89595. }
  89596. if ( cameraDef.type === 'perspective' ) {
  89597. camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  89598. } else if ( cameraDef.type === 'orthographic' ) {
  89599. camera = new OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  89600. }
  89601. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  89602. assignExtrasToUserData( camera, cameraDef );
  89603. return Promise.resolve( camera );
  89604. }
  89605. /**
  89606. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  89607. * @param {number} skinIndex
  89608. * @return {Promise<Object>}
  89609. */
  89610. loadSkin( skinIndex ) {
  89611. const skinDef = this.json.skins[ skinIndex ];
  89612. const skinEntry = { joints: skinDef.joints };
  89613. if ( skinDef.inverseBindMatrices === undefined ) {
  89614. return Promise.resolve( skinEntry );
  89615. }
  89616. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  89617. skinEntry.inverseBindMatrices = accessor;
  89618. return skinEntry;
  89619. } );
  89620. }
  89621. /**
  89622. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  89623. * @param {number} animationIndex
  89624. * @return {Promise<AnimationClip>}
  89625. */
  89626. loadAnimation( animationIndex ) {
  89627. const json = this.json;
  89628. const animationDef = json.animations[ animationIndex ];
  89629. const pendingNodes = [];
  89630. const pendingInputAccessors = [];
  89631. const pendingOutputAccessors = [];
  89632. const pendingSamplers = [];
  89633. const pendingTargets = [];
  89634. for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  89635. const channel = animationDef.channels[ i ];
  89636. const sampler = animationDef.samplers[ channel.sampler ];
  89637. const target = channel.target;
  89638. const name = target.node;
  89639. const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  89640. const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  89641. pendingNodes.push( this.getDependency( 'node', name ) );
  89642. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  89643. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  89644. pendingSamplers.push( sampler );
  89645. pendingTargets.push( target );
  89646. }
  89647. return Promise.all( [
  89648. Promise.all( pendingNodes ),
  89649. Promise.all( pendingInputAccessors ),
  89650. Promise.all( pendingOutputAccessors ),
  89651. Promise.all( pendingSamplers ),
  89652. Promise.all( pendingTargets )
  89653. ] ).then( function ( dependencies ) {
  89654. const nodes = dependencies[ 0 ];
  89655. const inputAccessors = dependencies[ 1 ];
  89656. const outputAccessors = dependencies[ 2 ];
  89657. const samplers = dependencies[ 3 ];
  89658. const targets = dependencies[ 4 ];
  89659. const tracks = [];
  89660. for ( let i = 0, il = nodes.length; i < il; i ++ ) {
  89661. const node = nodes[ i ];
  89662. const inputAccessor = inputAccessors[ i ];
  89663. const outputAccessor = outputAccessors[ i ];
  89664. const sampler = samplers[ i ];
  89665. const target = targets[ i ];
  89666. if ( node === undefined ) continue;
  89667. node.updateMatrix();
  89668. let TypedKeyframeTrack;
  89669. switch ( PATH_PROPERTIES[ target.path ] ) {
  89670. case PATH_PROPERTIES.weights:
  89671. TypedKeyframeTrack = NumberKeyframeTrack;
  89672. break;
  89673. case PATH_PROPERTIES.rotation:
  89674. TypedKeyframeTrack = QuaternionKeyframeTrack;
  89675. break;
  89676. case PATH_PROPERTIES.position:
  89677. case PATH_PROPERTIES.scale:
  89678. default:
  89679. TypedKeyframeTrack = VectorKeyframeTrack;
  89680. break;
  89681. }
  89682. const targetName = node.name ? node.name : node.uuid;
  89683. const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;
  89684. const targetNames = [];
  89685. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  89686. node.traverse( function ( object ) {
  89687. if ( object.morphTargetInfluences ) {
  89688. targetNames.push( object.name ? object.name : object.uuid );
  89689. }
  89690. } );
  89691. } else {
  89692. targetNames.push( targetName );
  89693. }
  89694. let outputArray = outputAccessor.array;
  89695. if ( outputAccessor.normalized ) {
  89696. const scale = getNormalizedComponentScale( outputArray.constructor );
  89697. const scaled = new Float32Array( outputArray.length );
  89698. for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {
  89699. scaled[ j ] = outputArray[ j ] * scale;
  89700. }
  89701. outputArray = scaled;
  89702. }
  89703. for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {
  89704. const track = new TypedKeyframeTrack(
  89705. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  89706. inputAccessor.array,
  89707. outputArray,
  89708. interpolation
  89709. );
  89710. // Override interpolation with custom factory method.
  89711. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  89712. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  89713. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  89714. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  89715. // must be divided by three to get the interpolant's sampleSize argument.
  89716. const interpolantType = ( this instanceof QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
  89717. return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );
  89718. };
  89719. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  89720. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  89721. }
  89722. tracks.push( track );
  89723. }
  89724. }
  89725. const name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  89726. return new AnimationClip( name, undefined, tracks );
  89727. } );
  89728. }
  89729. createNodeMesh( nodeIndex ) {
  89730. const json = this.json;
  89731. const parser = this;
  89732. const nodeDef = json.nodes[ nodeIndex ];
  89733. if ( nodeDef.mesh === undefined ) return null;
  89734. return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  89735. const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  89736. // if weights are provided on the node, override weights on the mesh.
  89737. if ( nodeDef.weights !== undefined ) {
  89738. node.traverse( function ( o ) {
  89739. if ( ! o.isMesh ) return;
  89740. for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  89741. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  89742. }
  89743. } );
  89744. }
  89745. return node;
  89746. } );
  89747. }
  89748. /**
  89749. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  89750. * @param {number} nodeIndex
  89751. * @return {Promise<Object3D>}
  89752. */
  89753. loadNode( nodeIndex ) {
  89754. const json = this.json;
  89755. const extensions = this.extensions;
  89756. const parser = this;
  89757. const nodeDef = json.nodes[ nodeIndex ];
  89758. // reserve node's name before its dependencies, so the root has the intended name.
  89759. const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  89760. return ( function () {
  89761. const pending = [];
  89762. const meshPromise = parser._invokeOne( function ( ext ) {
  89763. return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );
  89764. } );
  89765. if ( meshPromise ) {
  89766. pending.push( meshPromise );
  89767. }
  89768. if ( nodeDef.camera !== undefined ) {
  89769. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  89770. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  89771. } ) );
  89772. }
  89773. parser._invokeAll( function ( ext ) {
  89774. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  89775. } ).forEach( function ( promise ) {
  89776. pending.push( promise );
  89777. } );
  89778. return Promise.all( pending );
  89779. }() ).then( function ( objects ) {
  89780. let node;
  89781. // .isBone isn't in glTF spec. See ._markDefs
  89782. if ( nodeDef.isBone === true ) {
  89783. node = new Bone();
  89784. } else if ( objects.length > 1 ) {
  89785. node = new Group();
  89786. } else if ( objects.length === 1 ) {
  89787. node = objects[ 0 ];
  89788. } else {
  89789. node = new Object3D();
  89790. }
  89791. if ( node !== objects[ 0 ] ) {
  89792. for ( let i = 0, il = objects.length; i < il; i ++ ) {
  89793. node.add( objects[ i ] );
  89794. }
  89795. }
  89796. if ( nodeDef.name ) {
  89797. node.userData.name = nodeDef.name;
  89798. node.name = nodeName;
  89799. }
  89800. assignExtrasToUserData( node, nodeDef );
  89801. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  89802. if ( nodeDef.matrix !== undefined ) {
  89803. const matrix = new Matrix4();
  89804. matrix.fromArray( nodeDef.matrix );
  89805. node.applyMatrix4( matrix );
  89806. } else {
  89807. if ( nodeDef.translation !== undefined ) {
  89808. node.position.fromArray( nodeDef.translation );
  89809. }
  89810. if ( nodeDef.rotation !== undefined ) {
  89811. node.quaternion.fromArray( nodeDef.rotation );
  89812. }
  89813. if ( nodeDef.scale !== undefined ) {
  89814. node.scale.fromArray( nodeDef.scale );
  89815. }
  89816. }
  89817. if ( ! parser.associations.has( node ) ) {
  89818. parser.associations.set( node, {} );
  89819. }
  89820. parser.associations.get( node ).nodes = nodeIndex;
  89821. return node;
  89822. } );
  89823. }
  89824. /**
  89825. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  89826. * @param {number} sceneIndex
  89827. * @return {Promise<Group>}
  89828. */
  89829. loadScene( sceneIndex ) {
  89830. const json = this.json;
  89831. const extensions = this.extensions;
  89832. const sceneDef = this.json.scenes[ sceneIndex ];
  89833. const parser = this;
  89834. // Loader returns Group, not Scene.
  89835. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  89836. const scene = new Group();
  89837. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  89838. assignExtrasToUserData( scene, sceneDef );
  89839. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  89840. const nodeIds = sceneDef.nodes || [];
  89841. const pending = [];
  89842. for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {
  89843. pending.push( buildNodeHierarchy( nodeIds[ i ], scene, json, parser ) );
  89844. }
  89845. return Promise.all( pending ).then( function () {
  89846. // Removes dangling associations, associations that reference a node that
  89847. // didn't make it into the scene.
  89848. const reduceAssociations = ( node ) => {
  89849. const reducedAssociations = new Map();
  89850. for ( const [ key, value ] of parser.associations ) {
  89851. if ( key instanceof Material || key instanceof Texture ) {
  89852. reducedAssociations.set( key, value );
  89853. }
  89854. }
  89855. node.traverse( ( node ) => {
  89856. const mappings = parser.associations.get( node );
  89857. if ( mappings != null ) {
  89858. reducedAssociations.set( node, mappings );
  89859. }
  89860. } );
  89861. return reducedAssociations;
  89862. };
  89863. parser.associations = reduceAssociations( scene );
  89864. return scene;
  89865. } );
  89866. }
  89867. }
  89868. function buildNodeHierarchy( nodeId, parentObject, json, parser ) {
  89869. const nodeDef = json.nodes[ nodeId ];
  89870. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  89871. if ( nodeDef.skin === undefined ) return node;
  89872. // build skeleton here as well
  89873. let skinEntry;
  89874. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  89875. skinEntry = skin;
  89876. const pendingJoints = [];
  89877. for ( let i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  89878. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  89879. }
  89880. return Promise.all( pendingJoints );
  89881. } ).then( function ( jointNodes ) {
  89882. node.traverse( function ( mesh ) {
  89883. if ( ! mesh.isMesh ) return;
  89884. const bones = [];
  89885. const boneInverses = [];
  89886. for ( let j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  89887. const jointNode = jointNodes[ j ];
  89888. if ( jointNode ) {
  89889. bones.push( jointNode );
  89890. const mat = new Matrix4();
  89891. if ( skinEntry.inverseBindMatrices !== undefined ) {
  89892. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  89893. }
  89894. boneInverses.push( mat );
  89895. } else {
  89896. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  89897. }
  89898. }
  89899. mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld );
  89900. } );
  89901. return node;
  89902. } );
  89903. } ).then( function ( node ) {
  89904. // build node hierachy
  89905. parentObject.add( node );
  89906. const pending = [];
  89907. if ( nodeDef.children ) {
  89908. const children = nodeDef.children;
  89909. for ( let i = 0, il = children.length; i < il; i ++ ) {
  89910. const child = children[ i ];
  89911. pending.push( buildNodeHierarchy( child, node, json, parser ) );
  89912. }
  89913. }
  89914. return Promise.all( pending );
  89915. } );
  89916. }
  89917. /**
  89918. * @param {BufferGeometry} geometry
  89919. * @param {GLTF.Primitive} primitiveDef
  89920. * @param {GLTFParser} parser
  89921. */
  89922. function computeBounds( geometry, primitiveDef, parser ) {
  89923. const attributes = primitiveDef.attributes;
  89924. const box = new Box3();
  89925. if ( attributes.POSITION !== undefined ) {
  89926. const accessor = parser.json.accessors[ attributes.POSITION ];
  89927. const min = accessor.min;
  89928. const max = accessor.max;
  89929. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  89930. if ( min !== undefined && max !== undefined ) {
  89931. box.set(
  89932. new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  89933. new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )
  89934. );
  89935. if ( accessor.normalized ) {
  89936. const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
  89937. box.min.multiplyScalar( boxScale );
  89938. box.max.multiplyScalar( boxScale );
  89939. }
  89940. } else {
  89941. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  89942. return;
  89943. }
  89944. } else {
  89945. return;
  89946. }
  89947. const targets = primitiveDef.targets;
  89948. if ( targets !== undefined ) {
  89949. const maxDisplacement = new Vector3();
  89950. const vector = new Vector3();
  89951. for ( let i = 0, il = targets.length; i < il; i ++ ) {
  89952. const target = targets[ i ];
  89953. if ( target.POSITION !== undefined ) {
  89954. const accessor = parser.json.accessors[ target.POSITION ];
  89955. const min = accessor.min;
  89956. const max = accessor.max;
  89957. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  89958. if ( min !== undefined && max !== undefined ) {
  89959. // we need to get max of absolute components because target weight is [-1,1]
  89960. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  89961. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  89962. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  89963. if ( accessor.normalized ) {
  89964. const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
  89965. vector.multiplyScalar( boxScale );
  89966. }
  89967. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  89968. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  89969. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  89970. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  89971. maxDisplacement.max( vector );
  89972. } else {
  89973. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  89974. }
  89975. }
  89976. }
  89977. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  89978. box.expandByVector( maxDisplacement );
  89979. }
  89980. geometry.boundingBox = box;
  89981. const sphere = new Sphere();
  89982. box.getCenter( sphere.center );
  89983. sphere.radius = box.min.distanceTo( box.max ) / 2;
  89984. geometry.boundingSphere = sphere;
  89985. }
  89986. /**
  89987. * @param {BufferGeometry} geometry
  89988. * @param {GLTF.Primitive} primitiveDef
  89989. * @param {GLTFParser} parser
  89990. * @return {Promise<BufferGeometry>}
  89991. */
  89992. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  89993. const attributes = primitiveDef.attributes;
  89994. const pending = [];
  89995. function assignAttributeAccessor( accessorIndex, attributeName ) {
  89996. return parser.getDependency( 'accessor', accessorIndex )
  89997. .then( function ( accessor ) {
  89998. geometry.setAttribute( attributeName, accessor );
  89999. } );
  90000. }
  90001. for ( const gltfAttributeName in attributes ) {
  90002. const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  90003. // Skip attributes already provided by e.g. Draco extension.
  90004. if ( threeAttributeName in geometry.attributes ) continue;
  90005. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  90006. }
  90007. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  90008. const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  90009. geometry.setIndex( accessor );
  90010. } );
  90011. pending.push( accessor );
  90012. }
  90013. assignExtrasToUserData( geometry, primitiveDef );
  90014. computeBounds( geometry, primitiveDef, parser );
  90015. return Promise.all( pending ).then( function () {
  90016. return primitiveDef.targets !== undefined
  90017. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  90018. : geometry;
  90019. } );
  90020. }
  90021. /**
  90022. * @param {BufferGeometry} geometry
  90023. * @param {Number} drawMode
  90024. * @return {BufferGeometry}
  90025. */
  90026. function toTrianglesDrawMode( geometry, drawMode ) {
  90027. let index = geometry.getIndex();
  90028. // generate index if not present
  90029. if ( index === null ) {
  90030. const indices = [];
  90031. const position = geometry.getAttribute( 'position' );
  90032. if ( position !== undefined ) {
  90033. for ( let i = 0; i < position.count; i ++ ) {
  90034. indices.push( i );
  90035. }
  90036. geometry.setIndex( indices );
  90037. index = geometry.getIndex();
  90038. } else {
  90039. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  90040. return geometry;
  90041. }
  90042. }
  90043. //
  90044. const numberOfTriangles = index.count - 2;
  90045. const newIndices = [];
  90046. if ( drawMode === TriangleFanDrawMode ) {
  90047. // gl.TRIANGLE_FAN
  90048. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  90049. newIndices.push( index.getX( 0 ) );
  90050. newIndices.push( index.getX( i ) );
  90051. newIndices.push( index.getX( i + 1 ) );
  90052. }
  90053. } else {
  90054. // gl.TRIANGLE_STRIP
  90055. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  90056. if ( i % 2 === 0 ) {
  90057. newIndices.push( index.getX( i ) );
  90058. newIndices.push( index.getX( i + 1 ) );
  90059. newIndices.push( index.getX( i + 2 ) );
  90060. } else {
  90061. newIndices.push( index.getX( i + 2 ) );
  90062. newIndices.push( index.getX( i + 1 ) );
  90063. newIndices.push( index.getX( i ) );
  90064. }
  90065. }
  90066. }
  90067. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  90068. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  90069. }
  90070. // build final geometry
  90071. const newGeometry = geometry.clone();
  90072. newGeometry.setIndex( newIndices );
  90073. return newGeometry;
  90074. }
  90075. let globalThis = window; //add 有的app没有globalThis. 2023.1
  90076. /*! *****************************************************************************
  90077. Copyright (c) Microsoft Corporation.
  90078. Permission to use, copy, modify, and/or distribute this software for any
  90079. purpose with or without fee is hereby granted.
  90080. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  90081. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  90082. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  90083. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  90084. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  90085. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  90086. PERFORMANCE OF THIS SOFTWARE.
  90087. ***************************************************************************** */
  90088. let visiVertexCount = 0;
  90089. let visiGeoCount = 0;
  90090. const maxVertexVisi = 5e6;
  90091. const maxTexVisi = 500;
  90092. function getGpuMemoryUsage(win = window){//总的
  90093. let c = 0;
  90094. viewer.objs.children.filter(e=>{
  90095. if(e.fileType == '3dTiles'){
  90096. let tileset3D = e.runtime.getTileset();
  90097. c += tileset3D.gpuMemoryUsageInBytes;
  90098. }
  90099. });
  90100. if(win.parent != win){//还有父级页面。 暂时只有子级需要考虑父级,假设父级在前台时子级已经销毁
  90101. c += getGpuMemoryUsage(win.parent);
  90102. }
  90103. viewer.tiles3dMemoryUsage = c;
  90104. viewer.tiles3dVisiVCount = visiVertexCount;
  90105. return c
  90106. }
  90107. function __awaiter(thisArg, _arguments, P, generator) {
  90108. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  90109. return new (P || (P = Promise))(function (resolve, reject) {
  90110. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  90111. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  90112. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  90113. step((generator = generator.apply(thisArg, _arguments || [])).next());
  90114. });
  90115. }
  90116. function assert$7(condition, message) {
  90117. if (!condition) {
  90118. throw new Error(message || 'loader assertion failed.');
  90119. }
  90120. }
  90121. const isBrowser$2 = Boolean(typeof process !== 'object' || String(process) !== '[object process]' || process.browser);
  90122. const matches$1 = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  90123. matches$1 && parseFloat(matches$1[1]) || 0;
  90124. const VERSION$8 = "3.1.4" ;
  90125. function assert$6(condition, message) {
  90126. if (!condition) {
  90127. throw new Error(message || 'loaders.gl assertion failed.');
  90128. }
  90129. }
  90130. const globals$1 = {
  90131. self: typeof self !== 'undefined' && self,
  90132. window: typeof window !== 'undefined' && window,
  90133. global: typeof global !== 'undefined' && global,
  90134. document: typeof document !== 'undefined' && document
  90135. };
  90136. const global_ = globals$1.global || globals$1.self || globals$1.window || {};
  90137. const isBrowser$1 = typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
  90138. const isWorker = typeof importScripts === 'function';
  90139. const isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
  90140. const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
  90141. matches && parseFloat(matches[1]) || 0;
  90142. function _defineProperty(obj, key, value) {
  90143. if (key in obj) {
  90144. Object.defineProperty(obj, key, {
  90145. value: value,
  90146. enumerable: true,
  90147. configurable: true,
  90148. writable: true
  90149. });
  90150. } else {
  90151. obj[key] = value;
  90152. }
  90153. return obj;
  90154. }
  90155. class WorkerJob {
  90156. constructor(jobName, workerThread) {
  90157. _defineProperty(this, "name", void 0);
  90158. _defineProperty(this, "workerThread", void 0);
  90159. _defineProperty(this, "isRunning", void 0);
  90160. _defineProperty(this, "result", void 0);
  90161. _defineProperty(this, "_resolve", void 0);
  90162. _defineProperty(this, "_reject", void 0);
  90163. this.name = jobName;
  90164. this.workerThread = workerThread;
  90165. this.isRunning = true;
  90166. this._resolve = () => {};
  90167. this._reject = () => {};
  90168. this.result = new Promise((resolve, reject) => {
  90169. this._resolve = resolve;
  90170. this._reject = reject;
  90171. });
  90172. }
  90173. postMessage(type, payload) {
  90174. this.workerThread.postMessage({
  90175. source: 'loaders.gl',
  90176. type,
  90177. payload
  90178. });
  90179. }
  90180. done(value) {
  90181. assert$6(this.isRunning);
  90182. this.isRunning = false;
  90183. this._resolve(value);
  90184. }
  90185. error(error) {
  90186. assert$6(this.isRunning);
  90187. this.isRunning = false;
  90188. this._reject(error);
  90189. }
  90190. }
  90191. const workerURLCache = new Map();
  90192. function getLoadableWorkerURL(props) {
  90193. assert$6(props.source && !props.url || !props.source && props.url);
  90194. let workerURL = workerURLCache.get(props.source || props.url);
  90195. if (!workerURL) {
  90196. if (props.url) {
  90197. workerURL = getLoadableWorkerURLFromURL(props.url);
  90198. workerURLCache.set(props.url, workerURL);
  90199. }
  90200. if (props.source) {
  90201. workerURL = getLoadableWorkerURLFromSource(props.source);
  90202. workerURLCache.set(props.source, workerURL);
  90203. }
  90204. }
  90205. assert$6(workerURL);
  90206. return workerURL;
  90207. }
  90208. function getLoadableWorkerURLFromURL(url) {
  90209. if (!url.startsWith('http')) {
  90210. return url;
  90211. }
  90212. const workerSource = buildScriptSource(url);
  90213. return getLoadableWorkerURLFromSource(workerSource);
  90214. }
  90215. function getLoadableWorkerURLFromSource(workerSource) {
  90216. const blob = new Blob([workerSource], {
  90217. type: 'application/javascript'
  90218. });
  90219. return URL.createObjectURL(blob);
  90220. }
  90221. function buildScriptSource(workerUrl) {
  90222. return "try {\n importScripts('".concat(workerUrl, "');\n} catch (error) {\n console.error(error);\n throw error;\n}");
  90223. }
  90224. function getTransferList(object, recursive = true, transfers) {
  90225. const transfersSet = transfers || new Set();
  90226. if (!object) ; else if (isTransferable(object)) {
  90227. transfersSet.add(object);
  90228. } else if (isTransferable(object.buffer)) {
  90229. transfersSet.add(object.buffer);
  90230. } else if (ArrayBuffer.isView(object)) ; else if (recursive && typeof object === 'object') {
  90231. for (const key in object) {
  90232. getTransferList(object[key], recursive, transfersSet);
  90233. }
  90234. }
  90235. return transfers === undefined ? Array.from(transfersSet) : [];
  90236. }
  90237. function isTransferable(object) {
  90238. if (!object) {
  90239. return false;
  90240. }
  90241. if (object instanceof ArrayBuffer) {
  90242. return true;
  90243. }
  90244. if (typeof MessagePort !== 'undefined' && object instanceof MessagePort) {
  90245. return true;
  90246. }
  90247. if (typeof ImageBitmap !== 'undefined' && object instanceof ImageBitmap) {
  90248. return true;
  90249. }
  90250. if (typeof OffscreenCanvas !== 'undefined' && object instanceof OffscreenCanvas) {
  90251. return true;
  90252. }
  90253. return false;
  90254. }
  90255. const NOOP = () => {};
  90256. class WorkerThread {
  90257. static isSupported() {
  90258. return typeof Worker !== 'undefined';
  90259. }
  90260. constructor(props) {
  90261. _defineProperty(this, "name", void 0);
  90262. _defineProperty(this, "source", void 0);
  90263. _defineProperty(this, "url", void 0);
  90264. _defineProperty(this, "terminated", false);
  90265. _defineProperty(this, "worker", void 0);
  90266. _defineProperty(this, "onMessage", void 0);
  90267. _defineProperty(this, "onError", void 0);
  90268. _defineProperty(this, "_loadableURL", '');
  90269. const {
  90270. name,
  90271. source,
  90272. url
  90273. } = props;
  90274. assert$6(source || url);
  90275. this.name = name;
  90276. this.source = source;
  90277. this.url = url;
  90278. this.onMessage = NOOP;
  90279. this.onError = error => console.log(error);
  90280. this.worker = this._createBrowserWorker();
  90281. }
  90282. destroy() {
  90283. this.onMessage = NOOP;
  90284. this.onError = NOOP;
  90285. this.worker.terminate();
  90286. this.terminated = true;
  90287. }
  90288. get isRunning() {
  90289. return Boolean(this.onMessage);
  90290. }
  90291. postMessage(data, transferList) {
  90292. transferList = transferList || getTransferList(data);
  90293. this.worker.postMessage(data, transferList);
  90294. }
  90295. _getErrorFromErrorEvent(event) {
  90296. let message = 'Failed to load ';
  90297. message += "worker ".concat(this.name, " from ").concat(this.url, ". ");
  90298. if (event.message) {
  90299. message += "".concat(event.message, " in ");
  90300. }
  90301. if (event.lineno) {
  90302. message += ":".concat(event.lineno, ":").concat(event.colno);
  90303. }
  90304. return new Error(message);
  90305. }
  90306. _createBrowserWorker() {
  90307. this._loadableURL = getLoadableWorkerURL({
  90308. source: this.source,
  90309. url: this.url
  90310. });
  90311. const worker = new Worker(this._loadableURL, {
  90312. name: this.name
  90313. });
  90314. worker.onmessage = event => {
  90315. if (!event.data) {
  90316. this.onError(new Error('No data received'));
  90317. } else {
  90318. this.onMessage(event.data);
  90319. }
  90320. };
  90321. worker.onerror = error => {
  90322. this.onError(this._getErrorFromErrorEvent(error));
  90323. this.terminated = true;
  90324. };
  90325. worker.onmessageerror = event => console.error(event);
  90326. return worker;
  90327. }
  90328. }
  90329. class WorkerPool$2 {
  90330. constructor(props) {
  90331. _defineProperty(this, "name", 'unnamed');
  90332. _defineProperty(this, "source", void 0);
  90333. _defineProperty(this, "url", void 0);
  90334. _defineProperty(this, "maxConcurrency", 1);
  90335. _defineProperty(this, "maxMobileConcurrency", 1);
  90336. _defineProperty(this, "onDebug", () => {});
  90337. _defineProperty(this, "reuseWorkers", true);
  90338. _defineProperty(this, "props", {});
  90339. _defineProperty(this, "jobQueue", []);
  90340. _defineProperty(this, "idleQueue", []);
  90341. _defineProperty(this, "count", 0);
  90342. _defineProperty(this, "isDestroyed", false);
  90343. this.source = props.source;
  90344. this.url = props.url;
  90345. this.setProps(props);
  90346. }
  90347. destroy() {
  90348. this.idleQueue.forEach(worker => worker.destroy());
  90349. this.isDestroyed = true;
  90350. }
  90351. setProps(props) {
  90352. this.props = { ...this.props,
  90353. ...props
  90354. };
  90355. if (props.name !== undefined) {
  90356. this.name = props.name;
  90357. }
  90358. if (props.maxConcurrency !== undefined) {
  90359. this.maxConcurrency = props.maxConcurrency;
  90360. }
  90361. if (props.maxMobileConcurrency !== undefined) {
  90362. this.maxMobileConcurrency = props.maxMobileConcurrency;
  90363. }
  90364. if (props.reuseWorkers !== undefined) {
  90365. this.reuseWorkers = props.reuseWorkers;
  90366. }
  90367. if (props.onDebug !== undefined) {
  90368. this.onDebug = props.onDebug;
  90369. }
  90370. }
  90371. async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
  90372. const startPromise = new Promise(onStart => {
  90373. this.jobQueue.push({
  90374. name,
  90375. onMessage,
  90376. onError,
  90377. onStart
  90378. });
  90379. return this;
  90380. });
  90381. this._startQueuedJob();
  90382. return await startPromise;
  90383. }
  90384. async _startQueuedJob() {
  90385. if (!this.jobQueue.length) {
  90386. return;
  90387. }
  90388. const workerThread = this._getAvailableWorker();
  90389. if (!workerThread) {
  90390. return;
  90391. }
  90392. const queuedJob = this.jobQueue.shift();
  90393. if (queuedJob) {
  90394. this.onDebug({
  90395. message: 'Starting job',
  90396. name: queuedJob.name,
  90397. workerThread,
  90398. backlog: this.jobQueue.length
  90399. });
  90400. const job = new WorkerJob(queuedJob.name, workerThread);
  90401. workerThread.onMessage = data => queuedJob.onMessage(job, data.type, data.payload);
  90402. workerThread.onError = error => queuedJob.onError(job, error);
  90403. queuedJob.onStart(job);
  90404. try {
  90405. await job.result;
  90406. } finally {
  90407. this.returnWorkerToQueue(workerThread);
  90408. }
  90409. }
  90410. }
  90411. returnWorkerToQueue(worker) {
  90412. const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
  90413. if (shouldDestroyWorker) {
  90414. worker.destroy();
  90415. this.count--;
  90416. } else {
  90417. this.idleQueue.push(worker);
  90418. }
  90419. if (!this.isDestroyed) {
  90420. this._startQueuedJob();
  90421. }
  90422. }
  90423. _getAvailableWorker() {
  90424. if (this.idleQueue.length > 0) {
  90425. return this.idleQueue.shift() || null;
  90426. }
  90427. if (this.count < this._getMaxConcurrency()) {
  90428. this.count++;
  90429. const name = "".concat(this.name.toLowerCase(), " (#").concat(this.count, " of ").concat(this.maxConcurrency, ")");
  90430. return new WorkerThread({
  90431. name,
  90432. source: this.source,
  90433. url: this.url
  90434. });
  90435. }
  90436. return null;
  90437. }
  90438. _getMaxConcurrency() {
  90439. return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
  90440. }
  90441. }
  90442. const DEFAULT_PROPS$3 = {
  90443. maxConcurrency: 3,
  90444. maxMobileConcurrency: 1,
  90445. onDebug: () => {},
  90446. reuseWorkers: true
  90447. };
  90448. class WorkerFarm {
  90449. static isSupported() {
  90450. return WorkerThread.isSupported();
  90451. }
  90452. static getWorkerFarm(props = {}) {
  90453. WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
  90454. WorkerFarm._workerFarm.setProps(props);
  90455. return WorkerFarm._workerFarm;
  90456. }
  90457. constructor(props) {
  90458. _defineProperty(this, "props", void 0);
  90459. _defineProperty(this, "workerPools", new Map());
  90460. this.props = { ...DEFAULT_PROPS$3
  90461. };
  90462. this.setProps(props);
  90463. this.workerPools = new Map();
  90464. }
  90465. destroy() {
  90466. for (const workerPool of this.workerPools.values()) {
  90467. workerPool.destroy();
  90468. }
  90469. }
  90470. setProps(props) {
  90471. this.props = { ...this.props,
  90472. ...props
  90473. };
  90474. for (const workerPool of this.workerPools.values()) {
  90475. workerPool.setProps(this._getWorkerPoolProps());
  90476. }
  90477. }
  90478. getWorkerPool(options) {
  90479. const {
  90480. name,
  90481. source,
  90482. url
  90483. } = options;
  90484. let workerPool = this.workerPools.get(name);
  90485. if (!workerPool) {
  90486. workerPool = new WorkerPool$2({
  90487. name,
  90488. source,
  90489. url
  90490. });
  90491. workerPool.setProps(this._getWorkerPoolProps());
  90492. this.workerPools.set(name, workerPool);
  90493. }
  90494. return workerPool;
  90495. }
  90496. _getWorkerPoolProps() {
  90497. return {
  90498. maxConcurrency: this.props.maxConcurrency,
  90499. maxMobileConcurrency: this.props.maxMobileConcurrency,
  90500. reuseWorkers: this.props.reuseWorkers,
  90501. onDebug: this.props.onDebug
  90502. };
  90503. }
  90504. }
  90505. _defineProperty(WorkerFarm, "_workerFarm", void 0);
  90506. const NPM_TAG = 'latest';
  90507. function getWorkerURL(worker, options = {}) {
  90508. const workerOptions = options[worker.id] || {};
  90509. const workerFile = "".concat(worker.id, "-worker.js");
  90510. let url = workerOptions.workerUrl;
  90511. if (!url && worker.id === 'compression') {
  90512. url = options.workerUrl;
  90513. }
  90514. if (options._workerType === 'test') {
  90515. url = "modules/".concat(worker.module, "/dist/").concat(workerFile);
  90516. }
  90517. if (!url) {
  90518. let version = worker.version;
  90519. if (version === 'latest') {
  90520. version = NPM_TAG;
  90521. }
  90522. const versionTag = version ? "@".concat(version) : '';
  90523. url = "https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag, "/dist/").concat(workerFile);
  90524. }
  90525. assert$6(url);
  90526. return url;
  90527. }
  90528. function validateWorkerVersion(worker, coreVersion = VERSION$8) {
  90529. assert$6(worker, 'no worker provided');
  90530. const workerVersion = worker.version;
  90531. if (!coreVersion || !workerVersion) {
  90532. return false;
  90533. }
  90534. return true;
  90535. }
  90536. var ChildProcessProxy = {};
  90537. var node = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), ChildProcessProxy, {
  90538. 'default': ChildProcessProxy
  90539. }));
  90540. const VERSION$7 = "3.1.4" ;
  90541. const loadLibraryPromises = {};
  90542. async function loadLibrary(libraryUrl, moduleName = null, options = {}) {
  90543. if (moduleName) {
  90544. libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);
  90545. }
  90546. loadLibraryPromises[libraryUrl] = loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
  90547. return await loadLibraryPromises[libraryUrl];
  90548. }
  90549. function getLibraryUrl(library, moduleName, options) {
  90550. if (library.startsWith('http')) {
  90551. return library;
  90552. }
  90553. const modules = options.modules || {};
  90554. if (modules[library]) {
  90555. return modules[library];
  90556. }
  90557. if (!isBrowser$1) {
  90558. return "modules/".concat(moduleName, "/dist/libs/").concat(library);
  90559. }
  90560. if (options.CDN) {
  90561. assert$6(options.CDN.startsWith('http'));
  90562. return "".concat(options.CDN, "/").concat(moduleName, "@").concat(VERSION$7, "/dist/libs/").concat(library);
  90563. }
  90564. if (isWorker) {
  90565. return "../src/libs/".concat(library);
  90566. }
  90567. return "modules/".concat(moduleName, "/src/libs/").concat(library);
  90568. }
  90569. async function loadLibraryFromFile(libraryUrl) {
  90570. if (libraryUrl.endsWith('wasm')) {
  90571. const response = await fetch(libraryUrl);
  90572. return await response.arrayBuffer();
  90573. }
  90574. if (!isBrowser$1) {
  90575. try {
  90576. return node && ChildProcessProxy.requireFromFile && (await ChildProcessProxy.requireFromFile(libraryUrl));
  90577. } catch {
  90578. return null;
  90579. }
  90580. }
  90581. if (isWorker) {
  90582. return importScripts(libraryUrl);
  90583. }
  90584. const response = await fetch(libraryUrl);
  90585. const scriptSource = await response.text();
  90586. return loadLibraryFromString(scriptSource, libraryUrl);
  90587. }
  90588. function loadLibraryFromString(scriptSource, id) {
  90589. if (!isBrowser$1) {
  90590. return ChildProcessProxy.requireFromString && ChildProcessProxy.requireFromString(scriptSource, id);
  90591. }
  90592. if (isWorker) {
  90593. eval.call(global_, scriptSource);
  90594. return null;
  90595. }
  90596. const script = document.createElement('script');
  90597. script.id = id;
  90598. try {
  90599. script.appendChild(document.createTextNode(scriptSource));
  90600. } catch (e) {
  90601. script.text = scriptSource;
  90602. }
  90603. document.body.appendChild(script);
  90604. return null;
  90605. }
  90606. function canParseWithWorker(loader, options) {
  90607. if (!WorkerFarm.isSupported()) {
  90608. return false;
  90609. }
  90610. return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
  90611. }
  90612. async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
  90613. const name = loader.id;
  90614. const url = getWorkerURL(loader, options);
  90615. const workerFarm = WorkerFarm.getWorkerFarm(options);
  90616. const workerPool = workerFarm.getWorkerPool({
  90617. name,
  90618. url
  90619. });
  90620. options = JSON.parse(JSON.stringify(options));
  90621. const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
  90622. job.postMessage('process', {
  90623. input: data,
  90624. options
  90625. });
  90626. const result = await job.result;
  90627. return await result.result;
  90628. }
  90629. async function onMessage(parseOnMainThread, job, type, payload) {
  90630. switch (type) {
  90631. case 'done':
  90632. job.done(payload);
  90633. break;
  90634. case 'error':
  90635. job.error(new Error(payload.error));
  90636. break;
  90637. case 'process':
  90638. const {
  90639. id,
  90640. input,
  90641. options
  90642. } = payload;
  90643. try {
  90644. const result = await parseOnMainThread(input, options);
  90645. job.postMessage('done', {
  90646. id,
  90647. result
  90648. });
  90649. } catch (error) {
  90650. const message = error instanceof Error ? error.message : 'unknown error';
  90651. job.postMessage('error', {
  90652. id,
  90653. error: message
  90654. });
  90655. }
  90656. break;
  90657. default:
  90658. console.warn("parse-with-worker unknown message ".concat(type));
  90659. }
  90660. }
  90661. function getFirstCharacters$1(data, length = 5) {
  90662. if (typeof data === 'string') {
  90663. return data.slice(0, length);
  90664. } else if (ArrayBuffer.isView(data)) {
  90665. return getMagicString$3(data.buffer, data.byteOffset, length);
  90666. } else if (data instanceof ArrayBuffer) {
  90667. const byteOffset = 0;
  90668. return getMagicString$3(data, byteOffset, length);
  90669. }
  90670. return '';
  90671. }
  90672. function getMagicString$3(arrayBuffer, byteOffset, length) {
  90673. if (arrayBuffer.byteLength <= byteOffset + length) {
  90674. return '';
  90675. }
  90676. const dataView = new DataView(arrayBuffer);
  90677. let magic = '';
  90678. for (let i = 0; i < length; i++) {
  90679. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  90680. }
  90681. return magic;
  90682. }
  90683. function parseJSON(string) {
  90684. try {
  90685. return JSON.parse(string);
  90686. } catch (_) {
  90687. throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string), "\""));
  90688. }
  90689. }
  90690. function isBuffer$1(value) {
  90691. return value && typeof value === 'object' && value.isBuffer;
  90692. }
  90693. function bufferToArrayBuffer(buffer) {
  90694. if (isBuffer$1(buffer)) {
  90695. const typedArray = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
  90696. return typedArray.slice().buffer;
  90697. }
  90698. return buffer;
  90699. }
  90700. function toArrayBuffer(data) {
  90701. if (isBuffer$1(data)) {
  90702. return bufferToArrayBuffer(data);
  90703. }
  90704. if (data instanceof ArrayBuffer) {
  90705. return data;
  90706. }
  90707. if (ArrayBuffer.isView(data)) {
  90708. if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
  90709. return data.buffer;
  90710. }
  90711. return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
  90712. }
  90713. if (typeof data === 'string') {
  90714. const text = data;
  90715. const uint8Array = new TextEncoder().encode(text);
  90716. return uint8Array.buffer;
  90717. }
  90718. if (data && typeof data === 'object' && data._toArrayBuffer) {
  90719. return data._toArrayBuffer();
  90720. }
  90721. throw new Error('toArrayBuffer');
  90722. }
  90723. function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
  90724. byteLength = byteLength || arrayBuffer1.byteLength;
  90725. if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
  90726. return false;
  90727. }
  90728. const array1 = new Uint8Array(arrayBuffer1);
  90729. const array2 = new Uint8Array(arrayBuffer2);
  90730. for (let i = 0; i < array1.length; ++i) {
  90731. if (array1[i] !== array2[i]) {
  90732. return false;
  90733. }
  90734. }
  90735. return true;
  90736. }
  90737. function concatenateArrayBuffers(...sources) {
  90738. const sourceArrays = sources.map(source2 => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2);
  90739. const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
  90740. const result = new Uint8Array(byteLength);
  90741. let offset = 0;
  90742. for (const sourceArray of sourceArrays) {
  90743. result.set(sourceArray, offset);
  90744. offset += sourceArray.byteLength;
  90745. }
  90746. return result.buffer;
  90747. }
  90748. function sliceArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  90749. const subArray = byteLength !== undefined ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength) : new Uint8Array(arrayBuffer).subarray(byteOffset);
  90750. const arrayCopy = new Uint8Array(subArray);
  90751. return arrayCopy.buffer;
  90752. }
  90753. function padToNBytes(byteLength, padding) {
  90754. assert$7(byteLength >= 0);
  90755. assert$7(padding > 0);
  90756. return byteLength + (padding - 1) & ~(padding - 1);
  90757. }
  90758. function copyToArray(source, target, targetOffset) {
  90759. let sourceArray;
  90760. if (source instanceof ArrayBuffer) {
  90761. sourceArray = new Uint8Array(source);
  90762. } else {
  90763. const srcByteOffset = source.byteOffset;
  90764. const srcByteLength = source.byteLength;
  90765. sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);
  90766. }
  90767. target.set(sourceArray, targetOffset);
  90768. return targetOffset + padToNBytes(sourceArray.byteLength, 4);
  90769. }
  90770. async function concatenateArrayBuffersAsync(asyncIterator) {
  90771. const arrayBuffers = [];
  90772. for await (const chunk of asyncIterator) {
  90773. arrayBuffers.push(chunk);
  90774. }
  90775. return concatenateArrayBuffers(...arrayBuffers);
  90776. }
  90777. function getHiResTimestamp$1() {
  90778. let timestamp;
  90779. if (typeof window !== 'undefined' && window.performance) {
  90780. timestamp = window.performance.now();
  90781. } else if (typeof process !== 'undefined' && process.hrtime) {
  90782. const timeParts = process.hrtime();
  90783. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  90784. } else {
  90785. timestamp = Date.now();
  90786. }
  90787. return timestamp;
  90788. }
  90789. class Stat {
  90790. constructor(name, type) {
  90791. _defineProperty(this, "name", void 0);
  90792. _defineProperty(this, "type", void 0);
  90793. _defineProperty(this, "sampleSize", 1);
  90794. _defineProperty(this, "time", void 0);
  90795. _defineProperty(this, "count", void 0);
  90796. _defineProperty(this, "samples", void 0);
  90797. _defineProperty(this, "lastTiming", void 0);
  90798. _defineProperty(this, "lastSampleTime", void 0);
  90799. _defineProperty(this, "lastSampleCount", void 0);
  90800. _defineProperty(this, "_count", 0);
  90801. _defineProperty(this, "_time", 0);
  90802. _defineProperty(this, "_samples", 0);
  90803. _defineProperty(this, "_startTime", 0);
  90804. _defineProperty(this, "_timerPending", false);
  90805. this.name = name;
  90806. this.type = type;
  90807. this.reset();
  90808. }
  90809. setSampleSize(samples) {
  90810. this.sampleSize = samples;
  90811. return this;
  90812. }
  90813. incrementCount() {
  90814. this.addCount(1);
  90815. return this;
  90816. }
  90817. decrementCount() {
  90818. this.subtractCount(1);
  90819. return this;
  90820. }
  90821. addCount(value) {
  90822. this._count += value;
  90823. this._samples++;
  90824. this._checkSampling();
  90825. return this;
  90826. }
  90827. subtractCount(value) {
  90828. this._count -= value;
  90829. this._samples++;
  90830. this._checkSampling();
  90831. return this;
  90832. }
  90833. addTime(time) {
  90834. this._time += time;
  90835. this.lastTiming = time;
  90836. this._samples++;
  90837. this._checkSampling();
  90838. return this;
  90839. }
  90840. timeStart() {
  90841. this._startTime = getHiResTimestamp$1();
  90842. this._timerPending = true;
  90843. return this;
  90844. }
  90845. timeEnd() {
  90846. if (!this._timerPending) {
  90847. return this;
  90848. }
  90849. this.addTime(getHiResTimestamp$1() - this._startTime);
  90850. this._timerPending = false;
  90851. this._checkSampling();
  90852. return this;
  90853. }
  90854. getSampleAverageCount() {
  90855. return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
  90856. }
  90857. getSampleAverageTime() {
  90858. return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
  90859. }
  90860. getSampleHz() {
  90861. return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;
  90862. }
  90863. getAverageCount() {
  90864. return this.samples > 0 ? this.count / this.samples : 0;
  90865. }
  90866. getAverageTime() {
  90867. return this.samples > 0 ? this.time / this.samples : 0;
  90868. }
  90869. getHz() {
  90870. return this.time > 0 ? this.samples / (this.time / 1000) : 0;
  90871. }
  90872. reset() {
  90873. this.time = 0;
  90874. this.count = 0;
  90875. this.samples = 0;
  90876. this.lastTiming = 0;
  90877. this.lastSampleTime = 0;
  90878. this.lastSampleCount = 0;
  90879. this._count = 0;
  90880. this._time = 0;
  90881. this._samples = 0;
  90882. this._startTime = 0;
  90883. this._timerPending = false;
  90884. return this;
  90885. }
  90886. _checkSampling() {
  90887. if (this._samples === this.sampleSize) {
  90888. this.lastSampleTime = this._time;
  90889. this.lastSampleCount = this._count;
  90890. this.count += this._count;
  90891. this.time += this._time;
  90892. this.samples += this._samples;
  90893. this._time = 0;
  90894. this._count = 0;
  90895. this._samples = 0;
  90896. }
  90897. }
  90898. }
  90899. class Stats$1 {
  90900. constructor(options) {
  90901. _defineProperty(this, "id", void 0);
  90902. _defineProperty(this, "stats", {});
  90903. this.id = options.id;
  90904. this.stats = {};
  90905. this._initializeStats(options.stats);
  90906. Object.seal(this);
  90907. }
  90908. get(name) {
  90909. let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'count';
  90910. return this._getOrCreate({
  90911. name,
  90912. type
  90913. });
  90914. }
  90915. get size() {
  90916. return Object.keys(this.stats).length;
  90917. }
  90918. reset() {
  90919. for (const key in this.stats) {
  90920. this.stats[key].reset();
  90921. }
  90922. return this;
  90923. }
  90924. forEach(fn) {
  90925. for (const key in this.stats) {
  90926. fn(this.stats[key]);
  90927. }
  90928. }
  90929. getTable() {
  90930. const table = {};
  90931. this.forEach(stat => {
  90932. table[stat.name] = {
  90933. time: stat.time || 0,
  90934. count: stat.count || 0,
  90935. average: stat.getAverageTime() || 0,
  90936. hz: stat.getHz() || 0
  90937. };
  90938. });
  90939. return table;
  90940. }
  90941. _initializeStats() {
  90942. let stats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  90943. stats.forEach(stat => this._getOrCreate(stat));
  90944. }
  90945. _getOrCreate(stat) {
  90946. if (!stat || !stat.name) {
  90947. return null;
  90948. }
  90949. const {
  90950. name,
  90951. type
  90952. } = stat;
  90953. if (!this.stats[name]) {
  90954. if (stat instanceof Stat) {
  90955. this.stats[name] = stat;
  90956. } else {
  90957. this.stats[name] = new Stat(name, type);
  90958. }
  90959. }
  90960. return this.stats[name];
  90961. }
  90962. }
  90963. const STAT_QUEUED_REQUESTS = 'Queued Requests';
  90964. const STAT_ACTIVE_REQUESTS = 'Active Requests';
  90965. const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
  90966. const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
  90967. const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
  90968. const DEFAULT_PROPS$2 = {
  90969. id: 'request-scheduler',
  90970. throttleRequests: true,
  90971. maxRequests: 6
  90972. };
  90973. class RequestScheduler {
  90974. constructor(props = {}) {
  90975. _defineProperty(this, "props", void 0);
  90976. _defineProperty(this, "stats", void 0);
  90977. _defineProperty(this, "activeRequestCount", 0);
  90978. _defineProperty(this, "requestQueue", []);
  90979. _defineProperty(this, "requestMap", new Map());
  90980. _defineProperty(this, "deferredUpdate", null);
  90981. this.props = { ...DEFAULT_PROPS$2,
  90982. ...props
  90983. };
  90984. this.stats = new Stats$1({
  90985. id: this.props.id
  90986. });
  90987. this.stats.get(STAT_QUEUED_REQUESTS);
  90988. this.stats.get(STAT_ACTIVE_REQUESTS);
  90989. this.stats.get(STAT_CANCELLED_REQUESTS);
  90990. this.stats.get(STAT_QUEUED_REQUESTS_EVER);
  90991. this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
  90992. }
  90993. scheduleRequest(handle, getPriority = () => 0) {
  90994. if (!this.props.throttleRequests) {
  90995. return Promise.resolve({
  90996. done: () => {}
  90997. });
  90998. }
  90999. if (this.requestMap.has(handle)) {
  91000. return this.requestMap.get(handle);
  91001. }
  91002. const request = {
  91003. handle,
  91004. priority: 0,
  91005. getPriority
  91006. };
  91007. const promise = new Promise(resolve => {
  91008. request.resolve = resolve;
  91009. return request;
  91010. });
  91011. this.requestQueue.push(request);
  91012. this.requestMap.set(handle, promise);
  91013. this._issueNewRequests();
  91014. return promise;
  91015. }
  91016. _issueRequest(request) {
  91017. const {
  91018. handle,
  91019. resolve
  91020. } = request;
  91021. let isDone = false;
  91022. const done = () => {
  91023. if (!isDone) {
  91024. isDone = true;
  91025. this.requestMap.delete(handle);
  91026. this.activeRequestCount--;
  91027. this._issueNewRequests();
  91028. }
  91029. };
  91030. this.activeRequestCount++;
  91031. return resolve ? resolve({
  91032. done
  91033. }) : Promise.resolve({
  91034. done
  91035. });
  91036. }
  91037. _issueNewRequests() {
  91038. if (!this.deferredUpdate) {
  91039. this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
  91040. }
  91041. }
  91042. _issueNewRequestsAsync() {
  91043. this.deferredUpdate = null;
  91044. const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
  91045. if (freeSlots === 0) {
  91046. return;
  91047. }
  91048. this._updateAllRequests();
  91049. for (let i = 0; i < freeSlots; ++i) {
  91050. const request = this.requestQueue.shift();
  91051. if (request) {
  91052. this._issueRequest(request);
  91053. }
  91054. }
  91055. }
  91056. _updateAllRequests() {
  91057. const requestQueue = this.requestQueue;
  91058. for (let i = 0; i < requestQueue.length; ++i) {
  91059. const request = requestQueue[i];
  91060. if (!this._updateRequest(request)) {
  91061. requestQueue.splice(i, 1);
  91062. this.requestMap.delete(request.handle);
  91063. i--;
  91064. }
  91065. }
  91066. requestQueue.sort((a, b) => a.priority - b.priority);
  91067. }
  91068. _updateRequest(request) {
  91069. request.priority = request.getPriority(request.handle);
  91070. if (request.priority < 0) {
  91071. request.resolve(null);
  91072. return false;
  91073. }
  91074. return true;
  91075. }
  91076. }
  91077. let pathPrefix = '';
  91078. const fileAliases = {};
  91079. function resolvePath(filename) {
  91080. for (const alias in fileAliases) {
  91081. if (filename.startsWith(alias)) {
  91082. const replacement = fileAliases[alias];
  91083. filename = filename.replace(alias, replacement);
  91084. }
  91085. }
  91086. if (!filename.startsWith('http://') && !filename.startsWith('https://')) {
  91087. filename = "".concat(pathPrefix).concat(filename);
  91088. }
  91089. return filename;
  91090. }
  91091. function filename(url) {
  91092. const slashIndex = url && url.lastIndexOf('/');
  91093. return slashIndex >= 0 ? url.substr(slashIndex + 1) : '';
  91094. }
  91095. function dirname(url) {
  91096. const slashIndex = url && url.lastIndexOf('/');
  91097. return slashIndex >= 0 ? url.substr(0, slashIndex) : '';
  91098. }
  91099. const isBoolean = x => typeof x === 'boolean';
  91100. const isFunction = x => typeof x === 'function';
  91101. const isObject = x => x !== null && typeof x === 'object';
  91102. const isPureObject = x => isObject(x) && x.constructor === {}.constructor;
  91103. const isIterable = x => x && typeof x[Symbol.iterator] === 'function';
  91104. const isAsyncIterable = x => x && typeof x[Symbol.asyncIterator] === 'function';
  91105. const isResponse = x => typeof Response !== 'undefined' && x instanceof Response || x && x.arrayBuffer && x.text && x.json;
  91106. const isBlob = x => typeof Blob !== 'undefined' && x instanceof Blob;
  91107. const isBuffer = x => x && typeof x === 'object' && x.isBuffer;
  91108. const isReadableDOMStream = x => typeof ReadableStream !== 'undefined' && x instanceof ReadableStream || isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader);
  91109. const isReadableNodeStream = x => isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);
  91110. const isReadableStream = x => isReadableDOMStream(x) || isReadableNodeStream(x);
  91111. const DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
  91112. const MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
  91113. function parseMIMEType(mimeString) {
  91114. const matches = MIME_TYPE_PATTERN.exec(mimeString);
  91115. if (matches) {
  91116. return matches[1];
  91117. }
  91118. return mimeString;
  91119. }
  91120. function parseMIMETypeFromURL(url) {
  91121. const matches = DATA_URL_PATTERN.exec(url);
  91122. if (matches) {
  91123. return matches[1];
  91124. }
  91125. return '';
  91126. }
  91127. const QUERY_STRING_PATTERN = /\?.*/;
  91128. function getResourceUrlAndType(resource) {
  91129. if (isResponse(resource)) {
  91130. const url = stripQueryString(resource.url || '');
  91131. const contentTypeHeader = resource.headers.get('content-type') || '';
  91132. return {
  91133. url,
  91134. type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)
  91135. };
  91136. }
  91137. if (isBlob(resource)) {
  91138. return {
  91139. url: stripQueryString(resource.name || ''),
  91140. type: resource.type || ''
  91141. };
  91142. }
  91143. if (typeof resource === 'string') {
  91144. return {
  91145. url: stripQueryString(resource),
  91146. type: parseMIMETypeFromURL(resource)
  91147. };
  91148. }
  91149. return {
  91150. url: '',
  91151. type: ''
  91152. };
  91153. }
  91154. function getResourceContentLength(resource) {
  91155. if (isResponse(resource)) {
  91156. return resource.headers['content-length'] || -1;
  91157. }
  91158. if (isBlob(resource)) {
  91159. return resource.size;
  91160. }
  91161. if (typeof resource === 'string') {
  91162. return resource.length;
  91163. }
  91164. if (resource instanceof ArrayBuffer) {
  91165. return resource.byteLength;
  91166. }
  91167. if (ArrayBuffer.isView(resource)) {
  91168. return resource.byteLength;
  91169. }
  91170. return -1;
  91171. }
  91172. function stripQueryString(url) {
  91173. return url.replace(QUERY_STRING_PATTERN, '');
  91174. }
  91175. async function makeResponse(resource) {
  91176. if (isResponse(resource)) {
  91177. return resource;
  91178. }
  91179. const headers = {};
  91180. const contentLength = getResourceContentLength(resource);
  91181. if (contentLength >= 0) {
  91182. headers['content-length'] = String(contentLength);
  91183. }
  91184. const {
  91185. url,
  91186. type
  91187. } = getResourceUrlAndType(resource);
  91188. if (type) {
  91189. headers['content-type'] = type;
  91190. }
  91191. const initialDataUrl = await getInitialDataUrl(resource);
  91192. if (initialDataUrl) {
  91193. headers['x-first-bytes'] = initialDataUrl;
  91194. }
  91195. if (typeof resource === 'string') {
  91196. resource = new TextEncoder().encode(resource);
  91197. }
  91198. const response = new Response(resource, {
  91199. headers
  91200. });
  91201. Object.defineProperty(response, 'url', {
  91202. value: url
  91203. });
  91204. return response;
  91205. }
  91206. async function checkResponse(response) {
  91207. if (!response.ok) {
  91208. const message = await getResponseError(response);
  91209. throw new Error(message);
  91210. }
  91211. }
  91212. async function getResponseError(response) {
  91213. let message = "Failed to fetch resource ".concat(response.url, " (").concat(response.status, "): ");
  91214. try {
  91215. const contentType = response.headers.get('Content-Type');
  91216. let text = response.statusText;
  91217. if (contentType.includes('application/json')) {
  91218. text += " ".concat(await response.text());
  91219. }
  91220. message += text;
  91221. message = message.length > 60 ? "".concat(message.slice(60), "...") : message;
  91222. } catch (error) {}
  91223. return message;
  91224. }
  91225. async function getInitialDataUrl(resource) {
  91226. const INITIAL_DATA_LENGTH = 5;
  91227. if (typeof resource === 'string') {
  91228. return "data:,".concat(resource.slice(0, INITIAL_DATA_LENGTH));
  91229. }
  91230. if (resource instanceof Blob) {
  91231. const blobSlice = resource.slice(0, 5);
  91232. return await new Promise(resolve => {
  91233. const reader = new FileReader();
  91234. reader.onload = event => {
  91235. var _event$target;
  91236. return resolve(event === null || event === void 0 ? void 0 : (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.result);
  91237. };
  91238. reader.readAsDataURL(blobSlice);
  91239. });
  91240. }
  91241. if (resource instanceof ArrayBuffer) {
  91242. const slice = resource.slice(0, INITIAL_DATA_LENGTH);
  91243. const base64 = arrayBufferToBase64(slice);
  91244. return "data:base64,".concat(base64);
  91245. }
  91246. return null;
  91247. }
  91248. function arrayBufferToBase64(buffer) {
  91249. let binary = '';
  91250. const bytes = new Uint8Array(buffer);
  91251. for (let i = 0; i < bytes.byteLength; i++) {
  91252. binary += String.fromCharCode(bytes[i]);
  91253. }
  91254. return btoa(binary);
  91255. }
  91256. async function fetchFile(url, options) {
  91257. if (typeof url === 'string') {
  91258. url = resolvePath(url);
  91259. let fetchOptions = options;
  91260. if (options !== null && options !== void 0 && options.fetch && typeof (options === null || options === void 0 ? void 0 : options.fetch) !== 'function') {
  91261. fetchOptions = options.fetch;
  91262. }
  91263. return await fetch(url, fetchOptions);
  91264. }
  91265. return await makeResponse(url);
  91266. }
  91267. function isElectron(mockUserAgent) {
  91268. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  91269. return true;
  91270. }
  91271. if (typeof process !== 'undefined' && typeof process.versions === 'object' && Boolean(process.versions.electron)) {
  91272. return true;
  91273. }
  91274. const realUserAgent = typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;
  91275. const userAgent = mockUserAgent || realUserAgent;
  91276. if (userAgent && userAgent.indexOf('Electron') >= 0) {
  91277. return true;
  91278. }
  91279. return false;
  91280. }
  91281. function isBrowser() {
  91282. const isNode = typeof process === 'object' && String(process) === '[object process]' && !process.browser;
  91283. return !isNode || isElectron();
  91284. }
  91285. const globals = {
  91286. self: typeof self !== 'undefined' && self,
  91287. window: typeof window !== 'undefined' && window,
  91288. global: typeof global !== 'undefined' && global,
  91289. document: typeof document !== 'undefined' && document,
  91290. process: typeof process === 'object' && process
  91291. };
  91292. const window_ = globals.window || globals.self || globals.global;
  91293. const process_ = globals.process || {};
  91294. const VERSION$6 = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';
  91295. isBrowser();
  91296. function getStorage(type) {
  91297. try {
  91298. const storage = window[type];
  91299. const x = '__storage_test__';
  91300. storage.setItem(x, x);
  91301. storage.removeItem(x);
  91302. return storage;
  91303. } catch (e) {
  91304. return null;
  91305. }
  91306. }
  91307. class LocalStorage {
  91308. constructor(id) {
  91309. let defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  91310. let type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage';
  91311. _defineProperty(this, "storage", void 0);
  91312. _defineProperty(this, "id", void 0);
  91313. _defineProperty(this, "config", {});
  91314. this.storage = getStorage(type);
  91315. this.id = id;
  91316. this.config = {};
  91317. Object.assign(this.config, defaultSettings);
  91318. this._loadConfiguration();
  91319. }
  91320. getConfiguration() {
  91321. return this.config;
  91322. }
  91323. setConfiguration(configuration) {
  91324. this.config = {};
  91325. return this.updateConfiguration(configuration);
  91326. }
  91327. updateConfiguration(configuration) {
  91328. Object.assign(this.config, configuration);
  91329. if (this.storage) {
  91330. const serialized = JSON.stringify(this.config);
  91331. this.storage.setItem(this.id, serialized);
  91332. }
  91333. return this;
  91334. }
  91335. _loadConfiguration() {
  91336. let configuration = {};
  91337. if (this.storage) {
  91338. const serializedConfiguration = this.storage.getItem(this.id);
  91339. configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
  91340. }
  91341. Object.assign(this.config, configuration);
  91342. return this;
  91343. }
  91344. }
  91345. function formatTime(ms) {
  91346. let formatted;
  91347. if (ms < 10) {
  91348. formatted = "".concat(ms.toFixed(2), "ms");
  91349. } else if (ms < 100) {
  91350. formatted = "".concat(ms.toFixed(1), "ms");
  91351. } else if (ms < 1000) {
  91352. formatted = "".concat(ms.toFixed(0), "ms");
  91353. } else {
  91354. formatted = "".concat((ms / 1000).toFixed(2), "s");
  91355. }
  91356. return formatted;
  91357. }
  91358. function leftPad(string) {
  91359. let length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8;
  91360. const padLength = Math.max(length - string.length, 0);
  91361. return "".concat(' '.repeat(padLength)).concat(string);
  91362. }
  91363. function formatImage(image, message, scale) {
  91364. let maxWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 600;
  91365. const imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29');
  91366. if (image.width > maxWidth) {
  91367. scale = Math.min(scale, maxWidth / image.width);
  91368. }
  91369. const width = image.width * scale;
  91370. const height = image.height * scale;
  91371. const style = ['font-size:1px;', "padding:".concat(Math.floor(height / 2), "px ").concat(Math.floor(width / 2), "px;"), "line-height:".concat(height, "px;"), "background:url(".concat(imageUrl, ");"), "background-size:".concat(width, "px ").concat(height, "px;"), 'color:transparent;'].join('');
  91372. return ["".concat(message, " %c+"), style];
  91373. }
  91374. let COLOR;
  91375. (function (COLOR) {
  91376. COLOR[COLOR["BLACK"] = 30] = "BLACK";
  91377. COLOR[COLOR["RED"] = 31] = "RED";
  91378. COLOR[COLOR["GREEN"] = 32] = "GREEN";
  91379. COLOR[COLOR["YELLOW"] = 33] = "YELLOW";
  91380. COLOR[COLOR["BLUE"] = 34] = "BLUE";
  91381. COLOR[COLOR["MAGENTA"] = 35] = "MAGENTA";
  91382. COLOR[COLOR["CYAN"] = 36] = "CYAN";
  91383. COLOR[COLOR["WHITE"] = 37] = "WHITE";
  91384. COLOR[COLOR["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
  91385. COLOR[COLOR["BRIGHT_RED"] = 91] = "BRIGHT_RED";
  91386. COLOR[COLOR["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
  91387. COLOR[COLOR["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
  91388. COLOR[COLOR["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
  91389. COLOR[COLOR["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
  91390. COLOR[COLOR["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
  91391. COLOR[COLOR["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
  91392. })(COLOR || (COLOR = {}));
  91393. function getColor$1(color) {
  91394. return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color;
  91395. }
  91396. function addColor(string, color, background) {
  91397. if (!isBrowser && typeof string === 'string') {
  91398. if (color) {
  91399. color = getColor$1(color);
  91400. string = "\x1B[".concat(color, "m").concat(string, "\x1B[39m");
  91401. }
  91402. if (background) {
  91403. color = getColor$1(background);
  91404. string = "\x1B[".concat(background + 10, "m").concat(string, "\x1B[49m");
  91405. }
  91406. }
  91407. return string;
  91408. }
  91409. function autobind(obj) {
  91410. let predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor'];
  91411. const proto = Object.getPrototypeOf(obj);
  91412. const propNames = Object.getOwnPropertyNames(proto);
  91413. for (const key of propNames) {
  91414. if (typeof obj[key] === 'function') {
  91415. if (!predefined.find(name => key === name)) {
  91416. obj[key] = obj[key].bind(obj);
  91417. }
  91418. }
  91419. }
  91420. }
  91421. function assert$5(condition, message) {
  91422. if (!condition) {
  91423. throw new Error(message || 'Assertion failed');
  91424. }
  91425. }
  91426. function getHiResTimestamp() {
  91427. let timestamp;
  91428. if (isBrowser && 'performance' in window_) {
  91429. var _window$performance, _window$performance$n;
  91430. 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);
  91431. } else if ('hrtime' in process_) {
  91432. var _process$hrtime;
  91433. const timeParts = process_ === null || process_ === void 0 ? void 0 : (_process$hrtime = process_.hrtime) === null || _process$hrtime === void 0 ? void 0 : _process$hrtime.call(process_);
  91434. timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;
  91435. } else {
  91436. timestamp = Date.now();
  91437. }
  91438. return timestamp;
  91439. }
  91440. const originalConsole = {
  91441. debug: isBrowser ? console.debug || console.log : console.log,
  91442. log: console.log,
  91443. info: console.info,
  91444. warn: console.warn,
  91445. error: console.error
  91446. };
  91447. const DEFAULT_SETTINGS = {
  91448. enabled: true,
  91449. level: 0
  91450. };
  91451. function noop$1() {}
  91452. const cache = {};
  91453. const ONCE = {
  91454. once: true
  91455. };
  91456. class Log {
  91457. constructor() {
  91458. let {
  91459. id
  91460. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
  91461. id: ''
  91462. };
  91463. _defineProperty(this, "id", void 0);
  91464. _defineProperty(this, "VERSION", VERSION$6);
  91465. _defineProperty(this, "_startTs", getHiResTimestamp());
  91466. _defineProperty(this, "_deltaTs", getHiResTimestamp());
  91467. _defineProperty(this, "_storage", void 0);
  91468. _defineProperty(this, "userData", {});
  91469. _defineProperty(this, "LOG_THROTTLE_TIMEOUT", 0);
  91470. this.id = id;
  91471. this._storage = new LocalStorage("__probe-".concat(this.id, "__"), DEFAULT_SETTINGS);
  91472. this.userData = {};
  91473. this.timeStamp("".concat(this.id, " started"));
  91474. autobind(this);
  91475. Object.seal(this);
  91476. }
  91477. set level(newLevel) {
  91478. this.setLevel(newLevel);
  91479. }
  91480. get level() {
  91481. return this.getLevel();
  91482. }
  91483. isEnabled() {
  91484. return this._storage.config.enabled;
  91485. }
  91486. getLevel() {
  91487. return this._storage.config.level;
  91488. }
  91489. getTotal() {
  91490. return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
  91491. }
  91492. getDelta() {
  91493. return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
  91494. }
  91495. set priority(newPriority) {
  91496. this.level = newPriority;
  91497. }
  91498. get priority() {
  91499. return this.level;
  91500. }
  91501. getPriority() {
  91502. return this.level;
  91503. }
  91504. enable() {
  91505. let enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  91506. this._storage.updateConfiguration({
  91507. enabled
  91508. });
  91509. return this;
  91510. }
  91511. setLevel(level) {
  91512. this._storage.updateConfiguration({
  91513. level
  91514. });
  91515. return this;
  91516. }
  91517. get(setting) {
  91518. return this._storage.config[setting];
  91519. }
  91520. set(setting, value) {
  91521. this._storage.updateConfiguration({
  91522. [setting]: value
  91523. });
  91524. }
  91525. settings() {
  91526. if (console.table) {
  91527. console.table(this._storage.config);
  91528. } else {
  91529. console.log(this._storage.config);
  91530. }
  91531. }
  91532. assert(condition, message) {
  91533. assert$5(condition, message);
  91534. }
  91535. warn(message) {
  91536. return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
  91537. }
  91538. error(message) {
  91539. return this._getLogFunction(0, message, originalConsole.error, arguments);
  91540. }
  91541. deprecated(oldUsage, newUsage) {
  91542. return this.warn("`".concat(oldUsage, "` is deprecated and will be removed in a later version. Use `").concat(newUsage, "` instead"));
  91543. }
  91544. removed(oldUsage, newUsage) {
  91545. return this.error("`".concat(oldUsage, "` has been removed. Use `").concat(newUsage, "` instead"));
  91546. }
  91547. probe(logLevel, message) {
  91548. return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
  91549. time: true,
  91550. once: true
  91551. });
  91552. }
  91553. log(logLevel, message) {
  91554. return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
  91555. }
  91556. info(logLevel, message) {
  91557. return this._getLogFunction(logLevel, message, console.info, arguments);
  91558. }
  91559. once(logLevel, message) {
  91560. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  91561. args[_key - 2] = arguments[_key];
  91562. }
  91563. return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
  91564. }
  91565. table(logLevel, table, columns) {
  91566. if (table) {
  91567. return this._getLogFunction(logLevel, table, console.table || noop$1, columns && [columns], {
  91568. tag: getTableHeader(table)
  91569. });
  91570. }
  91571. return noop$1;
  91572. }
  91573. image(_ref) {
  91574. let {
  91575. logLevel,
  91576. priority,
  91577. image,
  91578. message = '',
  91579. scale = 1
  91580. } = _ref;
  91581. if (!this._shouldLog(logLevel || priority)) {
  91582. return noop$1;
  91583. }
  91584. return isBrowser ? logImageInBrowser({
  91585. image,
  91586. message,
  91587. scale
  91588. }) : logImageInNode({
  91589. image,
  91590. message,
  91591. scale
  91592. });
  91593. }
  91594. time(logLevel, message) {
  91595. return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
  91596. }
  91597. timeEnd(logLevel, message) {
  91598. return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
  91599. }
  91600. timeStamp(logLevel, message) {
  91601. return this._getLogFunction(logLevel, message, console.timeStamp || noop$1);
  91602. }
  91603. group(logLevel, message) {
  91604. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  91605. collapsed: false
  91606. };
  91607. const options = normalizeArguments({
  91608. logLevel,
  91609. message,
  91610. opts
  91611. });
  91612. const {
  91613. collapsed
  91614. } = opts;
  91615. options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
  91616. return this._getLogFunction(options);
  91617. }
  91618. groupCollapsed(logLevel, message) {
  91619. let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  91620. return this.group(logLevel, message, Object.assign({}, opts, {
  91621. collapsed: true
  91622. }));
  91623. }
  91624. groupEnd(logLevel) {
  91625. return this._getLogFunction(logLevel, '', console.groupEnd || noop$1);
  91626. }
  91627. withGroup(logLevel, message, func) {
  91628. this.group(logLevel, message)();
  91629. try {
  91630. func();
  91631. } finally {
  91632. this.groupEnd(logLevel)();
  91633. }
  91634. }
  91635. trace() {
  91636. if (console.trace) {
  91637. console.trace();
  91638. }
  91639. }
  91640. _shouldLog(logLevel) {
  91641. return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
  91642. }
  91643. _getLogFunction(logLevel, message, method, args, opts) {
  91644. if (this._shouldLog(logLevel)) {
  91645. opts = normalizeArguments({
  91646. logLevel,
  91647. message,
  91648. args,
  91649. opts
  91650. });
  91651. method = method || opts.method;
  91652. assert$5(method);
  91653. opts.total = this.getTotal();
  91654. opts.delta = this.getDelta();
  91655. this._deltaTs = getHiResTimestamp();
  91656. const tag = opts.tag || opts.message;
  91657. if (opts.once) {
  91658. if (!cache[tag]) {
  91659. cache[tag] = getHiResTimestamp();
  91660. } else {
  91661. return noop$1;
  91662. }
  91663. }
  91664. message = decorateMessage(this.id, opts.message, opts);
  91665. return method.bind(console, message, ...opts.args);
  91666. }
  91667. return noop$1;
  91668. }
  91669. }
  91670. _defineProperty(Log, "VERSION", VERSION$6);
  91671. function normalizeLogLevel(logLevel) {
  91672. if (!logLevel) {
  91673. return 0;
  91674. }
  91675. let resolvedLevel;
  91676. switch (typeof logLevel) {
  91677. case 'number':
  91678. resolvedLevel = logLevel;
  91679. break;
  91680. case 'object':
  91681. resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
  91682. break;
  91683. default:
  91684. return 0;
  91685. }
  91686. assert$5(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
  91687. return resolvedLevel;
  91688. }
  91689. function normalizeArguments(opts) {
  91690. const {
  91691. logLevel,
  91692. message
  91693. } = opts;
  91694. opts.logLevel = normalizeLogLevel(logLevel);
  91695. const args = opts.args ? Array.from(opts.args) : [];
  91696. while (args.length && args.shift() !== message) {}
  91697. switch (typeof logLevel) {
  91698. case 'string':
  91699. case 'function':
  91700. if (message !== undefined) {
  91701. args.unshift(message);
  91702. }
  91703. opts.message = logLevel;
  91704. break;
  91705. case 'object':
  91706. Object.assign(opts, logLevel);
  91707. break;
  91708. }
  91709. if (typeof opts.message === 'function') {
  91710. opts.message = opts.message();
  91711. }
  91712. const messageType = typeof opts.message;
  91713. assert$5(messageType === 'string' || messageType === 'object');
  91714. return Object.assign(opts, {
  91715. args
  91716. }, opts.opts);
  91717. }
  91718. function decorateMessage(id, message, opts) {
  91719. if (typeof message === 'string') {
  91720. const time = opts.time ? leftPad(formatTime(opts.total)) : '';
  91721. message = opts.time ? "".concat(id, ": ").concat(time, " ").concat(message) : "".concat(id, ": ").concat(message);
  91722. message = addColor(message, opts.color, opts.background);
  91723. }
  91724. return message;
  91725. }
  91726. function logImageInNode(_ref2) {
  91727. let {
  91728. image,
  91729. message = '',
  91730. scale = 1
  91731. } = _ref2;
  91732. let asciify = null;
  91733. try {
  91734. asciify = module.require('asciify-image');
  91735. } catch (error) {}
  91736. if (asciify) {
  91737. return () => asciify(image, {
  91738. fit: 'box',
  91739. width: "".concat(Math.round(80 * scale), "%")
  91740. }).then(data => console.log(data));
  91741. }
  91742. return noop$1;
  91743. }
  91744. function logImageInBrowser(_ref3) {
  91745. let {
  91746. image,
  91747. message = '',
  91748. scale = 1
  91749. } = _ref3;
  91750. if (typeof image === 'string') {
  91751. const img = new Image();
  91752. img.onload = () => {
  91753. const args = formatImage(img, message, scale);
  91754. console.log(...args);
  91755. };
  91756. img.src = image;
  91757. return noop$1;
  91758. }
  91759. const element = image.nodeName || '';
  91760. if (element.toLowerCase() === 'img') {
  91761. console.log(...formatImage(image, message, scale));
  91762. return noop$1;
  91763. }
  91764. if (element.toLowerCase() === 'canvas') {
  91765. const img = new Image();
  91766. img.onload = () => console.log(...formatImage(img, message, scale));
  91767. img.src = image.toDataURL();
  91768. return noop$1;
  91769. }
  91770. return noop$1;
  91771. }
  91772. function getTableHeader(table) {
  91773. for (const key in table) {
  91774. for (const title in table[key]) {
  91775. return title || 'untitled';
  91776. }
  91777. }
  91778. return 'empty';
  91779. }
  91780. const probeLog = new Log({
  91781. id: 'loaders.gl'
  91782. });
  91783. class NullLog {
  91784. log() {
  91785. return () => {};
  91786. }
  91787. info() {
  91788. return () => {};
  91789. }
  91790. warn() {
  91791. return () => {};
  91792. }
  91793. error() {
  91794. return () => {};
  91795. }
  91796. }
  91797. class ConsoleLog {
  91798. constructor() {
  91799. _defineProperty(this, "console", void 0);
  91800. this.console = console;
  91801. }
  91802. log(...args) {
  91803. return this.console.log.bind(this.console, ...args);
  91804. }
  91805. info(...args) {
  91806. return this.console.info.bind(this.console, ...args);
  91807. }
  91808. warn(...args) {
  91809. return this.console.warn.bind(this.console, ...args);
  91810. }
  91811. error(...args) {
  91812. return this.console.error.bind(this.console, ...args);
  91813. }
  91814. }
  91815. const DEFAULT_LOADER_OPTIONS = {
  91816. fetch: null,
  91817. mimeType: undefined,
  91818. nothrow: false,
  91819. log: new ConsoleLog(),
  91820. CDN: 'https://unpkg.com/@loaders.gl',
  91821. worker: true,
  91822. maxConcurrency: 3,
  91823. maxMobileConcurrency: 1,
  91824. reuseWorkers: true,
  91825. _workerType: '',
  91826. limit: 0,
  91827. _limitMB: 0,
  91828. batchSize: 'auto',
  91829. batchDebounceMs: 0,
  91830. metadata: false,
  91831. transforms: []
  91832. };
  91833. const REMOVED_LOADER_OPTIONS = {
  91834. throws: 'nothrow',
  91835. dataType: '(no longer used)',
  91836. uri: 'baseUri',
  91837. method: 'fetch.method',
  91838. headers: 'fetch.headers',
  91839. body: 'fetch.body',
  91840. mode: 'fetch.mode',
  91841. credentials: 'fetch.credentials',
  91842. cache: 'fetch.cache',
  91843. redirect: 'fetch.redirect',
  91844. referrer: 'fetch.referrer',
  91845. referrerPolicy: 'fetch.referrerPolicy',
  91846. integrity: 'fetch.integrity',
  91847. keepalive: 'fetch.keepalive',
  91848. signal: 'fetch.signal'
  91849. };
  91850. function getGlobalLoaderState() {
  91851. globalThis.loaders = globalThis.loaders || {};
  91852. const {
  91853. loaders
  91854. } = globalThis;
  91855. loaders._state = loaders._state || {};
  91856. return loaders._state;
  91857. }
  91858. const getGlobalLoaderOptions = () => {
  91859. const state = getGlobalLoaderState();
  91860. state.globalOptions = state.globalOptions || { ...DEFAULT_LOADER_OPTIONS
  91861. };
  91862. return state.globalOptions;
  91863. };
  91864. function normalizeOptions(options, loader, loaders, url) {
  91865. loaders = loaders || [];
  91866. loaders = Array.isArray(loaders) ? loaders : [loaders];
  91867. validateOptions(options, loaders);
  91868. return normalizeOptionsInternal(loader, options, url);
  91869. }
  91870. function getFetchFunction(options, context) {
  91871. const globalOptions = getGlobalLoaderOptions();
  91872. const fetchOptions = options || globalOptions;
  91873. if (typeof fetchOptions.fetch === 'function') {
  91874. return fetchOptions.fetch;
  91875. }
  91876. if (isObject(fetchOptions.fetch)) {
  91877. return url => fetchFile(url, fetchOptions);
  91878. }
  91879. if (context !== null && context !== void 0 && context.fetch) {
  91880. return context === null || context === void 0 ? void 0 : context.fetch;
  91881. }
  91882. return fetchFile;
  91883. }
  91884. function validateOptions(options, loaders) {
  91885. validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
  91886. for (const loader of loaders) {
  91887. const idOptions = options && options[loader.id] || {};
  91888. const loaderOptions = loader.options && loader.options[loader.id] || {};
  91889. const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
  91890. validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
  91891. }
  91892. }
  91893. function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
  91894. const loaderName = id || 'Top level';
  91895. const prefix = id ? "".concat(id, ".") : '';
  91896. for (const key in options) {
  91897. const isSubOptions = !id && isObject(options[key]);
  91898. const isBaseUriOption = key === 'baseUri' && !id;
  91899. const isWorkerUrlOption = key === 'workerUrl' && id;
  91900. if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
  91901. if (key in deprecatedOptions) {
  91902. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' no longer supported, use '").concat(deprecatedOptions[key], "'"))();
  91903. } else if (!isSubOptions) {
  91904. const suggestion = findSimilarOption(key, loaders);
  91905. probeLog.warn("".concat(loaderName, " loader option '").concat(prefix).concat(key, "' not recognized. ").concat(suggestion))();
  91906. }
  91907. }
  91908. }
  91909. }
  91910. function findSimilarOption(optionKey, loaders) {
  91911. const lowerCaseOptionKey = optionKey.toLowerCase();
  91912. let bestSuggestion = '';
  91913. for (const loader of loaders) {
  91914. for (const key in loader.options) {
  91915. if (optionKey === key) {
  91916. return "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  91917. }
  91918. const lowerCaseKey = key.toLowerCase();
  91919. const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
  91920. if (isPartialMatch) {
  91921. bestSuggestion = bestSuggestion || "Did you mean '".concat(loader.id, ".").concat(key, "'?");
  91922. }
  91923. }
  91924. }
  91925. return bestSuggestion;
  91926. }
  91927. function normalizeOptionsInternal(loader, options, url) {
  91928. const loaderDefaultOptions = loader.options || {};
  91929. const mergedOptions = { ...loaderDefaultOptions
  91930. };
  91931. addUrlOptions(mergedOptions, url);
  91932. if (mergedOptions.log === null) {
  91933. mergedOptions.log = new NullLog();
  91934. }
  91935. mergeNestedFields(mergedOptions, getGlobalLoaderOptions());
  91936. mergeNestedFields(mergedOptions, options);
  91937. return mergedOptions;
  91938. }
  91939. function mergeNestedFields(mergedOptions, options) {
  91940. for (const key in options) {
  91941. if (key in options) {
  91942. const value = options[key];
  91943. if (isPureObject(value) && isPureObject(mergedOptions[key])) {
  91944. mergedOptions[key] = { ...mergedOptions[key],
  91945. ...options[key]
  91946. };
  91947. } else {
  91948. mergedOptions[key] = options[key];
  91949. }
  91950. }
  91951. }
  91952. }
  91953. function addUrlOptions(options, url) {
  91954. if (url && !('baseUri' in options)) {
  91955. options.baseUri = url;
  91956. }
  91957. }
  91958. function isLoaderObject(loader) {
  91959. var _loader;
  91960. if (!loader) {
  91961. return false;
  91962. }
  91963. if (Array.isArray(loader)) {
  91964. loader = loader[0];
  91965. }
  91966. const hasExtensions = Array.isArray((_loader = loader) === null || _loader === void 0 ? void 0 : _loader.extensions);
  91967. return hasExtensions;
  91968. }
  91969. function normalizeLoader(loader) {
  91970. var _loader2, _loader3;
  91971. assert$7(loader, 'null loader');
  91972. assert$7(isLoaderObject(loader), 'invalid loader');
  91973. let options;
  91974. if (Array.isArray(loader)) {
  91975. options = loader[1];
  91976. loader = loader[0];
  91977. loader = { ...loader,
  91978. options: { ...loader.options,
  91979. ...options
  91980. }
  91981. };
  91982. }
  91983. if ((_loader2 = loader) !== null && _loader2 !== void 0 && _loader2.parseTextSync || (_loader3 = loader) !== null && _loader3 !== void 0 && _loader3.parseText) {
  91984. loader.text = true;
  91985. }
  91986. if (!loader.text) {
  91987. loader.binary = true;
  91988. }
  91989. return loader;
  91990. }
  91991. const getGlobalLoaderRegistry = () => {
  91992. const state = getGlobalLoaderState();
  91993. state.loaderRegistry = state.loaderRegistry || [];
  91994. return state.loaderRegistry;
  91995. };
  91996. function getRegisteredLoaders() {
  91997. return getGlobalLoaderRegistry();
  91998. }
  91999. const EXT_PATTERN = /\.([^.]+)$/;
  92000. async function selectLoader(data, loaders = [], options, context) {
  92001. if (!validHTTPResponse(data)) {
  92002. return null;
  92003. }
  92004. let loader = selectLoaderSync(data, loaders, { ...options,
  92005. nothrow: true
  92006. }, context);
  92007. if (loader) {
  92008. return loader;
  92009. }
  92010. if (isBlob(data)) {
  92011. data = await data.slice(0, 10).arrayBuffer();
  92012. loader = selectLoaderSync(data, loaders, options, context);
  92013. }
  92014. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  92015. throw new Error(getNoValidLoaderMessage(data));
  92016. }
  92017. return loader;
  92018. }
  92019. function selectLoaderSync(data, loaders = [], options, context) {
  92020. if (!validHTTPResponse(data)) {
  92021. return null;
  92022. }
  92023. if (loaders && !Array.isArray(loaders)) {
  92024. return normalizeLoader(loaders);
  92025. }
  92026. let candidateLoaders = [];
  92027. if (loaders) {
  92028. candidateLoaders = candidateLoaders.concat(loaders);
  92029. }
  92030. if (!(options !== null && options !== void 0 && options.ignoreRegisteredLoaders)) {
  92031. candidateLoaders.push(...getRegisteredLoaders());
  92032. }
  92033. normalizeLoaders(candidateLoaders);
  92034. const loader = selectLoaderInternal(data, candidateLoaders, options, context);
  92035. if (!loader && !(options !== null && options !== void 0 && options.nothrow)) {
  92036. throw new Error(getNoValidLoaderMessage(data));
  92037. }
  92038. return loader;
  92039. }
  92040. function selectLoaderInternal(data, loaders, options, context) {
  92041. const {
  92042. url,
  92043. type
  92044. } = getResourceUrlAndType(data);
  92045. const testUrl = url || (context === null || context === void 0 ? void 0 : context.url);
  92046. let loader = null;
  92047. if (options !== null && options !== void 0 && options.mimeType) {
  92048. loader = findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.mimeType);
  92049. }
  92050. loader = loader || findLoaderByUrl(loaders, testUrl);
  92051. loader = loader || findLoaderByMIMEType(loaders, type);
  92052. loader = loader || findLoaderByInitialBytes(loaders, data);
  92053. loader = loader || findLoaderByMIMEType(loaders, options === null || options === void 0 ? void 0 : options.fallbackMimeType);
  92054. return loader;
  92055. }
  92056. function validHTTPResponse(data) {
  92057. if (data instanceof Response) {
  92058. if (data.status === 204) {
  92059. return false;
  92060. }
  92061. }
  92062. return true;
  92063. }
  92064. function getNoValidLoaderMessage(data) {
  92065. const {
  92066. url,
  92067. type
  92068. } = getResourceUrlAndType(data);
  92069. let message = 'No valid loader found (';
  92070. message += url ? "".concat(filename(url), ", ") : 'no url provided, ';
  92071. message += "MIME type: ".concat(type ? "\"".concat(type, "\"") : 'not provided', ", ");
  92072. const firstCharacters = data ? getFirstCharacters(data) : '';
  92073. message += firstCharacters ? " first bytes: \"".concat(firstCharacters, "\"") : 'first bytes: not available';
  92074. message += ')';
  92075. return message;
  92076. }
  92077. function normalizeLoaders(loaders) {
  92078. for (const loader of loaders) {
  92079. normalizeLoader(loader);
  92080. }
  92081. }
  92082. function findLoaderByUrl(loaders, url) {
  92083. const match = url && EXT_PATTERN.exec(url);
  92084. const extension = match && match[1];
  92085. return extension ? findLoaderByExtension(loaders, extension) : null;
  92086. }
  92087. function findLoaderByExtension(loaders, extension) {
  92088. extension = extension.toLowerCase();
  92089. for (const loader of loaders) {
  92090. for (const loaderExtension of loader.extensions) {
  92091. if (loaderExtension.toLowerCase() === extension) {
  92092. return loader;
  92093. }
  92094. }
  92095. }
  92096. return null;
  92097. }
  92098. function findLoaderByMIMEType(loaders, mimeType) {
  92099. for (const loader of loaders) {
  92100. if (loader.mimeTypes && loader.mimeTypes.includes(mimeType)) {
  92101. return loader;
  92102. }
  92103. if (mimeType === "application/x.".concat(loader.id)) {
  92104. return loader;
  92105. }
  92106. }
  92107. return null;
  92108. }
  92109. function findLoaderByInitialBytes(loaders, data) {
  92110. if (!data) {
  92111. return null;
  92112. }
  92113. for (const loader of loaders) {
  92114. if (typeof data === 'string') {
  92115. if (testDataAgainstText(data, loader)) {
  92116. return loader;
  92117. }
  92118. } else if (ArrayBuffer.isView(data)) {
  92119. if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
  92120. return loader;
  92121. }
  92122. } else if (data instanceof ArrayBuffer) {
  92123. const byteOffset = 0;
  92124. if (testDataAgainstBinary(data, byteOffset, loader)) {
  92125. return loader;
  92126. }
  92127. }
  92128. }
  92129. return null;
  92130. }
  92131. function testDataAgainstText(data, loader) {
  92132. if (loader.testText) {
  92133. return loader.testText(data);
  92134. }
  92135. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  92136. return tests.some(test => data.startsWith(test));
  92137. }
  92138. function testDataAgainstBinary(data, byteOffset, loader) {
  92139. const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
  92140. return tests.some(test => testBinary(data, byteOffset, loader, test));
  92141. }
  92142. function testBinary(data, byteOffset, loader, test) {
  92143. if (test instanceof ArrayBuffer) {
  92144. return compareArrayBuffers(test, data, test.byteLength);
  92145. }
  92146. switch (typeof test) {
  92147. case 'function':
  92148. return test(data, loader);
  92149. case 'string':
  92150. const magic = getMagicString$2(data, byteOffset, test.length);
  92151. return test === magic;
  92152. default:
  92153. return false;
  92154. }
  92155. }
  92156. function getFirstCharacters(data, length = 5) {
  92157. if (typeof data === 'string') {
  92158. return data.slice(0, length);
  92159. } else if (ArrayBuffer.isView(data)) {
  92160. return getMagicString$2(data.buffer, data.byteOffset, length);
  92161. } else if (data instanceof ArrayBuffer) {
  92162. const byteOffset = 0;
  92163. return getMagicString$2(data, byteOffset, length);
  92164. }
  92165. return '';
  92166. }
  92167. function getMagicString$2(arrayBuffer, byteOffset, length) {
  92168. if (arrayBuffer.byteLength < byteOffset + length) {
  92169. return '';
  92170. }
  92171. const dataView = new DataView(arrayBuffer);
  92172. let magic = '';
  92173. for (let i = 0; i < length; i++) {
  92174. magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
  92175. }
  92176. return magic;
  92177. }
  92178. const DEFAULT_CHUNK_SIZE$2 = 256 * 1024;
  92179. function* makeStringIterator(string, options) {
  92180. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE$2;
  92181. let offset = 0;
  92182. const textEncoder = new TextEncoder();
  92183. while (offset < string.length) {
  92184. const chunkLength = Math.min(string.length - offset, chunkSize);
  92185. const chunk = string.slice(offset, offset + chunkLength);
  92186. offset += chunkLength;
  92187. yield textEncoder.encode(chunk);
  92188. }
  92189. }
  92190. const DEFAULT_CHUNK_SIZE$1 = 256 * 1024;
  92191. function* makeArrayBufferIterator(arrayBuffer, options = {}) {
  92192. const {
  92193. chunkSize = DEFAULT_CHUNK_SIZE$1
  92194. } = options;
  92195. let byteOffset = 0;
  92196. while (byteOffset < arrayBuffer.byteLength) {
  92197. const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
  92198. const chunk = new ArrayBuffer(chunkByteLength);
  92199. const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
  92200. const chunkArray = new Uint8Array(chunk);
  92201. chunkArray.set(sourceArray);
  92202. byteOffset += chunkByteLength;
  92203. yield chunk;
  92204. }
  92205. }
  92206. const DEFAULT_CHUNK_SIZE = 1024 * 1024;
  92207. async function* makeBlobIterator(blob, options) {
  92208. const chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || DEFAULT_CHUNK_SIZE;
  92209. let offset = 0;
  92210. while (offset < blob.size) {
  92211. const end = offset + chunkSize;
  92212. const chunk = await blob.slice(offset, end).arrayBuffer();
  92213. offset = end;
  92214. yield chunk;
  92215. }
  92216. }
  92217. function makeStreamIterator(stream, options) {
  92218. return isBrowser$2 ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream);
  92219. }
  92220. async function* makeBrowserStreamIterator(stream, options) {
  92221. const reader = stream.getReader();
  92222. let nextBatchPromise;
  92223. try {
  92224. while (true) {
  92225. const currentBatchPromise = nextBatchPromise || reader.read();
  92226. if (options !== null && options !== void 0 && options._streamReadAhead) {
  92227. nextBatchPromise = reader.read();
  92228. }
  92229. const {
  92230. done,
  92231. value
  92232. } = await currentBatchPromise;
  92233. if (done) {
  92234. return;
  92235. }
  92236. yield toArrayBuffer(value);
  92237. }
  92238. } catch (error) {
  92239. reader.releaseLock();
  92240. }
  92241. }
  92242. async function* makeNodeStreamIterator(stream, options) {
  92243. for await (const chunk of stream) {
  92244. yield toArrayBuffer(chunk);
  92245. }
  92246. }
  92247. function makeIterator(data, options) {
  92248. if (typeof data === 'string') {
  92249. return makeStringIterator(data, options);
  92250. }
  92251. if (data instanceof ArrayBuffer) {
  92252. return makeArrayBufferIterator(data, options);
  92253. }
  92254. if (isBlob(data)) {
  92255. return makeBlobIterator(data, options);
  92256. }
  92257. if (isReadableStream(data)) {
  92258. return makeStreamIterator(data, options);
  92259. }
  92260. if (isResponse(data)) {
  92261. const response = data;
  92262. return makeStreamIterator(response.body, options);
  92263. }
  92264. throw new Error('makeIterator');
  92265. }
  92266. const ERR_DATA = 'Cannot convert supplied data type';
  92267. function getArrayBufferOrStringFromDataSync(data, loader, options) {
  92268. if (loader.text && typeof data === 'string') {
  92269. return data;
  92270. }
  92271. if (isBuffer(data)) {
  92272. data = data.buffer;
  92273. }
  92274. if (data instanceof ArrayBuffer) {
  92275. const arrayBuffer = data;
  92276. if (loader.text && !loader.binary) {
  92277. const textDecoder = new TextDecoder('utf8');
  92278. return textDecoder.decode(arrayBuffer);
  92279. }
  92280. return arrayBuffer;
  92281. }
  92282. if (ArrayBuffer.isView(data)) {
  92283. if (loader.text && !loader.binary) {
  92284. const textDecoder = new TextDecoder('utf8');
  92285. return textDecoder.decode(data);
  92286. }
  92287. let arrayBuffer = data.buffer;
  92288. const byteLength = data.byteLength || data.length;
  92289. if (data.byteOffset !== 0 || byteLength !== arrayBuffer.byteLength) {
  92290. arrayBuffer = arrayBuffer.slice(data.byteOffset, data.byteOffset + byteLength);
  92291. }
  92292. return arrayBuffer;
  92293. }
  92294. throw new Error(ERR_DATA);
  92295. }
  92296. async function getArrayBufferOrStringFromData(data, loader, options) {
  92297. const isArrayBuffer = data instanceof ArrayBuffer || ArrayBuffer.isView(data);
  92298. if (typeof data === 'string' || isArrayBuffer) {
  92299. return getArrayBufferOrStringFromDataSync(data, loader);
  92300. }
  92301. if (isBlob(data)) {
  92302. data = await makeResponse(data);
  92303. }
  92304. if (isResponse(data)) {
  92305. const response = data;
  92306. await checkResponse(response);
  92307. return loader.binary ? await response.arrayBuffer() : await response.text();
  92308. }
  92309. if (isReadableStream(data)) {
  92310. data = makeIterator(data, options);
  92311. }
  92312. if (isIterable(data) || isAsyncIterable(data)) {
  92313. return concatenateArrayBuffersAsync(data);
  92314. }
  92315. throw new Error(ERR_DATA);
  92316. }
  92317. function getLoaderContext(context, options, previousContext = null) {
  92318. if (previousContext) {
  92319. return previousContext;
  92320. }
  92321. const resolvedContext = {
  92322. fetch: getFetchFunction(options, context),
  92323. ...context
  92324. };
  92325. if (!Array.isArray(resolvedContext.loaders)) {
  92326. resolvedContext.loaders = null;
  92327. }
  92328. return resolvedContext;
  92329. }
  92330. function getLoadersFromContext(loaders, context) {
  92331. if (!context && loaders && !Array.isArray(loaders)) {
  92332. return loaders;
  92333. }
  92334. let candidateLoaders;
  92335. if (loaders) {
  92336. candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
  92337. }
  92338. if (context && context.loaders) {
  92339. const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
  92340. candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
  92341. }
  92342. return candidateLoaders && candidateLoaders.length ? candidateLoaders : null;
  92343. }
  92344. async function parse$3(data, loaders, options, context) {
  92345. assert$6(!context || typeof context === 'object');
  92346. if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
  92347. context = undefined;
  92348. options = loaders;
  92349. loaders = undefined;
  92350. }
  92351. data = await data;
  92352. options = options || {};
  92353. const {
  92354. url
  92355. } = getResourceUrlAndType(data);
  92356. const typedLoaders = loaders;
  92357. const candidateLoaders = getLoadersFromContext(typedLoaders, context);
  92358. const loader = await selectLoader(data, candidateLoaders, options);
  92359. if (!loader) {
  92360. return null;
  92361. }
  92362. options = normalizeOptions(options, loader, candidateLoaders, url);
  92363. context = getLoaderContext({
  92364. url,
  92365. parse: parse$3,
  92366. loaders: candidateLoaders
  92367. }, options, context);
  92368. return await parseWithLoader(loader, data, options, context);
  92369. }
  92370. async function parseWithLoader(loader, data, options, context) {
  92371. validateWorkerVersion(loader);
  92372. data = await getArrayBufferOrStringFromData(data, loader, options);
  92373. if (loader.parseTextSync && typeof data === 'string') {
  92374. options.dataType = 'text';
  92375. return loader.parseTextSync(data, options, context, loader);
  92376. }
  92377. if (canParseWithWorker(loader, options)) {
  92378. return await parseWithWorker(loader, data, options, context, parse$3);
  92379. }
  92380. if (loader.parseText && typeof data === 'string') {
  92381. return await loader.parseText(data, options, context, loader);
  92382. }
  92383. if (loader.parse) {
  92384. return await loader.parse(data, options, context, loader);
  92385. }
  92386. assert$6(!loader.parseSync);
  92387. throw new Error("".concat(loader.id, " loader - no parser found and worker is disabled"));
  92388. }
  92389. async function load(url, loaders, options, context) {
  92390. if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
  92391. options = loaders;
  92392. loaders = undefined;
  92393. }
  92394. const fetch = getFetchFunction(options);
  92395. let data = url;
  92396. if (typeof url === 'string') {
  92397. data = await fetch(url);
  92398. }
  92399. if (isBlob(url)) {
  92400. data = await fetch(url);
  92401. }
  92402. return await parse$3(data, loaders, options);
  92403. }
  92404. function assert$4(condition, message) {
  92405. if (!condition) {
  92406. throw new Error("math.gl assertion ".concat(message));
  92407. }
  92408. }
  92409. const RADIANS_TO_DEGREES = 1 / Math.PI * 180;
  92410. const DEGREES_TO_RADIANS = 1 / 180 * Math.PI;
  92411. const config$2 = {};
  92412. config$2.EPSILON = 1e-12;
  92413. config$2.debug = false;
  92414. config$2.precision = 4;
  92415. config$2.printTypes = false;
  92416. config$2.printDegrees = false;
  92417. config$2.printRowMajor = true;
  92418. function round(value) {
  92419. return Math.round(value / config$2.EPSILON) * config$2.EPSILON;
  92420. }
  92421. function formatValue(value, {
  92422. precision = config$2.precision || 4
  92423. } = {}) {
  92424. value = round(value);
  92425. return "".concat(parseFloat(value.toPrecision(precision)));
  92426. }
  92427. function isArray(value) {
  92428. return Array.isArray(value) || ArrayBuffer.isView(value) && !(value instanceof DataView);
  92429. }
  92430. function duplicateArray(array) {
  92431. return array.clone ? array.clone() : new Array(array.length);
  92432. }
  92433. function map$1(value, func, result) {
  92434. if (isArray(value)) {
  92435. result = result || duplicateArray(value);
  92436. for (let i = 0; i < result.length && i < value.length; ++i) {
  92437. result[i] = func(value[i], i, result);
  92438. }
  92439. return result;
  92440. }
  92441. return func(value);
  92442. }
  92443. function toRadians(degrees) {
  92444. return radians(degrees);
  92445. }
  92446. function toDegrees(radians) {
  92447. return degrees(radians);
  92448. }
  92449. function radians(degrees, result) {
  92450. return map$1(degrees, degrees => degrees * DEGREES_TO_RADIANS, result);
  92451. }
  92452. function degrees(radians, result) {
  92453. return map$1(radians, radians => radians * RADIANS_TO_DEGREES, result);
  92454. }
  92455. function clamp(value, min, max) {
  92456. return map$1(value, value => Math.max(min, Math.min(max, value)));
  92457. }
  92458. function equals$1(a, b, epsilon) {
  92459. const oldEpsilon = config$2.EPSILON;
  92460. if (epsilon) {
  92461. config$2.EPSILON = epsilon;
  92462. }
  92463. try {
  92464. if (a === b) {
  92465. return true;
  92466. }
  92467. if (isArray(a) && isArray(b)) {
  92468. if (a.length !== b.length) {
  92469. return false;
  92470. }
  92471. for (let i = 0; i < a.length; ++i) {
  92472. if (!equals$1(a[i], b[i])) {
  92473. return false;
  92474. }
  92475. }
  92476. return true;
  92477. }
  92478. if (a && a.equals) {
  92479. return a.equals(b);
  92480. }
  92481. if (b && b.equals) {
  92482. return b.equals(a);
  92483. }
  92484. if (Number.isFinite(a) && Number.isFinite(b)) {
  92485. return Math.abs(a - b) <= config$2.EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
  92486. }
  92487. return false;
  92488. } finally {
  92489. config$2.EPSILON = oldEpsilon;
  92490. }
  92491. }
  92492. function _extendableBuiltin(cls) {
  92493. function ExtendableBuiltin() {
  92494. var instance = Reflect.construct(cls, Array.from(arguments));
  92495. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  92496. return instance;
  92497. }
  92498. ExtendableBuiltin.prototype = Object.create(cls.prototype, {
  92499. constructor: {
  92500. value: cls,
  92501. enumerable: false,
  92502. writable: true,
  92503. configurable: true
  92504. }
  92505. });
  92506. if (Object.setPrototypeOf) {
  92507. Object.setPrototypeOf(ExtendableBuiltin, cls);
  92508. } else {
  92509. ExtendableBuiltin.__proto__ = cls;
  92510. }
  92511. return ExtendableBuiltin;
  92512. }
  92513. class MathArray extends _extendableBuiltin(Array) {
  92514. get ELEMENTS() {
  92515. assert$4(false);
  92516. return 0;
  92517. }
  92518. clone() {
  92519. return new this.constructor().copy(this);
  92520. }
  92521. from(arrayOrObject) {
  92522. return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);
  92523. }
  92524. fromArray(array, offset = 0) {
  92525. for (let i = 0; i < this.ELEMENTS; ++i) {
  92526. this[i] = array[i + offset];
  92527. }
  92528. return this.check();
  92529. }
  92530. to(arrayOrObject) {
  92531. if (arrayOrObject === this) {
  92532. return this;
  92533. }
  92534. return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);
  92535. }
  92536. toTarget(target) {
  92537. return target ? this.to(target) : this;
  92538. }
  92539. toArray(array = [], offset = 0) {
  92540. for (let i = 0; i < this.ELEMENTS; ++i) {
  92541. array[offset + i] = this[i];
  92542. }
  92543. return array;
  92544. }
  92545. toFloat32Array() {
  92546. return new Float32Array(this);
  92547. }
  92548. toString() {
  92549. return this.formatString(config$2);
  92550. }
  92551. formatString(opts) {
  92552. let string = '';
  92553. for (let i = 0; i < this.ELEMENTS; ++i) {
  92554. string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);
  92555. }
  92556. return "".concat(opts.printTypes ? this.constructor.name : '', "[").concat(string, "]");
  92557. }
  92558. equals(array) {
  92559. if (!array || this.length !== array.length) {
  92560. return false;
  92561. }
  92562. for (let i = 0; i < this.ELEMENTS; ++i) {
  92563. if (!equals$1(this[i], array[i])) {
  92564. return false;
  92565. }
  92566. }
  92567. return true;
  92568. }
  92569. exactEquals(array) {
  92570. if (!array || this.length !== array.length) {
  92571. return false;
  92572. }
  92573. for (let i = 0; i < this.ELEMENTS; ++i) {
  92574. if (this[i] !== array[i]) {
  92575. return false;
  92576. }
  92577. }
  92578. return true;
  92579. }
  92580. negate() {
  92581. for (let i = 0; i < this.ELEMENTS; ++i) {
  92582. this[i] = -this[i];
  92583. }
  92584. return this.check();
  92585. }
  92586. lerp(a, b, t) {
  92587. if (t === undefined) {
  92588. t = b;
  92589. b = a;
  92590. a = this;
  92591. }
  92592. for (let i = 0; i < this.ELEMENTS; ++i) {
  92593. const ai = a[i];
  92594. this[i] = ai + t * (b[i] - ai);
  92595. }
  92596. return this.check();
  92597. }
  92598. min(vector) {
  92599. for (let i = 0; i < this.ELEMENTS; ++i) {
  92600. this[i] = Math.min(vector[i], this[i]);
  92601. }
  92602. return this.check();
  92603. }
  92604. max(vector) {
  92605. for (let i = 0; i < this.ELEMENTS; ++i) {
  92606. this[i] = Math.max(vector[i], this[i]);
  92607. }
  92608. return this.check();
  92609. }
  92610. clamp(minVector, maxVector) {
  92611. for (let i = 0; i < this.ELEMENTS; ++i) {
  92612. this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);
  92613. }
  92614. return this.check();
  92615. }
  92616. add(...vectors) {
  92617. for (const vector of vectors) {
  92618. for (let i = 0; i < this.ELEMENTS; ++i) {
  92619. this[i] += vector[i];
  92620. }
  92621. }
  92622. return this.check();
  92623. }
  92624. subtract(...vectors) {
  92625. for (const vector of vectors) {
  92626. for (let i = 0; i < this.ELEMENTS; ++i) {
  92627. this[i] -= vector[i];
  92628. }
  92629. }
  92630. return this.check();
  92631. }
  92632. scale(scale) {
  92633. if (Array.isArray(scale)) {
  92634. return this.multiply(scale);
  92635. }
  92636. for (let i = 0; i < this.ELEMENTS; ++i) {
  92637. this[i] *= scale;
  92638. }
  92639. return this.check();
  92640. }
  92641. sub(a) {
  92642. return this.subtract(a);
  92643. }
  92644. setScalar(a) {
  92645. for (let i = 0; i < this.ELEMENTS; ++i) {
  92646. this[i] = a;
  92647. }
  92648. return this.check();
  92649. }
  92650. addScalar(a) {
  92651. for (let i = 0; i < this.ELEMENTS; ++i) {
  92652. this[i] += a;
  92653. }
  92654. return this.check();
  92655. }
  92656. subScalar(a) {
  92657. return this.addScalar(-a);
  92658. }
  92659. multiplyScalar(scalar) {
  92660. for (let i = 0; i < this.ELEMENTS; ++i) {
  92661. this[i] *= scalar;
  92662. }
  92663. return this.check();
  92664. }
  92665. divideScalar(a) {
  92666. return this.scale(1 / a);
  92667. }
  92668. clampScalar(min, max) {
  92669. for (let i = 0; i < this.ELEMENTS; ++i) {
  92670. this[i] = Math.min(Math.max(this[i], min), max);
  92671. }
  92672. return this.check();
  92673. }
  92674. multiplyByScalar(scalar) {
  92675. return this.scale(scalar);
  92676. }
  92677. get elements() {
  92678. return this;
  92679. }
  92680. check() {
  92681. if (config$2.debug && !this.validate()) {
  92682. throw new Error("math.gl: ".concat(this.constructor.name, " some fields set to invalid numbers'"));
  92683. }
  92684. return this;
  92685. }
  92686. validate() {
  92687. let valid = this.length === this.ELEMENTS;
  92688. for (let i = 0; i < this.ELEMENTS; ++i) {
  92689. valid = valid && Number.isFinite(this[i]);
  92690. }
  92691. return valid;
  92692. }
  92693. }
  92694. function validateVector(v, length) {
  92695. if (v.length !== length) {
  92696. return false;
  92697. }
  92698. for (let i = 0; i < v.length; ++i) {
  92699. if (!Number.isFinite(v[i])) {
  92700. return false;
  92701. }
  92702. }
  92703. return true;
  92704. }
  92705. function checkNumber(value) {
  92706. if (!Number.isFinite(value)) {
  92707. throw new Error("Invalid number ".concat(value));
  92708. }
  92709. return value;
  92710. }
  92711. function checkVector(v, length, callerName = '') {
  92712. if (config$2.debug && !validateVector(v, length)) {
  92713. throw new Error("math.gl: ".concat(callerName, " some fields set to invalid numbers'"));
  92714. }
  92715. return v;
  92716. }
  92717. const map = {};
  92718. function deprecated(method, version) {
  92719. if (!map[method]) {
  92720. map[method] = true;
  92721. console.warn("".concat(method, " has been removed in version ").concat(version, ", see upgrade guide for more information"));
  92722. }
  92723. }
  92724. class Vector extends MathArray {
  92725. get ELEMENTS() {
  92726. assert$4(false);
  92727. return 0;
  92728. }
  92729. copy(vector) {
  92730. assert$4(false);
  92731. return this;
  92732. }
  92733. get x() {
  92734. return this[0];
  92735. }
  92736. set x(value) {
  92737. this[0] = checkNumber(value);
  92738. }
  92739. get y() {
  92740. return this[1];
  92741. }
  92742. set y(value) {
  92743. this[1] = checkNumber(value);
  92744. }
  92745. len() {
  92746. return Math.sqrt(this.lengthSquared());
  92747. }
  92748. magnitude() {
  92749. return this.len();
  92750. }
  92751. lengthSquared() {
  92752. let length = 0;
  92753. for (let i = 0; i < this.ELEMENTS; ++i) {
  92754. length += this[i] * this[i];
  92755. }
  92756. return length;
  92757. }
  92758. magnitudeSquared() {
  92759. return this.lengthSquared();
  92760. }
  92761. distance(mathArray) {
  92762. return Math.sqrt(this.distanceSquared(mathArray));
  92763. }
  92764. distanceSquared(mathArray) {
  92765. let length = 0;
  92766. for (let i = 0; i < this.ELEMENTS; ++i) {
  92767. const dist = this[i] - mathArray[i];
  92768. length += dist * dist;
  92769. }
  92770. return checkNumber(length);
  92771. }
  92772. dot(mathArray) {
  92773. let product = 0;
  92774. for (let i = 0; i < this.ELEMENTS; ++i) {
  92775. product += this[i] * mathArray[i];
  92776. }
  92777. return checkNumber(product);
  92778. }
  92779. normalize() {
  92780. const length = this.magnitude();
  92781. if (length !== 0) {
  92782. for (let i = 0; i < this.ELEMENTS; ++i) {
  92783. this[i] /= length;
  92784. }
  92785. }
  92786. return this.check();
  92787. }
  92788. multiply(...vectors) {
  92789. for (const vector of vectors) {
  92790. for (let i = 0; i < this.ELEMENTS; ++i) {
  92791. this[i] *= vector[i];
  92792. }
  92793. }
  92794. return this.check();
  92795. }
  92796. divide(...vectors) {
  92797. for (const vector of vectors) {
  92798. for (let i = 0; i < this.ELEMENTS; ++i) {
  92799. this[i] /= vector[i];
  92800. }
  92801. }
  92802. return this.check();
  92803. }
  92804. lengthSq() {
  92805. return this.lengthSquared();
  92806. }
  92807. distanceTo(vector) {
  92808. return this.distance(vector);
  92809. }
  92810. distanceToSquared(vector) {
  92811. return this.distanceSquared(vector);
  92812. }
  92813. getComponent(i) {
  92814. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  92815. return checkNumber(this[i]);
  92816. }
  92817. setComponent(i, value) {
  92818. assert$4(i >= 0 && i < this.ELEMENTS, 'index is out of range');
  92819. this[i] = value;
  92820. return this.check();
  92821. }
  92822. addVectors(a, b) {
  92823. return this.copy(a).add(b);
  92824. }
  92825. subVectors(a, b) {
  92826. return this.copy(a).subtract(b);
  92827. }
  92828. multiplyVectors(a, b) {
  92829. return this.copy(a).multiply(b);
  92830. }
  92831. addScaledVector(a, b) {
  92832. return this.add(new this.constructor(a).multiplyScalar(b));
  92833. }
  92834. }
  92835. /**
  92836. * Common utilities
  92837. * @module glMatrix
  92838. */
  92839. // Configuration Constants
  92840. var EPSILON = 0.000001;
  92841. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  92842. if (!Math.hypot) Math.hypot = function () {
  92843. var y = 0,
  92844. i = arguments.length;
  92845. while (i--) {
  92846. y += arguments[i] * arguments[i];
  92847. }
  92848. return Math.sqrt(y);
  92849. };
  92850. /**
  92851. * 2 Dimensional Vector
  92852. * @module vec2
  92853. */
  92854. /**
  92855. * Creates a new, empty vec2
  92856. *
  92857. * @returns {vec2} a new 2D vector
  92858. */
  92859. function create$4() {
  92860. var out = new ARRAY_TYPE(2);
  92861. if (ARRAY_TYPE != Float32Array) {
  92862. out[0] = 0;
  92863. out[1] = 0;
  92864. }
  92865. return out;
  92866. }
  92867. /**
  92868. * Transforms the vec2 with a mat2
  92869. *
  92870. * @param {vec2} out the receiving vector
  92871. * @param {ReadonlyVec2} a the vector to transform
  92872. * @param {ReadonlyMat2} m matrix to transform with
  92873. * @returns {vec2} out
  92874. */
  92875. function transformMat2(out, a, m) {
  92876. var x = a[0],
  92877. y = a[1];
  92878. out[0] = m[0] * x + m[2] * y;
  92879. out[1] = m[1] * x + m[3] * y;
  92880. return out;
  92881. }
  92882. /**
  92883. * Transforms the vec2 with a mat2d
  92884. *
  92885. * @param {vec2} out the receiving vector
  92886. * @param {ReadonlyVec2} a the vector to transform
  92887. * @param {ReadonlyMat2d} m matrix to transform with
  92888. * @returns {vec2} out
  92889. */
  92890. function transformMat2d(out, a, m) {
  92891. var x = a[0],
  92892. y = a[1];
  92893. out[0] = m[0] * x + m[2] * y + m[4];
  92894. out[1] = m[1] * x + m[3] * y + m[5];
  92895. return out;
  92896. }
  92897. /**
  92898. * Transforms the vec2 with a mat3
  92899. * 3rd vector component is implicitly '1'
  92900. *
  92901. * @param {vec2} out the receiving vector
  92902. * @param {ReadonlyVec2} a the vector to transform
  92903. * @param {ReadonlyMat3} m matrix to transform with
  92904. * @returns {vec2} out
  92905. */
  92906. function transformMat3$1(out, a, m) {
  92907. var x = a[0],
  92908. y = a[1];
  92909. out[0] = m[0] * x + m[3] * y + m[6];
  92910. out[1] = m[1] * x + m[4] * y + m[7];
  92911. return out;
  92912. }
  92913. /**
  92914. * Transforms the vec2 with a mat4
  92915. * 3rd vector component is implicitly '0'
  92916. * 4th vector component is implicitly '1'
  92917. *
  92918. * @param {vec2} out the receiving vector
  92919. * @param {ReadonlyVec2} a the vector to transform
  92920. * @param {ReadonlyMat4} m matrix to transform with
  92921. * @returns {vec2} out
  92922. */
  92923. function transformMat4$2(out, a, m) {
  92924. var x = a[0];
  92925. var y = a[1];
  92926. out[0] = m[0] * x + m[4] * y + m[12];
  92927. out[1] = m[1] * x + m[5] * y + m[13];
  92928. return out;
  92929. }
  92930. /**
  92931. * Perform some operation over an array of vec2s.
  92932. *
  92933. * @param {Array} a the array of vectors to iterate over
  92934. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  92935. * @param {Number} offset Number of elements to skip at the beginning of the array
  92936. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  92937. * @param {Function} fn Function to call for each vector in the array
  92938. * @param {Object} [arg] additional argument to pass to fn
  92939. * @returns {Array} a
  92940. * @function
  92941. */
  92942. (function () {
  92943. var vec = create$4();
  92944. return function (a, stride, offset, count, fn, arg) {
  92945. var i, l;
  92946. if (!stride) {
  92947. stride = 2;
  92948. }
  92949. if (!offset) {
  92950. offset = 0;
  92951. }
  92952. if (count) {
  92953. l = Math.min(count * stride + offset, a.length);
  92954. } else {
  92955. l = a.length;
  92956. }
  92957. for (i = offset; i < l; i += stride) {
  92958. vec[0] = a[i];
  92959. vec[1] = a[i + 1];
  92960. fn(vec, vec, arg);
  92961. a[i] = vec[0];
  92962. a[i + 1] = vec[1];
  92963. }
  92964. return a;
  92965. };
  92966. })();
  92967. function vec2_transformMat4AsVector(out, a, m) {
  92968. const x = a[0];
  92969. const y = a[1];
  92970. const w = m[3] * x + m[7] * y || 1.0;
  92971. out[0] = (m[0] * x + m[4] * y) / w;
  92972. out[1] = (m[1] * x + m[5] * y) / w;
  92973. return out;
  92974. }
  92975. function vec3_transformMat4AsVector(out, a, m) {
  92976. const x = a[0];
  92977. const y = a[1];
  92978. const z = a[2];
  92979. const w = m[3] * x + m[7] * y + m[11] * z || 1.0;
  92980. out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;
  92981. out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;
  92982. out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;
  92983. return out;
  92984. }
  92985. function vec3_transformMat2(out, a, m) {
  92986. const x = a[0];
  92987. const y = a[1];
  92988. out[0] = m[0] * x + m[2] * y;
  92989. out[1] = m[1] * x + m[3] * y;
  92990. out[2] = a[2];
  92991. return out;
  92992. }
  92993. function vec4_transformMat3(out, a, m) {
  92994. const x = a[0];
  92995. const y = a[1];
  92996. const z = a[2];
  92997. out[0] = m[0] * x + m[3] * y + m[6] * z;
  92998. out[1] = m[1] * x + m[4] * y + m[7] * z;
  92999. out[2] = m[2] * x + m[5] * y + m[8] * z;
  93000. out[3] = a[3];
  93001. return out;
  93002. }
  93003. class Vector2$1 extends Vector {
  93004. constructor(x = 0, y = 0) {
  93005. super(2);
  93006. if (isArray(x) && arguments.length === 1) {
  93007. this.copy(x);
  93008. } else {
  93009. if (config$2.debug) {
  93010. checkNumber(x);
  93011. checkNumber(y);
  93012. }
  93013. this[0] = x;
  93014. this[1] = y;
  93015. }
  93016. }
  93017. set(x, y) {
  93018. this[0] = x;
  93019. this[1] = y;
  93020. return this.check();
  93021. }
  93022. copy(array) {
  93023. this[0] = array[0];
  93024. this[1] = array[1];
  93025. return this.check();
  93026. }
  93027. fromObject(object) {
  93028. if (config$2.debug) {
  93029. checkNumber(object.x);
  93030. checkNumber(object.y);
  93031. }
  93032. this[0] = object.x;
  93033. this[1] = object.y;
  93034. return this.check();
  93035. }
  93036. toObject(object) {
  93037. object.x = this[0];
  93038. object.y = this[1];
  93039. return object;
  93040. }
  93041. get ELEMENTS() {
  93042. return 2;
  93043. }
  93044. horizontalAngle() {
  93045. return Math.atan2(this.y, this.x);
  93046. }
  93047. verticalAngle() {
  93048. return Math.atan2(this.x, this.y);
  93049. }
  93050. transform(matrix4) {
  93051. return this.transformAsPoint(matrix4);
  93052. }
  93053. transformAsPoint(matrix4) {
  93054. transformMat4$2(this, this, matrix4);
  93055. return this.check();
  93056. }
  93057. transformAsVector(matrix4) {
  93058. vec2_transformMat4AsVector(this, this, matrix4);
  93059. return this.check();
  93060. }
  93061. transformByMatrix3(matrix3) {
  93062. transformMat3$1(this, this, matrix3);
  93063. return this.check();
  93064. }
  93065. transformByMatrix2x3(matrix2x3) {
  93066. transformMat2d(this, this, matrix2x3);
  93067. return this.check();
  93068. }
  93069. transformByMatrix2(matrix2) {
  93070. transformMat2(this, this, matrix2);
  93071. return this.check();
  93072. }
  93073. }
  93074. /**
  93075. * 3 Dimensional Vector
  93076. * @module vec3
  93077. */
  93078. /**
  93079. * Creates a new, empty vec3
  93080. *
  93081. * @returns {vec3} a new 3D vector
  93082. */
  93083. function create$3() {
  93084. var out = new ARRAY_TYPE(3);
  93085. if (ARRAY_TYPE != Float32Array) {
  93086. out[0] = 0;
  93087. out[1] = 0;
  93088. out[2] = 0;
  93089. }
  93090. return out;
  93091. }
  93092. /**
  93093. * Calculates the length of a vec3
  93094. *
  93095. * @param {ReadonlyVec3} a vector to calculate length of
  93096. * @returns {Number} length of a
  93097. */
  93098. function length$2(a) {
  93099. var x = a[0];
  93100. var y = a[1];
  93101. var z = a[2];
  93102. return Math.hypot(x, y, z);
  93103. }
  93104. /**
  93105. * Creates a new vec3 initialized with the given values
  93106. *
  93107. * @param {Number} x X component
  93108. * @param {Number} y Y component
  93109. * @param {Number} z Z component
  93110. * @returns {vec3} a new 3D vector
  93111. */
  93112. function fromValues(x, y, z) {
  93113. var out = new ARRAY_TYPE(3);
  93114. out[0] = x;
  93115. out[1] = y;
  93116. out[2] = z;
  93117. return out;
  93118. }
  93119. /**
  93120. * Normalize a vec3
  93121. *
  93122. * @param {vec3} out the receiving vector
  93123. * @param {ReadonlyVec3} a vector to normalize
  93124. * @returns {vec3} out
  93125. */
  93126. function normalize$2(out, a) {
  93127. var x = a[0];
  93128. var y = a[1];
  93129. var z = a[2];
  93130. var len = x * x + y * y + z * z;
  93131. if (len > 0) {
  93132. //TODO: evaluate use of glm_invsqrt here?
  93133. len = 1 / Math.sqrt(len);
  93134. }
  93135. out[0] = a[0] * len;
  93136. out[1] = a[1] * len;
  93137. out[2] = a[2] * len;
  93138. return out;
  93139. }
  93140. /**
  93141. * Calculates the dot product of two vec3's
  93142. *
  93143. * @param {ReadonlyVec3} a the first operand
  93144. * @param {ReadonlyVec3} b the second operand
  93145. * @returns {Number} dot product of a and b
  93146. */
  93147. function dot$2(a, b) {
  93148. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  93149. }
  93150. /**
  93151. * Computes the cross product of two vec3's
  93152. *
  93153. * @param {vec3} out the receiving vector
  93154. * @param {ReadonlyVec3} a the first operand
  93155. * @param {ReadonlyVec3} b the second operand
  93156. * @returns {vec3} out
  93157. */
  93158. function cross(out, a, b) {
  93159. var ax = a[0],
  93160. ay = a[1],
  93161. az = a[2];
  93162. var bx = b[0],
  93163. by = b[1],
  93164. bz = b[2];
  93165. out[0] = ay * bz - az * by;
  93166. out[1] = az * bx - ax * bz;
  93167. out[2] = ax * by - ay * bx;
  93168. return out;
  93169. }
  93170. /**
  93171. * Transforms the vec3 with a mat4.
  93172. * 4th vector component is implicitly '1'
  93173. *
  93174. * @param {vec3} out the receiving vector
  93175. * @param {ReadonlyVec3} a the vector to transform
  93176. * @param {ReadonlyMat4} m matrix to transform with
  93177. * @returns {vec3} out
  93178. */
  93179. function transformMat4$1(out, a, m) {
  93180. var x = a[0],
  93181. y = a[1],
  93182. z = a[2];
  93183. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  93184. w = w || 1.0;
  93185. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  93186. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  93187. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  93188. return out;
  93189. }
  93190. /**
  93191. * Transforms the vec3 with a mat3.
  93192. *
  93193. * @param {vec3} out the receiving vector
  93194. * @param {ReadonlyVec3} a the vector to transform
  93195. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  93196. * @returns {vec3} out
  93197. */
  93198. function transformMat3(out, a, m) {
  93199. var x = a[0],
  93200. y = a[1],
  93201. z = a[2];
  93202. out[0] = x * m[0] + y * m[3] + z * m[6];
  93203. out[1] = x * m[1] + y * m[4] + z * m[7];
  93204. out[2] = x * m[2] + y * m[5] + z * m[8];
  93205. return out;
  93206. }
  93207. /**
  93208. * Transforms the vec3 with a quat
  93209. * Can also be used for dual quaternions. (Multiply it with the real part)
  93210. *
  93211. * @param {vec3} out the receiving vector
  93212. * @param {ReadonlyVec3} a the vector to transform
  93213. * @param {ReadonlyQuat} q quaternion to transform with
  93214. * @returns {vec3} out
  93215. */
  93216. function transformQuat$1(out, a, q) {
  93217. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  93218. var qx = q[0],
  93219. qy = q[1],
  93220. qz = q[2],
  93221. qw = q[3];
  93222. var x = a[0],
  93223. y = a[1],
  93224. z = a[2]; // var qvec = [qx, qy, qz];
  93225. // var uv = vec3.cross([], qvec, a);
  93226. var uvx = qy * z - qz * y,
  93227. uvy = qz * x - qx * z,
  93228. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  93229. var uuvx = qy * uvz - qz * uvy,
  93230. uuvy = qz * uvx - qx * uvz,
  93231. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  93232. var w2 = qw * 2;
  93233. uvx *= w2;
  93234. uvy *= w2;
  93235. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  93236. uuvx *= 2;
  93237. uuvy *= 2;
  93238. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  93239. out[0] = x + uvx + uuvx;
  93240. out[1] = y + uvy + uuvy;
  93241. out[2] = z + uvz + uuvz;
  93242. return out;
  93243. }
  93244. /**
  93245. * Rotate a 3D vector around the x-axis
  93246. * @param {vec3} out The receiving vec3
  93247. * @param {ReadonlyVec3} a The vec3 point to rotate
  93248. * @param {ReadonlyVec3} b The origin of the rotation
  93249. * @param {Number} rad The angle of rotation in radians
  93250. * @returns {vec3} out
  93251. */
  93252. function rotateX$2(out, a, b, rad) {
  93253. var p = [],
  93254. r = []; //Translate point to the origin
  93255. p[0] = a[0] - b[0];
  93256. p[1] = a[1] - b[1];
  93257. p[2] = a[2] - b[2]; //perform rotation
  93258. r[0] = p[0];
  93259. r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);
  93260. r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position
  93261. out[0] = r[0] + b[0];
  93262. out[1] = r[1] + b[1];
  93263. out[2] = r[2] + b[2];
  93264. return out;
  93265. }
  93266. /**
  93267. * Rotate a 3D vector around the y-axis
  93268. * @param {vec3} out The receiving vec3
  93269. * @param {ReadonlyVec3} a The vec3 point to rotate
  93270. * @param {ReadonlyVec3} b The origin of the rotation
  93271. * @param {Number} rad The angle of rotation in radians
  93272. * @returns {vec3} out
  93273. */
  93274. function rotateY$2(out, a, b, rad) {
  93275. var p = [],
  93276. r = []; //Translate point to the origin
  93277. p[0] = a[0] - b[0];
  93278. p[1] = a[1] - b[1];
  93279. p[2] = a[2] - b[2]; //perform rotation
  93280. r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);
  93281. r[1] = p[1];
  93282. r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position
  93283. out[0] = r[0] + b[0];
  93284. out[1] = r[1] + b[1];
  93285. out[2] = r[2] + b[2];
  93286. return out;
  93287. }
  93288. /**
  93289. * Rotate a 3D vector around the z-axis
  93290. * @param {vec3} out The receiving vec3
  93291. * @param {ReadonlyVec3} a The vec3 point to rotate
  93292. * @param {ReadonlyVec3} b The origin of the rotation
  93293. * @param {Number} rad The angle of rotation in radians
  93294. * @returns {vec3} out
  93295. */
  93296. function rotateZ$2(out, a, b, rad) {
  93297. var p = [],
  93298. r = []; //Translate point to the origin
  93299. p[0] = a[0] - b[0];
  93300. p[1] = a[1] - b[1];
  93301. p[2] = a[2] - b[2]; //perform rotation
  93302. r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);
  93303. r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);
  93304. r[2] = p[2]; //translate to correct position
  93305. out[0] = r[0] + b[0];
  93306. out[1] = r[1] + b[1];
  93307. out[2] = r[2] + b[2];
  93308. return out;
  93309. }
  93310. /**
  93311. * Get the angle between two 3D vectors
  93312. * @param {ReadonlyVec3} a The first operand
  93313. * @param {ReadonlyVec3} b The second operand
  93314. * @returns {Number} The angle in radians
  93315. */
  93316. function angle$1(a, b) {
  93317. var ax = a[0],
  93318. ay = a[1],
  93319. az = a[2],
  93320. bx = b[0],
  93321. by = b[1],
  93322. bz = b[2],
  93323. mag1 = Math.sqrt(ax * ax + ay * ay + az * az),
  93324. mag2 = Math.sqrt(bx * bx + by * by + bz * bz),
  93325. mag = mag1 * mag2,
  93326. cosine = mag && dot$2(a, b) / mag;
  93327. return Math.acos(Math.min(Math.max(cosine, -1), 1));
  93328. }
  93329. /**
  93330. * Alias for {@link vec3.length}
  93331. * @function
  93332. */
  93333. var len = length$2;
  93334. /**
  93335. * Perform some operation over an array of vec3s.
  93336. *
  93337. * @param {Array} a the array of vectors to iterate over
  93338. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  93339. * @param {Number} offset Number of elements to skip at the beginning of the array
  93340. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  93341. * @param {Function} fn Function to call for each vector in the array
  93342. * @param {Object} [arg] additional argument to pass to fn
  93343. * @returns {Array} a
  93344. * @function
  93345. */
  93346. (function () {
  93347. var vec = create$3();
  93348. return function (a, stride, offset, count, fn, arg) {
  93349. var i, l;
  93350. if (!stride) {
  93351. stride = 3;
  93352. }
  93353. if (!offset) {
  93354. offset = 0;
  93355. }
  93356. if (count) {
  93357. l = Math.min(count * stride + offset, a.length);
  93358. } else {
  93359. l = a.length;
  93360. }
  93361. for (i = offset; i < l; i += stride) {
  93362. vec[0] = a[i];
  93363. vec[1] = a[i + 1];
  93364. vec[2] = a[i + 2];
  93365. fn(vec, vec, arg);
  93366. a[i] = vec[0];
  93367. a[i + 1] = vec[1];
  93368. a[i + 2] = vec[2];
  93369. }
  93370. return a;
  93371. };
  93372. })();
  93373. const ORIGIN = [0, 0, 0];
  93374. const constants$2 = {};
  93375. class Vector3$1 extends Vector {
  93376. static get ZERO() {
  93377. return constants$2.ZERO = constants$2.ZERO || Object.freeze(new Vector3$1(0, 0, 0, 0));
  93378. }
  93379. constructor(x = 0, y = 0, z = 0) {
  93380. super(-0, -0, -0);
  93381. if (arguments.length === 1 && isArray(x)) {
  93382. this.copy(x);
  93383. } else {
  93384. if (config$2.debug) {
  93385. checkNumber(x);
  93386. checkNumber(y);
  93387. checkNumber(z);
  93388. }
  93389. this[0] = x;
  93390. this[1] = y;
  93391. this[2] = z;
  93392. }
  93393. }
  93394. set(x, y, z) {
  93395. this[0] = x;
  93396. this[1] = y;
  93397. this[2] = z;
  93398. return this.check();
  93399. }
  93400. copy(array) {
  93401. this[0] = array[0];
  93402. this[1] = array[1];
  93403. this[2] = array[2];
  93404. return this.check();
  93405. }
  93406. fromObject(object) {
  93407. if (config$2.debug) {
  93408. checkNumber(object.x);
  93409. checkNumber(object.y);
  93410. checkNumber(object.z);
  93411. }
  93412. this[0] = object.x;
  93413. this[1] = object.y;
  93414. this[2] = object.z;
  93415. return this.check();
  93416. }
  93417. toObject(object) {
  93418. object.x = this[0];
  93419. object.y = this[1];
  93420. object.z = this[2];
  93421. return object;
  93422. }
  93423. get ELEMENTS() {
  93424. return 3;
  93425. }
  93426. get z() {
  93427. return this[2];
  93428. }
  93429. set z(value) {
  93430. this[2] = checkNumber(value);
  93431. }
  93432. angle(vector) {
  93433. return angle$1(this, vector);
  93434. }
  93435. cross(vector) {
  93436. cross(this, this, vector);
  93437. return this.check();
  93438. }
  93439. rotateX({
  93440. radians,
  93441. origin = ORIGIN
  93442. }) {
  93443. rotateX$2(this, this, origin, radians);
  93444. return this.check();
  93445. }
  93446. rotateY({
  93447. radians,
  93448. origin = ORIGIN
  93449. }) {
  93450. rotateY$2(this, this, origin, radians);
  93451. return this.check();
  93452. }
  93453. rotateZ({
  93454. radians,
  93455. origin = ORIGIN
  93456. }) {
  93457. rotateZ$2(this, this, origin, radians);
  93458. return this.check();
  93459. }
  93460. transform(matrix4) {
  93461. return this.transformAsPoint(matrix4);
  93462. }
  93463. transformAsPoint(matrix4) {
  93464. transformMat4$1(this, this, matrix4);
  93465. return this.check();
  93466. }
  93467. transformAsVector(matrix4) {
  93468. vec3_transformMat4AsVector(this, this, matrix4);
  93469. return this.check();
  93470. }
  93471. transformByMatrix3(matrix3) {
  93472. transformMat3(this, this, matrix3);
  93473. return this.check();
  93474. }
  93475. transformByMatrix2(matrix2) {
  93476. vec3_transformMat2(this, this, matrix2);
  93477. return this.check();
  93478. }
  93479. transformByQuaternion(quaternion) {
  93480. transformQuat$1(this, this, quaternion);
  93481. return this.check();
  93482. }
  93483. }
  93484. class Matrix extends MathArray {
  93485. get ELEMENTS() {
  93486. assert$4(false);
  93487. return 0;
  93488. }
  93489. get RANK() {
  93490. assert$4(false);
  93491. return 0;
  93492. }
  93493. toString() {
  93494. let string = '[';
  93495. if (config$2.printRowMajor) {
  93496. string += 'row-major:';
  93497. for (let row = 0; row < this.RANK; ++row) {
  93498. for (let col = 0; col < this.RANK; ++col) {
  93499. string += " ".concat(this[col * this.RANK + row]);
  93500. }
  93501. }
  93502. } else {
  93503. string += 'column-major:';
  93504. for (let i = 0; i < this.ELEMENTS; ++i) {
  93505. string += " ".concat(this[i]);
  93506. }
  93507. }
  93508. string += ']';
  93509. return string;
  93510. }
  93511. getElementIndex(row, col) {
  93512. return col * this.RANK + row;
  93513. }
  93514. getElement(row, col) {
  93515. return this[col * this.RANK + row];
  93516. }
  93517. setElement(row, col, value) {
  93518. this[col * this.RANK + row] = checkNumber(value);
  93519. return this;
  93520. }
  93521. getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {
  93522. const firstIndex = columnIndex * this.RANK;
  93523. for (let i = 0; i < this.RANK; ++i) {
  93524. result[i] = this[firstIndex + i];
  93525. }
  93526. return result;
  93527. }
  93528. setColumn(columnIndex, columnVector) {
  93529. const firstIndex = columnIndex * this.RANK;
  93530. for (let i = 0; i < this.RANK; ++i) {
  93531. this[firstIndex + i] = columnVector[i];
  93532. }
  93533. return this;
  93534. }
  93535. }
  93536. /**
  93537. * 3x3 Matrix
  93538. * @module mat3
  93539. */
  93540. /**
  93541. * Creates a new identity mat3
  93542. *
  93543. * @returns {mat3} a new 3x3 matrix
  93544. */
  93545. function create$2() {
  93546. var out = new ARRAY_TYPE(9);
  93547. if (ARRAY_TYPE != Float32Array) {
  93548. out[1] = 0;
  93549. out[2] = 0;
  93550. out[3] = 0;
  93551. out[5] = 0;
  93552. out[6] = 0;
  93553. out[7] = 0;
  93554. }
  93555. out[0] = 1;
  93556. out[4] = 1;
  93557. out[8] = 1;
  93558. return out;
  93559. }
  93560. /**
  93561. * Transpose the values of a mat3
  93562. *
  93563. * @param {mat3} out the receiving matrix
  93564. * @param {ReadonlyMat3} a the source matrix
  93565. * @returns {mat3} out
  93566. */
  93567. function transpose$1(out, a) {
  93568. // If we are transposing ourselves we can skip a few steps but have to cache some values
  93569. if (out === a) {
  93570. var a01 = a[1],
  93571. a02 = a[2],
  93572. a12 = a[5];
  93573. out[1] = a[3];
  93574. out[2] = a[6];
  93575. out[3] = a01;
  93576. out[5] = a[7];
  93577. out[6] = a02;
  93578. out[7] = a12;
  93579. } else {
  93580. out[0] = a[0];
  93581. out[1] = a[3];
  93582. out[2] = a[6];
  93583. out[3] = a[1];
  93584. out[4] = a[4];
  93585. out[5] = a[7];
  93586. out[6] = a[2];
  93587. out[7] = a[5];
  93588. out[8] = a[8];
  93589. }
  93590. return out;
  93591. }
  93592. /**
  93593. * Inverts a mat3
  93594. *
  93595. * @param {mat3} out the receiving matrix
  93596. * @param {ReadonlyMat3} a the source matrix
  93597. * @returns {mat3} out
  93598. */
  93599. function invert$2(out, a) {
  93600. var a00 = a[0],
  93601. a01 = a[1],
  93602. a02 = a[2];
  93603. var a10 = a[3],
  93604. a11 = a[4],
  93605. a12 = a[5];
  93606. var a20 = a[6],
  93607. a21 = a[7],
  93608. a22 = a[8];
  93609. var b01 = a22 * a11 - a12 * a21;
  93610. var b11 = -a22 * a10 + a12 * a20;
  93611. var b21 = a21 * a10 - a11 * a20; // Calculate the determinant
  93612. var det = a00 * b01 + a01 * b11 + a02 * b21;
  93613. if (!det) {
  93614. return null;
  93615. }
  93616. det = 1.0 / det;
  93617. out[0] = b01 * det;
  93618. out[1] = (-a22 * a01 + a02 * a21) * det;
  93619. out[2] = (a12 * a01 - a02 * a11) * det;
  93620. out[3] = b11 * det;
  93621. out[4] = (a22 * a00 - a02 * a20) * det;
  93622. out[5] = (-a12 * a00 + a02 * a10) * det;
  93623. out[6] = b21 * det;
  93624. out[7] = (-a21 * a00 + a01 * a20) * det;
  93625. out[8] = (a11 * a00 - a01 * a10) * det;
  93626. return out;
  93627. }
  93628. /**
  93629. * Calculates the determinant of a mat3
  93630. *
  93631. * @param {ReadonlyMat3} a the source matrix
  93632. * @returns {Number} determinant of a
  93633. */
  93634. function determinant$1(a) {
  93635. var a00 = a[0],
  93636. a01 = a[1],
  93637. a02 = a[2];
  93638. var a10 = a[3],
  93639. a11 = a[4],
  93640. a12 = a[5];
  93641. var a20 = a[6],
  93642. a21 = a[7],
  93643. a22 = a[8];
  93644. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  93645. }
  93646. /**
  93647. * Multiplies two mat3's
  93648. *
  93649. * @param {mat3} out the receiving matrix
  93650. * @param {ReadonlyMat3} a the first operand
  93651. * @param {ReadonlyMat3} b the second operand
  93652. * @returns {mat3} out
  93653. */
  93654. function multiply$2(out, a, b) {
  93655. var a00 = a[0],
  93656. a01 = a[1],
  93657. a02 = a[2];
  93658. var a10 = a[3],
  93659. a11 = a[4],
  93660. a12 = a[5];
  93661. var a20 = a[6],
  93662. a21 = a[7],
  93663. a22 = a[8];
  93664. var b00 = b[0],
  93665. b01 = b[1],
  93666. b02 = b[2];
  93667. var b10 = b[3],
  93668. b11 = b[4],
  93669. b12 = b[5];
  93670. var b20 = b[6],
  93671. b21 = b[7],
  93672. b22 = b[8];
  93673. out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  93674. out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  93675. out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  93676. out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  93677. out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  93678. out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  93679. out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  93680. out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  93681. out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  93682. return out;
  93683. }
  93684. /**
  93685. * Translate a mat3 by the given vector
  93686. *
  93687. * @param {mat3} out the receiving matrix
  93688. * @param {ReadonlyMat3} a the matrix to translate
  93689. * @param {ReadonlyVec2} v vector to translate by
  93690. * @returns {mat3} out
  93691. */
  93692. function translate$1(out, a, v) {
  93693. var a00 = a[0],
  93694. a01 = a[1],
  93695. a02 = a[2],
  93696. a10 = a[3],
  93697. a11 = a[4],
  93698. a12 = a[5],
  93699. a20 = a[6],
  93700. a21 = a[7],
  93701. a22 = a[8],
  93702. x = v[0],
  93703. y = v[1];
  93704. out[0] = a00;
  93705. out[1] = a01;
  93706. out[2] = a02;
  93707. out[3] = a10;
  93708. out[4] = a11;
  93709. out[5] = a12;
  93710. out[6] = x * a00 + y * a10 + a20;
  93711. out[7] = x * a01 + y * a11 + a21;
  93712. out[8] = x * a02 + y * a12 + a22;
  93713. return out;
  93714. }
  93715. /**
  93716. * Rotates a mat3 by the given angle
  93717. *
  93718. * @param {mat3} out the receiving matrix
  93719. * @param {ReadonlyMat3} a the matrix to rotate
  93720. * @param {Number} rad the angle to rotate the matrix by
  93721. * @returns {mat3} out
  93722. */
  93723. function rotate$1(out, a, rad) {
  93724. var a00 = a[0],
  93725. a01 = a[1],
  93726. a02 = a[2],
  93727. a10 = a[3],
  93728. a11 = a[4],
  93729. a12 = a[5],
  93730. a20 = a[6],
  93731. a21 = a[7],
  93732. a22 = a[8],
  93733. s = Math.sin(rad),
  93734. c = Math.cos(rad);
  93735. out[0] = c * a00 + s * a10;
  93736. out[1] = c * a01 + s * a11;
  93737. out[2] = c * a02 + s * a12;
  93738. out[3] = c * a10 - s * a00;
  93739. out[4] = c * a11 - s * a01;
  93740. out[5] = c * a12 - s * a02;
  93741. out[6] = a20;
  93742. out[7] = a21;
  93743. out[8] = a22;
  93744. return out;
  93745. }
  93746. /**
  93747. * Scales the mat3 by the dimensions in the given vec2
  93748. *
  93749. * @param {mat3} out the receiving matrix
  93750. * @param {ReadonlyMat3} a the matrix to rotate
  93751. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  93752. * @returns {mat3} out
  93753. **/
  93754. function scale$3(out, a, v) {
  93755. var x = v[0],
  93756. y = v[1];
  93757. out[0] = x * a[0];
  93758. out[1] = x * a[1];
  93759. out[2] = x * a[2];
  93760. out[3] = y * a[3];
  93761. out[4] = y * a[4];
  93762. out[5] = y * a[5];
  93763. out[6] = a[6];
  93764. out[7] = a[7];
  93765. out[8] = a[8];
  93766. return out;
  93767. }
  93768. /**
  93769. * Calculates a 3x3 matrix from the given quaternion
  93770. *
  93771. * @param {mat3} out mat3 receiving operation result
  93772. * @param {ReadonlyQuat} q Quaternion to create matrix from
  93773. *
  93774. * @returns {mat3} out
  93775. */
  93776. function fromQuat$1(out, q) {
  93777. var x = q[0],
  93778. y = q[1],
  93779. z = q[2],
  93780. w = q[3];
  93781. var x2 = x + x;
  93782. var y2 = y + y;
  93783. var z2 = z + z;
  93784. var xx = x * x2;
  93785. var yx = y * x2;
  93786. var yy = y * y2;
  93787. var zx = z * x2;
  93788. var zy = z * y2;
  93789. var zz = z * z2;
  93790. var wx = w * x2;
  93791. var wy = w * y2;
  93792. var wz = w * z2;
  93793. out[0] = 1 - yy - zz;
  93794. out[3] = yx - wz;
  93795. out[6] = zx + wy;
  93796. out[1] = yx + wz;
  93797. out[4] = 1 - xx - zz;
  93798. out[7] = zy - wx;
  93799. out[2] = zx - wy;
  93800. out[5] = zy + wx;
  93801. out[8] = 1 - xx - yy;
  93802. return out;
  93803. }
  93804. const IDENTITY$1 = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);
  93805. const ZERO$1 = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0]);
  93806. const INDICES$1 = Object.freeze({
  93807. COL0ROW0: 0,
  93808. COL0ROW1: 1,
  93809. COL0ROW2: 2,
  93810. COL1ROW0: 3,
  93811. COL1ROW1: 4,
  93812. COL1ROW2: 5,
  93813. COL2ROW0: 6,
  93814. COL2ROW1: 7,
  93815. COL2ROW2: 8
  93816. });
  93817. const constants$1 = {};
  93818. class Matrix3$1 extends Matrix {
  93819. static get IDENTITY() {
  93820. constants$1.IDENTITY = constants$1.IDENTITY || Object.freeze(new Matrix3$1(IDENTITY$1));
  93821. return constants$1.IDENTITY;
  93822. }
  93823. static get ZERO() {
  93824. constants$1.ZERO = constants$1.ZERO || Object.freeze(new Matrix3$1(ZERO$1));
  93825. return constants$1.ZERO;
  93826. }
  93827. get ELEMENTS() {
  93828. return 9;
  93829. }
  93830. get RANK() {
  93831. return 3;
  93832. }
  93833. get INDICES() {
  93834. return INDICES$1;
  93835. }
  93836. constructor(array) {
  93837. super(-0, -0, -0, -0, -0, -0, -0, -0, -0);
  93838. if (arguments.length === 1 && Array.isArray(array)) {
  93839. this.copy(array);
  93840. } else {
  93841. this.identity();
  93842. }
  93843. }
  93844. copy(array) {
  93845. this[0] = array[0];
  93846. this[1] = array[1];
  93847. this[2] = array[2];
  93848. this[3] = array[3];
  93849. this[4] = array[4];
  93850. this[5] = array[5];
  93851. this[6] = array[6];
  93852. this[7] = array[7];
  93853. this[8] = array[8];
  93854. return this.check();
  93855. }
  93856. set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {
  93857. this[0] = m00;
  93858. this[1] = m10;
  93859. this[2] = m20;
  93860. this[3] = m01;
  93861. this[4] = m11;
  93862. this[5] = m21;
  93863. this[6] = m02;
  93864. this[7] = m12;
  93865. this[8] = m22;
  93866. return this.check();
  93867. }
  93868. setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  93869. this[0] = m00;
  93870. this[1] = m10;
  93871. this[2] = m20;
  93872. this[3] = m01;
  93873. this[4] = m11;
  93874. this[5] = m21;
  93875. this[6] = m02;
  93876. this[7] = m12;
  93877. this[8] = m22;
  93878. return this.check();
  93879. }
  93880. determinant() {
  93881. return determinant$1(this);
  93882. }
  93883. identity() {
  93884. return this.copy(IDENTITY$1);
  93885. }
  93886. fromQuaternion(q) {
  93887. fromQuat$1(this, q);
  93888. return this.check();
  93889. }
  93890. transpose() {
  93891. transpose$1(this, this);
  93892. return this.check();
  93893. }
  93894. invert() {
  93895. invert$2(this, this);
  93896. return this.check();
  93897. }
  93898. multiplyLeft(a) {
  93899. multiply$2(this, a, this);
  93900. return this.check();
  93901. }
  93902. multiplyRight(a) {
  93903. multiply$2(this, this, a);
  93904. return this.check();
  93905. }
  93906. rotate(radians) {
  93907. rotate$1(this, this, radians);
  93908. return this.check();
  93909. }
  93910. scale(factor) {
  93911. if (Array.isArray(factor)) {
  93912. scale$3(this, this, factor);
  93913. } else {
  93914. scale$3(this, this, [factor, factor, factor]);
  93915. }
  93916. return this.check();
  93917. }
  93918. translate(vec) {
  93919. translate$1(this, this, vec);
  93920. return this.check();
  93921. }
  93922. transform(vector, result) {
  93923. switch (vector.length) {
  93924. case 2:
  93925. result = transformMat3$1(result || [-0, -0], vector, this);
  93926. break;
  93927. case 3:
  93928. result = transformMat3(result || [-0, -0, -0], vector, this);
  93929. break;
  93930. case 4:
  93931. result = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);
  93932. break;
  93933. default:
  93934. throw new Error('Illegal vector');
  93935. }
  93936. checkVector(result, vector.length);
  93937. return result;
  93938. }
  93939. transformVector(vector, result) {
  93940. deprecated('Matrix3.transformVector');
  93941. return this.transform(vector, result);
  93942. }
  93943. transformVector2(vector, result) {
  93944. deprecated('Matrix3.transformVector');
  93945. return this.transform(vector, result);
  93946. }
  93947. transformVector3(vector, result) {
  93948. deprecated('Matrix3.transformVector');
  93949. return this.transform(vector, result);
  93950. }
  93951. }
  93952. /**
  93953. * Set a mat4 to the identity matrix
  93954. *
  93955. * @param {mat4} out the receiving matrix
  93956. * @returns {mat4} out
  93957. */
  93958. function identity$1(out) {
  93959. out[0] = 1;
  93960. out[1] = 0;
  93961. out[2] = 0;
  93962. out[3] = 0;
  93963. out[4] = 0;
  93964. out[5] = 1;
  93965. out[6] = 0;
  93966. out[7] = 0;
  93967. out[8] = 0;
  93968. out[9] = 0;
  93969. out[10] = 1;
  93970. out[11] = 0;
  93971. out[12] = 0;
  93972. out[13] = 0;
  93973. out[14] = 0;
  93974. out[15] = 1;
  93975. return out;
  93976. }
  93977. /**
  93978. * Transpose the values of a mat4
  93979. *
  93980. * @param {mat4} out the receiving matrix
  93981. * @param {ReadonlyMat4} a the source matrix
  93982. * @returns {mat4} out
  93983. */
  93984. function transpose(out, a) {
  93985. // If we are transposing ourselves we can skip a few steps but have to cache some values
  93986. if (out === a) {
  93987. var a01 = a[1],
  93988. a02 = a[2],
  93989. a03 = a[3];
  93990. var a12 = a[6],
  93991. a13 = a[7];
  93992. var a23 = a[11];
  93993. out[1] = a[4];
  93994. out[2] = a[8];
  93995. out[3] = a[12];
  93996. out[4] = a01;
  93997. out[6] = a[9];
  93998. out[7] = a[13];
  93999. out[8] = a02;
  94000. out[9] = a12;
  94001. out[11] = a[14];
  94002. out[12] = a03;
  94003. out[13] = a13;
  94004. out[14] = a23;
  94005. } else {
  94006. out[0] = a[0];
  94007. out[1] = a[4];
  94008. out[2] = a[8];
  94009. out[3] = a[12];
  94010. out[4] = a[1];
  94011. out[5] = a[5];
  94012. out[6] = a[9];
  94013. out[7] = a[13];
  94014. out[8] = a[2];
  94015. out[9] = a[6];
  94016. out[10] = a[10];
  94017. out[11] = a[14];
  94018. out[12] = a[3];
  94019. out[13] = a[7];
  94020. out[14] = a[11];
  94021. out[15] = a[15];
  94022. }
  94023. return out;
  94024. }
  94025. /**
  94026. * Inverts a mat4
  94027. *
  94028. * @param {mat4} out the receiving matrix
  94029. * @param {ReadonlyMat4} a the source matrix
  94030. * @returns {mat4} out
  94031. */
  94032. function invert$1(out, a) {
  94033. var a00 = a[0],
  94034. a01 = a[1],
  94035. a02 = a[2],
  94036. a03 = a[3];
  94037. var a10 = a[4],
  94038. a11 = a[5],
  94039. a12 = a[6],
  94040. a13 = a[7];
  94041. var a20 = a[8],
  94042. a21 = a[9],
  94043. a22 = a[10],
  94044. a23 = a[11];
  94045. var a30 = a[12],
  94046. a31 = a[13],
  94047. a32 = a[14],
  94048. a33 = a[15];
  94049. var b00 = a00 * a11 - a01 * a10;
  94050. var b01 = a00 * a12 - a02 * a10;
  94051. var b02 = a00 * a13 - a03 * a10;
  94052. var b03 = a01 * a12 - a02 * a11;
  94053. var b04 = a01 * a13 - a03 * a11;
  94054. var b05 = a02 * a13 - a03 * a12;
  94055. var b06 = a20 * a31 - a21 * a30;
  94056. var b07 = a20 * a32 - a22 * a30;
  94057. var b08 = a20 * a33 - a23 * a30;
  94058. var b09 = a21 * a32 - a22 * a31;
  94059. var b10 = a21 * a33 - a23 * a31;
  94060. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  94061. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  94062. if (!det) {
  94063. return null;
  94064. }
  94065. det = 1.0 / det;
  94066. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  94067. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  94068. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  94069. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  94070. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  94071. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  94072. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  94073. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  94074. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  94075. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  94076. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  94077. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  94078. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  94079. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  94080. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  94081. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  94082. return out;
  94083. }
  94084. /**
  94085. * Calculates the determinant of a mat4
  94086. *
  94087. * @param {ReadonlyMat4} a the source matrix
  94088. * @returns {Number} determinant of a
  94089. */
  94090. function determinant(a) {
  94091. var a00 = a[0],
  94092. a01 = a[1],
  94093. a02 = a[2],
  94094. a03 = a[3];
  94095. var a10 = a[4],
  94096. a11 = a[5],
  94097. a12 = a[6],
  94098. a13 = a[7];
  94099. var a20 = a[8],
  94100. a21 = a[9],
  94101. a22 = a[10],
  94102. a23 = a[11];
  94103. var a30 = a[12],
  94104. a31 = a[13],
  94105. a32 = a[14],
  94106. a33 = a[15];
  94107. var b00 = a00 * a11 - a01 * a10;
  94108. var b01 = a00 * a12 - a02 * a10;
  94109. var b02 = a00 * a13 - a03 * a10;
  94110. var b03 = a01 * a12 - a02 * a11;
  94111. var b04 = a01 * a13 - a03 * a11;
  94112. var b05 = a02 * a13 - a03 * a12;
  94113. var b06 = a20 * a31 - a21 * a30;
  94114. var b07 = a20 * a32 - a22 * a30;
  94115. var b08 = a20 * a33 - a23 * a30;
  94116. var b09 = a21 * a32 - a22 * a31;
  94117. var b10 = a21 * a33 - a23 * a31;
  94118. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  94119. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  94120. }
  94121. /**
  94122. * Multiplies two mat4s
  94123. *
  94124. * @param {mat4} out the receiving matrix
  94125. * @param {ReadonlyMat4} a the first operand
  94126. * @param {ReadonlyMat4} b the second operand
  94127. * @returns {mat4} out
  94128. */
  94129. function multiply$1(out, a, b) {
  94130. var a00 = a[0],
  94131. a01 = a[1],
  94132. a02 = a[2],
  94133. a03 = a[3];
  94134. var a10 = a[4],
  94135. a11 = a[5],
  94136. a12 = a[6],
  94137. a13 = a[7];
  94138. var a20 = a[8],
  94139. a21 = a[9],
  94140. a22 = a[10],
  94141. a23 = a[11];
  94142. var a30 = a[12],
  94143. a31 = a[13],
  94144. a32 = a[14],
  94145. a33 = a[15]; // Cache only the current line of the second matrix
  94146. var b0 = b[0],
  94147. b1 = b[1],
  94148. b2 = b[2],
  94149. b3 = b[3];
  94150. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  94151. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  94152. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  94153. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  94154. b0 = b[4];
  94155. b1 = b[5];
  94156. b2 = b[6];
  94157. b3 = b[7];
  94158. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  94159. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  94160. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  94161. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  94162. b0 = b[8];
  94163. b1 = b[9];
  94164. b2 = b[10];
  94165. b3 = b[11];
  94166. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  94167. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  94168. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  94169. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  94170. b0 = b[12];
  94171. b1 = b[13];
  94172. b2 = b[14];
  94173. b3 = b[15];
  94174. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  94175. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  94176. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  94177. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  94178. return out;
  94179. }
  94180. /**
  94181. * Translate a mat4 by the given vector
  94182. *
  94183. * @param {mat4} out the receiving matrix
  94184. * @param {ReadonlyMat4} a the matrix to translate
  94185. * @param {ReadonlyVec3} v vector to translate by
  94186. * @returns {mat4} out
  94187. */
  94188. function translate(out, a, v) {
  94189. var x = v[0],
  94190. y = v[1],
  94191. z = v[2];
  94192. var a00, a01, a02, a03;
  94193. var a10, a11, a12, a13;
  94194. var a20, a21, a22, a23;
  94195. if (a === out) {
  94196. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  94197. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  94198. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  94199. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  94200. } else {
  94201. a00 = a[0];
  94202. a01 = a[1];
  94203. a02 = a[2];
  94204. a03 = a[3];
  94205. a10 = a[4];
  94206. a11 = a[5];
  94207. a12 = a[6];
  94208. a13 = a[7];
  94209. a20 = a[8];
  94210. a21 = a[9];
  94211. a22 = a[10];
  94212. a23 = a[11];
  94213. out[0] = a00;
  94214. out[1] = a01;
  94215. out[2] = a02;
  94216. out[3] = a03;
  94217. out[4] = a10;
  94218. out[5] = a11;
  94219. out[6] = a12;
  94220. out[7] = a13;
  94221. out[8] = a20;
  94222. out[9] = a21;
  94223. out[10] = a22;
  94224. out[11] = a23;
  94225. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  94226. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  94227. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  94228. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  94229. }
  94230. return out;
  94231. }
  94232. /**
  94233. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  94234. *
  94235. * @param {mat4} out the receiving matrix
  94236. * @param {ReadonlyMat4} a the matrix to scale
  94237. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  94238. * @returns {mat4} out
  94239. **/
  94240. function scale$2(out, a, v) {
  94241. var x = v[0],
  94242. y = v[1],
  94243. z = v[2];
  94244. out[0] = a[0] * x;
  94245. out[1] = a[1] * x;
  94246. out[2] = a[2] * x;
  94247. out[3] = a[3] * x;
  94248. out[4] = a[4] * y;
  94249. out[5] = a[5] * y;
  94250. out[6] = a[6] * y;
  94251. out[7] = a[7] * y;
  94252. out[8] = a[8] * z;
  94253. out[9] = a[9] * z;
  94254. out[10] = a[10] * z;
  94255. out[11] = a[11] * z;
  94256. out[12] = a[12];
  94257. out[13] = a[13];
  94258. out[14] = a[14];
  94259. out[15] = a[15];
  94260. return out;
  94261. }
  94262. /**
  94263. * Rotates a mat4 by the given angle around the given axis
  94264. *
  94265. * @param {mat4} out the receiving matrix
  94266. * @param {ReadonlyMat4} a the matrix to rotate
  94267. * @param {Number} rad the angle to rotate the matrix by
  94268. * @param {ReadonlyVec3} axis the axis to rotate around
  94269. * @returns {mat4} out
  94270. */
  94271. function rotate(out, a, rad, axis) {
  94272. var x = axis[0],
  94273. y = axis[1],
  94274. z = axis[2];
  94275. var len = Math.hypot(x, y, z);
  94276. var s, c, t;
  94277. var a00, a01, a02, a03;
  94278. var a10, a11, a12, a13;
  94279. var a20, a21, a22, a23;
  94280. var b00, b01, b02;
  94281. var b10, b11, b12;
  94282. var b20, b21, b22;
  94283. if (len < EPSILON) {
  94284. return null;
  94285. }
  94286. len = 1 / len;
  94287. x *= len;
  94288. y *= len;
  94289. z *= len;
  94290. s = Math.sin(rad);
  94291. c = Math.cos(rad);
  94292. t = 1 - c;
  94293. a00 = a[0];
  94294. a01 = a[1];
  94295. a02 = a[2];
  94296. a03 = a[3];
  94297. a10 = a[4];
  94298. a11 = a[5];
  94299. a12 = a[6];
  94300. a13 = a[7];
  94301. a20 = a[8];
  94302. a21 = a[9];
  94303. a22 = a[10];
  94304. a23 = a[11]; // Construct the elements of the rotation matrix
  94305. b00 = x * x * t + c;
  94306. b01 = y * x * t + z * s;
  94307. b02 = z * x * t - y * s;
  94308. b10 = x * y * t - z * s;
  94309. b11 = y * y * t + c;
  94310. b12 = z * y * t + x * s;
  94311. b20 = x * z * t + y * s;
  94312. b21 = y * z * t - x * s;
  94313. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  94314. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  94315. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  94316. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  94317. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  94318. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  94319. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  94320. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  94321. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  94322. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  94323. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  94324. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  94325. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  94326. if (a !== out) {
  94327. // If the source and destination differ, copy the unchanged last row
  94328. out[12] = a[12];
  94329. out[13] = a[13];
  94330. out[14] = a[14];
  94331. out[15] = a[15];
  94332. }
  94333. return out;
  94334. }
  94335. /**
  94336. * Rotates a matrix by the given angle around the X axis
  94337. *
  94338. * @param {mat4} out the receiving matrix
  94339. * @param {ReadonlyMat4} a the matrix to rotate
  94340. * @param {Number} rad the angle to rotate the matrix by
  94341. * @returns {mat4} out
  94342. */
  94343. function rotateX$1(out, a, rad) {
  94344. var s = Math.sin(rad);
  94345. var c = Math.cos(rad);
  94346. var a10 = a[4];
  94347. var a11 = a[5];
  94348. var a12 = a[6];
  94349. var a13 = a[7];
  94350. var a20 = a[8];
  94351. var a21 = a[9];
  94352. var a22 = a[10];
  94353. var a23 = a[11];
  94354. if (a !== out) {
  94355. // If the source and destination differ, copy the unchanged rows
  94356. out[0] = a[0];
  94357. out[1] = a[1];
  94358. out[2] = a[2];
  94359. out[3] = a[3];
  94360. out[12] = a[12];
  94361. out[13] = a[13];
  94362. out[14] = a[14];
  94363. out[15] = a[15];
  94364. } // Perform axis-specific matrix multiplication
  94365. out[4] = a10 * c + a20 * s;
  94366. out[5] = a11 * c + a21 * s;
  94367. out[6] = a12 * c + a22 * s;
  94368. out[7] = a13 * c + a23 * s;
  94369. out[8] = a20 * c - a10 * s;
  94370. out[9] = a21 * c - a11 * s;
  94371. out[10] = a22 * c - a12 * s;
  94372. out[11] = a23 * c - a13 * s;
  94373. return out;
  94374. }
  94375. /**
  94376. * Rotates a matrix by the given angle around the Y axis
  94377. *
  94378. * @param {mat4} out the receiving matrix
  94379. * @param {ReadonlyMat4} a the matrix to rotate
  94380. * @param {Number} rad the angle to rotate the matrix by
  94381. * @returns {mat4} out
  94382. */
  94383. function rotateY$1(out, a, rad) {
  94384. var s = Math.sin(rad);
  94385. var c = Math.cos(rad);
  94386. var a00 = a[0];
  94387. var a01 = a[1];
  94388. var a02 = a[2];
  94389. var a03 = a[3];
  94390. var a20 = a[8];
  94391. var a21 = a[9];
  94392. var a22 = a[10];
  94393. var a23 = a[11];
  94394. if (a !== out) {
  94395. // If the source and destination differ, copy the unchanged rows
  94396. out[4] = a[4];
  94397. out[5] = a[5];
  94398. out[6] = a[6];
  94399. out[7] = a[7];
  94400. out[12] = a[12];
  94401. out[13] = a[13];
  94402. out[14] = a[14];
  94403. out[15] = a[15];
  94404. } // Perform axis-specific matrix multiplication
  94405. out[0] = a00 * c - a20 * s;
  94406. out[1] = a01 * c - a21 * s;
  94407. out[2] = a02 * c - a22 * s;
  94408. out[3] = a03 * c - a23 * s;
  94409. out[8] = a00 * s + a20 * c;
  94410. out[9] = a01 * s + a21 * c;
  94411. out[10] = a02 * s + a22 * c;
  94412. out[11] = a03 * s + a23 * c;
  94413. return out;
  94414. }
  94415. /**
  94416. * Rotates a matrix by the given angle around the Z axis
  94417. *
  94418. * @param {mat4} out the receiving matrix
  94419. * @param {ReadonlyMat4} a the matrix to rotate
  94420. * @param {Number} rad the angle to rotate the matrix by
  94421. * @returns {mat4} out
  94422. */
  94423. function rotateZ$1(out, a, rad) {
  94424. var s = Math.sin(rad);
  94425. var c = Math.cos(rad);
  94426. var a00 = a[0];
  94427. var a01 = a[1];
  94428. var a02 = a[2];
  94429. var a03 = a[3];
  94430. var a10 = a[4];
  94431. var a11 = a[5];
  94432. var a12 = a[6];
  94433. var a13 = a[7];
  94434. if (a !== out) {
  94435. // If the source and destination differ, copy the unchanged last row
  94436. out[8] = a[8];
  94437. out[9] = a[9];
  94438. out[10] = a[10];
  94439. out[11] = a[11];
  94440. out[12] = a[12];
  94441. out[13] = a[13];
  94442. out[14] = a[14];
  94443. out[15] = a[15];
  94444. } // Perform axis-specific matrix multiplication
  94445. out[0] = a00 * c + a10 * s;
  94446. out[1] = a01 * c + a11 * s;
  94447. out[2] = a02 * c + a12 * s;
  94448. out[3] = a03 * c + a13 * s;
  94449. out[4] = a10 * c - a00 * s;
  94450. out[5] = a11 * c - a01 * s;
  94451. out[6] = a12 * c - a02 * s;
  94452. out[7] = a13 * c - a03 * s;
  94453. return out;
  94454. }
  94455. /**
  94456. * Returns the scaling factor component of a transformation
  94457. * matrix. If a matrix is built with fromRotationTranslationScale
  94458. * with a normalized Quaternion paramter, the returned vector will be
  94459. * the same as the scaling vector
  94460. * originally supplied.
  94461. * @param {vec3} out Vector to receive scaling factor component
  94462. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  94463. * @return {vec3} out
  94464. */
  94465. function getScaling(out, mat) {
  94466. var m11 = mat[0];
  94467. var m12 = mat[1];
  94468. var m13 = mat[2];
  94469. var m21 = mat[4];
  94470. var m22 = mat[5];
  94471. var m23 = mat[6];
  94472. var m31 = mat[8];
  94473. var m32 = mat[9];
  94474. var m33 = mat[10];
  94475. out[0] = Math.hypot(m11, m12, m13);
  94476. out[1] = Math.hypot(m21, m22, m23);
  94477. out[2] = Math.hypot(m31, m32, m33);
  94478. return out;
  94479. }
  94480. /**
  94481. * Calculates a 4x4 matrix from the given quaternion
  94482. *
  94483. * @param {mat4} out mat4 receiving operation result
  94484. * @param {ReadonlyQuat} q Quaternion to create matrix from
  94485. *
  94486. * @returns {mat4} out
  94487. */
  94488. function fromQuat(out, q) {
  94489. var x = q[0],
  94490. y = q[1],
  94491. z = q[2],
  94492. w = q[3];
  94493. var x2 = x + x;
  94494. var y2 = y + y;
  94495. var z2 = z + z;
  94496. var xx = x * x2;
  94497. var yx = y * x2;
  94498. var yy = y * y2;
  94499. var zx = z * x2;
  94500. var zy = z * y2;
  94501. var zz = z * z2;
  94502. var wx = w * x2;
  94503. var wy = w * y2;
  94504. var wz = w * z2;
  94505. out[0] = 1 - yy - zz;
  94506. out[1] = yx + wz;
  94507. out[2] = zx - wy;
  94508. out[3] = 0;
  94509. out[4] = yx - wz;
  94510. out[5] = 1 - xx - zz;
  94511. out[6] = zy + wx;
  94512. out[7] = 0;
  94513. out[8] = zx + wy;
  94514. out[9] = zy - wx;
  94515. out[10] = 1 - xx - yy;
  94516. out[11] = 0;
  94517. out[12] = 0;
  94518. out[13] = 0;
  94519. out[14] = 0;
  94520. out[15] = 1;
  94521. return out;
  94522. }
  94523. /**
  94524. * Generates a frustum matrix with the given bounds
  94525. *
  94526. * @param {mat4} out mat4 frustum matrix will be written into
  94527. * @param {Number} left Left bound of the frustum
  94528. * @param {Number} right Right bound of the frustum
  94529. * @param {Number} bottom Bottom bound of the frustum
  94530. * @param {Number} top Top bound of the frustum
  94531. * @param {Number} near Near bound of the frustum
  94532. * @param {Number} far Far bound of the frustum
  94533. * @returns {mat4} out
  94534. */
  94535. function frustum(out, left, right, bottom, top, near, far) {
  94536. var rl = 1 / (right - left);
  94537. var tb = 1 / (top - bottom);
  94538. var nf = 1 / (near - far);
  94539. out[0] = near * 2 * rl;
  94540. out[1] = 0;
  94541. out[2] = 0;
  94542. out[3] = 0;
  94543. out[4] = 0;
  94544. out[5] = near * 2 * tb;
  94545. out[6] = 0;
  94546. out[7] = 0;
  94547. out[8] = (right + left) * rl;
  94548. out[9] = (top + bottom) * tb;
  94549. out[10] = (far + near) * nf;
  94550. out[11] = -1;
  94551. out[12] = 0;
  94552. out[13] = 0;
  94553. out[14] = far * near * 2 * nf;
  94554. out[15] = 0;
  94555. return out;
  94556. }
  94557. /**
  94558. * Generates a perspective projection matrix with the given bounds.
  94559. * Passing null/undefined/no value for far will generate infinite projection matrix.
  94560. *
  94561. * @param {mat4} out mat4 frustum matrix will be written into
  94562. * @param {number} fovy Vertical field of view in radians
  94563. * @param {number} aspect Aspect ratio. typically viewport width/height
  94564. * @param {number} near Near bound of the frustum
  94565. * @param {number} far Far bound of the frustum, can be null or Infinity
  94566. * @returns {mat4} out
  94567. */
  94568. function perspective(out, fovy, aspect, near, far) {
  94569. var f = 1.0 / Math.tan(fovy / 2),
  94570. nf;
  94571. out[0] = f / aspect;
  94572. out[1] = 0;
  94573. out[2] = 0;
  94574. out[3] = 0;
  94575. out[4] = 0;
  94576. out[5] = f;
  94577. out[6] = 0;
  94578. out[7] = 0;
  94579. out[8] = 0;
  94580. out[9] = 0;
  94581. out[11] = -1;
  94582. out[12] = 0;
  94583. out[13] = 0;
  94584. out[15] = 0;
  94585. if (far != null && far !== Infinity) {
  94586. nf = 1 / (near - far);
  94587. out[10] = (far + near) * nf;
  94588. out[14] = 2 * far * near * nf;
  94589. } else {
  94590. out[10] = -1;
  94591. out[14] = -2 * near;
  94592. }
  94593. return out;
  94594. }
  94595. /**
  94596. * Generates a orthogonal projection matrix with the given bounds
  94597. *
  94598. * @param {mat4} out mat4 frustum matrix will be written into
  94599. * @param {number} left Left bound of the frustum
  94600. * @param {number} right Right bound of the frustum
  94601. * @param {number} bottom Bottom bound of the frustum
  94602. * @param {number} top Top bound of the frustum
  94603. * @param {number} near Near bound of the frustum
  94604. * @param {number} far Far bound of the frustum
  94605. * @returns {mat4} out
  94606. */
  94607. function ortho(out, left, right, bottom, top, near, far) {
  94608. var lr = 1 / (left - right);
  94609. var bt = 1 / (bottom - top);
  94610. var nf = 1 / (near - far);
  94611. out[0] = -2 * lr;
  94612. out[1] = 0;
  94613. out[2] = 0;
  94614. out[3] = 0;
  94615. out[4] = 0;
  94616. out[5] = -2 * bt;
  94617. out[6] = 0;
  94618. out[7] = 0;
  94619. out[8] = 0;
  94620. out[9] = 0;
  94621. out[10] = 2 * nf;
  94622. out[11] = 0;
  94623. out[12] = (left + right) * lr;
  94624. out[13] = (top + bottom) * bt;
  94625. out[14] = (far + near) * nf;
  94626. out[15] = 1;
  94627. return out;
  94628. }
  94629. /**
  94630. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  94631. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  94632. *
  94633. * @param {mat4} out mat4 frustum matrix will be written into
  94634. * @param {ReadonlyVec3} eye Position of the viewer
  94635. * @param {ReadonlyVec3} center Point the viewer is looking at
  94636. * @param {ReadonlyVec3} up vec3 pointing up
  94637. * @returns {mat4} out
  94638. */
  94639. function lookAt(out, eye, center, up) {
  94640. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  94641. var eyex = eye[0];
  94642. var eyey = eye[1];
  94643. var eyez = eye[2];
  94644. var upx = up[0];
  94645. var upy = up[1];
  94646. var upz = up[2];
  94647. var centerx = center[0];
  94648. var centery = center[1];
  94649. var centerz = center[2];
  94650. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  94651. return identity$1(out);
  94652. }
  94653. z0 = eyex - centerx;
  94654. z1 = eyey - centery;
  94655. z2 = eyez - centerz;
  94656. len = 1 / Math.hypot(z0, z1, z2);
  94657. z0 *= len;
  94658. z1 *= len;
  94659. z2 *= len;
  94660. x0 = upy * z2 - upz * z1;
  94661. x1 = upz * z0 - upx * z2;
  94662. x2 = upx * z1 - upy * z0;
  94663. len = Math.hypot(x0, x1, x2);
  94664. if (!len) {
  94665. x0 = 0;
  94666. x1 = 0;
  94667. x2 = 0;
  94668. } else {
  94669. len = 1 / len;
  94670. x0 *= len;
  94671. x1 *= len;
  94672. x2 *= len;
  94673. }
  94674. y0 = z1 * x2 - z2 * x1;
  94675. y1 = z2 * x0 - z0 * x2;
  94676. y2 = z0 * x1 - z1 * x0;
  94677. len = Math.hypot(y0, y1, y2);
  94678. if (!len) {
  94679. y0 = 0;
  94680. y1 = 0;
  94681. y2 = 0;
  94682. } else {
  94683. len = 1 / len;
  94684. y0 *= len;
  94685. y1 *= len;
  94686. y2 *= len;
  94687. }
  94688. out[0] = x0;
  94689. out[1] = y0;
  94690. out[2] = z0;
  94691. out[3] = 0;
  94692. out[4] = x1;
  94693. out[5] = y1;
  94694. out[6] = z1;
  94695. out[7] = 0;
  94696. out[8] = x2;
  94697. out[9] = y2;
  94698. out[10] = z2;
  94699. out[11] = 0;
  94700. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  94701. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  94702. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  94703. out[15] = 1;
  94704. return out;
  94705. }
  94706. /**
  94707. * 4 Dimensional Vector
  94708. * @module vec4
  94709. */
  94710. /**
  94711. * Creates a new, empty vec4
  94712. *
  94713. * @returns {vec4} a new 4D vector
  94714. */
  94715. function create$1() {
  94716. var out = new ARRAY_TYPE(4);
  94717. if (ARRAY_TYPE != Float32Array) {
  94718. out[0] = 0;
  94719. out[1] = 0;
  94720. out[2] = 0;
  94721. out[3] = 0;
  94722. }
  94723. return out;
  94724. }
  94725. /**
  94726. * Adds two vec4's
  94727. *
  94728. * @param {vec4} out the receiving vector
  94729. * @param {ReadonlyVec4} a the first operand
  94730. * @param {ReadonlyVec4} b the second operand
  94731. * @returns {vec4} out
  94732. */
  94733. function add$1(out, a, b) {
  94734. out[0] = a[0] + b[0];
  94735. out[1] = a[1] + b[1];
  94736. out[2] = a[2] + b[2];
  94737. out[3] = a[3] + b[3];
  94738. return out;
  94739. }
  94740. /**
  94741. * Scales a vec4 by a scalar number
  94742. *
  94743. * @param {vec4} out the receiving vector
  94744. * @param {ReadonlyVec4} a the vector to scale
  94745. * @param {Number} b amount to scale the vector by
  94746. * @returns {vec4} out
  94747. */
  94748. function scale$1(out, a, b) {
  94749. out[0] = a[0] * b;
  94750. out[1] = a[1] * b;
  94751. out[2] = a[2] * b;
  94752. out[3] = a[3] * b;
  94753. return out;
  94754. }
  94755. /**
  94756. * Calculates the length of a vec4
  94757. *
  94758. * @param {ReadonlyVec4} a vector to calculate length of
  94759. * @returns {Number} length of a
  94760. */
  94761. function length$1(a) {
  94762. var x = a[0];
  94763. var y = a[1];
  94764. var z = a[2];
  94765. var w = a[3];
  94766. return Math.hypot(x, y, z, w);
  94767. }
  94768. /**
  94769. * Calculates the squared length of a vec4
  94770. *
  94771. * @param {ReadonlyVec4} a vector to calculate squared length of
  94772. * @returns {Number} squared length of a
  94773. */
  94774. function squaredLength$1(a) {
  94775. var x = a[0];
  94776. var y = a[1];
  94777. var z = a[2];
  94778. var w = a[3];
  94779. return x * x + y * y + z * z + w * w;
  94780. }
  94781. /**
  94782. * Normalize a vec4
  94783. *
  94784. * @param {vec4} out the receiving vector
  94785. * @param {ReadonlyVec4} a vector to normalize
  94786. * @returns {vec4} out
  94787. */
  94788. function normalize$1(out, a) {
  94789. var x = a[0];
  94790. var y = a[1];
  94791. var z = a[2];
  94792. var w = a[3];
  94793. var len = x * x + y * y + z * z + w * w;
  94794. if (len > 0) {
  94795. len = 1 / Math.sqrt(len);
  94796. }
  94797. out[0] = x * len;
  94798. out[1] = y * len;
  94799. out[2] = z * len;
  94800. out[3] = w * len;
  94801. return out;
  94802. }
  94803. /**
  94804. * Calculates the dot product of two vec4's
  94805. *
  94806. * @param {ReadonlyVec4} a the first operand
  94807. * @param {ReadonlyVec4} b the second operand
  94808. * @returns {Number} dot product of a and b
  94809. */
  94810. function dot$1(a, b) {
  94811. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  94812. }
  94813. /**
  94814. * Performs a linear interpolation between two vec4's
  94815. *
  94816. * @param {vec4} out the receiving vector
  94817. * @param {ReadonlyVec4} a the first operand
  94818. * @param {ReadonlyVec4} b the second operand
  94819. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  94820. * @returns {vec4} out
  94821. */
  94822. function lerp$1(out, a, b, t) {
  94823. var ax = a[0];
  94824. var ay = a[1];
  94825. var az = a[2];
  94826. var aw = a[3];
  94827. out[0] = ax + t * (b[0] - ax);
  94828. out[1] = ay + t * (b[1] - ay);
  94829. out[2] = az + t * (b[2] - az);
  94830. out[3] = aw + t * (b[3] - aw);
  94831. return out;
  94832. }
  94833. /**
  94834. * Transforms the vec4 with a mat4.
  94835. *
  94836. * @param {vec4} out the receiving vector
  94837. * @param {ReadonlyVec4} a the vector to transform
  94838. * @param {ReadonlyMat4} m matrix to transform with
  94839. * @returns {vec4} out
  94840. */
  94841. function transformMat4(out, a, m) {
  94842. var x = a[0],
  94843. y = a[1],
  94844. z = a[2],
  94845. w = a[3];
  94846. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  94847. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  94848. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  94849. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  94850. return out;
  94851. }
  94852. /**
  94853. * Transforms the vec4 with a quat
  94854. *
  94855. * @param {vec4} out the receiving vector
  94856. * @param {ReadonlyVec4} a the vector to transform
  94857. * @param {ReadonlyQuat} q quaternion to transform with
  94858. * @returns {vec4} out
  94859. */
  94860. function transformQuat(out, a, q) {
  94861. var x = a[0],
  94862. y = a[1],
  94863. z = a[2];
  94864. var qx = q[0],
  94865. qy = q[1],
  94866. qz = q[2],
  94867. qw = q[3]; // calculate quat * vec
  94868. var ix = qw * x + qy * z - qz * y;
  94869. var iy = qw * y + qz * x - qx * z;
  94870. var iz = qw * z + qx * y - qy * x;
  94871. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  94872. out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  94873. out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  94874. out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  94875. out[3] = a[3];
  94876. return out;
  94877. }
  94878. /**
  94879. * Perform some operation over an array of vec4s.
  94880. *
  94881. * @param {Array} a the array of vectors to iterate over
  94882. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  94883. * @param {Number} offset Number of elements to skip at the beginning of the array
  94884. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  94885. * @param {Function} fn Function to call for each vector in the array
  94886. * @param {Object} [arg] additional argument to pass to fn
  94887. * @returns {Array} a
  94888. * @function
  94889. */
  94890. (function () {
  94891. var vec = create$1();
  94892. return function (a, stride, offset, count, fn, arg) {
  94893. var i, l;
  94894. if (!stride) {
  94895. stride = 4;
  94896. }
  94897. if (!offset) {
  94898. offset = 0;
  94899. }
  94900. if (count) {
  94901. l = Math.min(count * stride + offset, a.length);
  94902. } else {
  94903. l = a.length;
  94904. }
  94905. for (i = offset; i < l; i += stride) {
  94906. vec[0] = a[i];
  94907. vec[1] = a[i + 1];
  94908. vec[2] = a[i + 2];
  94909. vec[3] = a[i + 3];
  94910. fn(vec, vec, arg);
  94911. a[i] = vec[0];
  94912. a[i + 1] = vec[1];
  94913. a[i + 2] = vec[2];
  94914. a[i + 3] = vec[3];
  94915. }
  94916. return a;
  94917. };
  94918. })();
  94919. const IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
  94920. const ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  94921. const INDICES = Object.freeze({
  94922. COL0ROW0: 0,
  94923. COL0ROW1: 1,
  94924. COL0ROW2: 2,
  94925. COL0ROW3: 3,
  94926. COL1ROW0: 4,
  94927. COL1ROW1: 5,
  94928. COL1ROW2: 6,
  94929. COL1ROW3: 7,
  94930. COL2ROW0: 8,
  94931. COL2ROW1: 9,
  94932. COL2ROW2: 10,
  94933. COL2ROW3: 11,
  94934. COL3ROW0: 12,
  94935. COL3ROW1: 13,
  94936. COL3ROW2: 14,
  94937. COL3ROW3: 15
  94938. });
  94939. const constants = {};
  94940. class Matrix4$1 extends Matrix {
  94941. static get IDENTITY() {
  94942. constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix4$1(IDENTITY));
  94943. return constants.IDENTITY;
  94944. }
  94945. static get ZERO() {
  94946. constants.ZERO = constants.ZERO || Object.freeze(new Matrix4$1(ZERO));
  94947. return constants.ZERO;
  94948. }
  94949. get INDICES() {
  94950. return INDICES;
  94951. }
  94952. get ELEMENTS() {
  94953. return 16;
  94954. }
  94955. get RANK() {
  94956. return 4;
  94957. }
  94958. constructor(array) {
  94959. super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);
  94960. if (arguments.length === 1 && Array.isArray(array)) {
  94961. this.copy(array);
  94962. } else {
  94963. this.identity();
  94964. }
  94965. }
  94966. copy(array) {
  94967. this[0] = array[0];
  94968. this[1] = array[1];
  94969. this[2] = array[2];
  94970. this[3] = array[3];
  94971. this[4] = array[4];
  94972. this[5] = array[5];
  94973. this[6] = array[6];
  94974. this[7] = array[7];
  94975. this[8] = array[8];
  94976. this[9] = array[9];
  94977. this[10] = array[10];
  94978. this[11] = array[11];
  94979. this[12] = array[12];
  94980. this[13] = array[13];
  94981. this[14] = array[14];
  94982. this[15] = array[15];
  94983. return this.check();
  94984. }
  94985. set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {
  94986. this[0] = m00;
  94987. this[1] = m10;
  94988. this[2] = m20;
  94989. this[3] = m30;
  94990. this[4] = m01;
  94991. this[5] = m11;
  94992. this[6] = m21;
  94993. this[7] = m31;
  94994. this[8] = m02;
  94995. this[9] = m12;
  94996. this[10] = m22;
  94997. this[11] = m32;
  94998. this[12] = m03;
  94999. this[13] = m13;
  95000. this[14] = m23;
  95001. this[15] = m33;
  95002. return this.check();
  95003. }
  95004. setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  95005. this[0] = m00;
  95006. this[1] = m10;
  95007. this[2] = m20;
  95008. this[3] = m30;
  95009. this[4] = m01;
  95010. this[5] = m11;
  95011. this[6] = m21;
  95012. this[7] = m31;
  95013. this[8] = m02;
  95014. this[9] = m12;
  95015. this[10] = m22;
  95016. this[11] = m32;
  95017. this[12] = m03;
  95018. this[13] = m13;
  95019. this[14] = m23;
  95020. this[15] = m33;
  95021. return this.check();
  95022. }
  95023. toRowMajor(result) {
  95024. result[0] = this[0];
  95025. result[1] = this[4];
  95026. result[2] = this[8];
  95027. result[3] = this[12];
  95028. result[4] = this[1];
  95029. result[5] = this[5];
  95030. result[6] = this[9];
  95031. result[7] = this[13];
  95032. result[8] = this[2];
  95033. result[9] = this[6];
  95034. result[10] = this[10];
  95035. result[11] = this[14];
  95036. result[12] = this[3];
  95037. result[13] = this[7];
  95038. result[14] = this[11];
  95039. result[15] = this[15];
  95040. return result;
  95041. }
  95042. identity() {
  95043. return this.copy(IDENTITY);
  95044. }
  95045. fromQuaternion(q) {
  95046. fromQuat(this, q);
  95047. return this.check();
  95048. }
  95049. frustum({
  95050. left,
  95051. right,
  95052. bottom,
  95053. top,
  95054. near,
  95055. far
  95056. }) {
  95057. if (far === Infinity) {
  95058. Matrix4$1._computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);
  95059. } else {
  95060. frustum(this, left, right, bottom, top, near, far);
  95061. }
  95062. return this.check();
  95063. }
  95064. static _computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {
  95065. const column0Row0 = 2.0 * near / (right - left);
  95066. const column1Row1 = 2.0 * near / (top - bottom);
  95067. const column2Row0 = (right + left) / (right - left);
  95068. const column2Row1 = (top + bottom) / (top - bottom);
  95069. const column2Row2 = -1.0;
  95070. const column2Row3 = -1.0;
  95071. const column3Row2 = -2.0 * near;
  95072. result[0] = column0Row0;
  95073. result[1] = 0.0;
  95074. result[2] = 0.0;
  95075. result[3] = 0.0;
  95076. result[4] = 0.0;
  95077. result[5] = column1Row1;
  95078. result[6] = 0.0;
  95079. result[7] = 0.0;
  95080. result[8] = column2Row0;
  95081. result[9] = column2Row1;
  95082. result[10] = column2Row2;
  95083. result[11] = column2Row3;
  95084. result[12] = 0.0;
  95085. result[13] = 0.0;
  95086. result[14] = column3Row2;
  95087. result[15] = 0.0;
  95088. return result;
  95089. }
  95090. lookAt(eye, center, up) {
  95091. if (arguments.length === 1) {
  95092. ({
  95093. eye,
  95094. center,
  95095. up
  95096. } = eye);
  95097. }
  95098. center = center || [0, 0, 0];
  95099. up = up || [0, 1, 0];
  95100. lookAt(this, eye, center, up);
  95101. return this.check();
  95102. }
  95103. ortho({
  95104. left,
  95105. right,
  95106. bottom,
  95107. top,
  95108. near = 0.1,
  95109. far = 500
  95110. }) {
  95111. ortho(this, left, right, bottom, top, near, far);
  95112. return this.check();
  95113. }
  95114. orthographic({
  95115. fovy = 45 * Math.PI / 180,
  95116. aspect = 1,
  95117. focalDistance = 1,
  95118. near = 0.1,
  95119. far = 500
  95120. }) {
  95121. if (fovy > Math.PI * 2) {
  95122. throw Error('radians');
  95123. }
  95124. const halfY = fovy / 2;
  95125. const top = focalDistance * Math.tan(halfY);
  95126. const right = top * aspect;
  95127. return new Matrix4$1().ortho({
  95128. left: -right,
  95129. right,
  95130. bottom: -top,
  95131. top,
  95132. near,
  95133. far
  95134. });
  95135. }
  95136. perspective({
  95137. fovy = undefined,
  95138. fov = 45 * Math.PI / 180,
  95139. aspect = 1,
  95140. near = 0.1,
  95141. far = 500
  95142. } = {}) {
  95143. fovy = fovy || fov;
  95144. if (fovy > Math.PI * 2) {
  95145. throw Error('radians');
  95146. }
  95147. perspective(this, fovy, aspect, near, far);
  95148. return this.check();
  95149. }
  95150. determinant() {
  95151. return determinant(this);
  95152. }
  95153. getScale(result = [-0, -0, -0]) {
  95154. result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
  95155. result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);
  95156. result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);
  95157. return result;
  95158. }
  95159. getTranslation(result = [-0, -0, -0]) {
  95160. result[0] = this[12];
  95161. result[1] = this[13];
  95162. result[2] = this[14];
  95163. return result;
  95164. }
  95165. getRotation(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  95166. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  95167. const inverseScale0 = 1 / scale[0];
  95168. const inverseScale1 = 1 / scale[1];
  95169. const inverseScale2 = 1 / scale[2];
  95170. result[0] = this[0] * inverseScale0;
  95171. result[1] = this[1] * inverseScale1;
  95172. result[2] = this[2] * inverseScale2;
  95173. result[3] = 0;
  95174. result[4] = this[4] * inverseScale0;
  95175. result[5] = this[5] * inverseScale1;
  95176. result[6] = this[6] * inverseScale2;
  95177. result[7] = 0;
  95178. result[8] = this[8] * inverseScale0;
  95179. result[9] = this[9] * inverseScale1;
  95180. result[10] = this[10] * inverseScale2;
  95181. result[11] = 0;
  95182. result[12] = 0;
  95183. result[13] = 0;
  95184. result[14] = 0;
  95185. result[15] = 1;
  95186. return result;
  95187. }
  95188. getRotationMatrix3(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {
  95189. const scale = this.getScale(scaleResult || [-0, -0, -0]);
  95190. const inverseScale0 = 1 / scale[0];
  95191. const inverseScale1 = 1 / scale[1];
  95192. const inverseScale2 = 1 / scale[2];
  95193. result[0] = this[0] * inverseScale0;
  95194. result[1] = this[1] * inverseScale1;
  95195. result[2] = this[2] * inverseScale2;
  95196. result[3] = this[4] * inverseScale0;
  95197. result[4] = this[5] * inverseScale1;
  95198. result[5] = this[6] * inverseScale2;
  95199. result[6] = this[8] * inverseScale0;
  95200. result[7] = this[9] * inverseScale1;
  95201. result[8] = this[10] * inverseScale2;
  95202. return result;
  95203. }
  95204. transpose() {
  95205. transpose(this, this);
  95206. return this.check();
  95207. }
  95208. invert() {
  95209. invert$1(this, this);
  95210. return this.check();
  95211. }
  95212. multiplyLeft(a) {
  95213. multiply$1(this, a, this);
  95214. return this.check();
  95215. }
  95216. multiplyRight(a) {
  95217. multiply$1(this, this, a);
  95218. return this.check();
  95219. }
  95220. rotateX(radians) {
  95221. rotateX$1(this, this, radians);
  95222. return this.check();
  95223. }
  95224. rotateY(radians) {
  95225. rotateY$1(this, this, radians);
  95226. return this.check();
  95227. }
  95228. rotateZ(radians) {
  95229. rotateZ$1(this, this, radians);
  95230. return this.check();
  95231. }
  95232. rotateXYZ([rx, ry, rz]) {
  95233. return this.rotateX(rx).rotateY(ry).rotateZ(rz);
  95234. }
  95235. rotateAxis(radians, axis) {
  95236. rotate(this, this, radians, axis);
  95237. return this.check();
  95238. }
  95239. scale(factor) {
  95240. if (Array.isArray(factor)) {
  95241. scale$2(this, this, factor);
  95242. } else {
  95243. scale$2(this, this, [factor, factor, factor]);
  95244. }
  95245. return this.check();
  95246. }
  95247. translate(vec) {
  95248. translate(this, this, vec);
  95249. return this.check();
  95250. }
  95251. transform(vector, result) {
  95252. if (vector.length === 4) {
  95253. result = transformMat4(result || [-0, -0, -0, -0], vector, this);
  95254. checkVector(result, 4);
  95255. return result;
  95256. }
  95257. return this.transformAsPoint(vector, result);
  95258. }
  95259. transformAsPoint(vector, result) {
  95260. const {
  95261. length
  95262. } = vector;
  95263. switch (length) {
  95264. case 2:
  95265. result = transformMat4$2(result || [-0, -0], vector, this);
  95266. break;
  95267. case 3:
  95268. result = transformMat4$1(result || [-0, -0, -0], vector, this);
  95269. break;
  95270. default:
  95271. throw new Error('Illegal vector');
  95272. }
  95273. checkVector(result, vector.length);
  95274. return result;
  95275. }
  95276. transformAsVector(vector, result) {
  95277. switch (vector.length) {
  95278. case 2:
  95279. result = vec2_transformMat4AsVector(result || [-0, -0], vector, this);
  95280. break;
  95281. case 3:
  95282. result = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);
  95283. break;
  95284. default:
  95285. throw new Error('Illegal vector');
  95286. }
  95287. checkVector(result, vector.length);
  95288. return result;
  95289. }
  95290. makeRotationX(radians) {
  95291. return this.identity().rotateX(radians);
  95292. }
  95293. makeTranslation(x, y, z) {
  95294. return this.identity().translate([x, y, z]);
  95295. }
  95296. transformPoint(vector, result) {
  95297. deprecated('Matrix4.transformPoint', '3.0');
  95298. return this.transformAsPoint(vector, result);
  95299. }
  95300. transformVector(vector, result) {
  95301. deprecated('Matrix4.transformVector', '3.0');
  95302. return this.transformAsPoint(vector, result);
  95303. }
  95304. transformDirection(vector, result) {
  95305. deprecated('Matrix4.transformDirection', '3.0');
  95306. return this.transformAsVector(vector, result);
  95307. }
  95308. }
  95309. /**
  95310. * Quaternion
  95311. * @module quat
  95312. */
  95313. /**
  95314. * Creates a new identity quat
  95315. *
  95316. * @returns {quat} a new quaternion
  95317. */
  95318. function create() {
  95319. var out = new ARRAY_TYPE(4);
  95320. if (ARRAY_TYPE != Float32Array) {
  95321. out[0] = 0;
  95322. out[1] = 0;
  95323. out[2] = 0;
  95324. }
  95325. out[3] = 1;
  95326. return out;
  95327. }
  95328. /**
  95329. * Set a quat to the identity quaternion
  95330. *
  95331. * @param {quat} out the receiving quaternion
  95332. * @returns {quat} out
  95333. */
  95334. function identity(out) {
  95335. out[0] = 0;
  95336. out[1] = 0;
  95337. out[2] = 0;
  95338. out[3] = 1;
  95339. return out;
  95340. }
  95341. /**
  95342. * Sets a quat from the given angle and rotation axis,
  95343. * then returns it.
  95344. *
  95345. * @param {quat} out the receiving quaternion
  95346. * @param {ReadonlyVec3} axis the axis around which to rotate
  95347. * @param {Number} rad the angle in radians
  95348. * @returns {quat} out
  95349. **/
  95350. function setAxisAngle(out, axis, rad) {
  95351. rad = rad * 0.5;
  95352. var s = Math.sin(rad);
  95353. out[0] = s * axis[0];
  95354. out[1] = s * axis[1];
  95355. out[2] = s * axis[2];
  95356. out[3] = Math.cos(rad);
  95357. return out;
  95358. }
  95359. /**
  95360. * Multiplies two quat's
  95361. *
  95362. * @param {quat} out the receiving quaternion
  95363. * @param {ReadonlyQuat} a the first operand
  95364. * @param {ReadonlyQuat} b the second operand
  95365. * @returns {quat} out
  95366. */
  95367. function multiply(out, a, b) {
  95368. var ax = a[0],
  95369. ay = a[1],
  95370. az = a[2],
  95371. aw = a[3];
  95372. var bx = b[0],
  95373. by = b[1],
  95374. bz = b[2],
  95375. bw = b[3];
  95376. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  95377. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  95378. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  95379. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  95380. return out;
  95381. }
  95382. /**
  95383. * Rotates a quaternion by the given angle about the X axis
  95384. *
  95385. * @param {quat} out quat receiving operation result
  95386. * @param {ReadonlyQuat} a quat to rotate
  95387. * @param {number} rad angle (in radians) to rotate
  95388. * @returns {quat} out
  95389. */
  95390. function rotateX(out, a, rad) {
  95391. rad *= 0.5;
  95392. var ax = a[0],
  95393. ay = a[1],
  95394. az = a[2],
  95395. aw = a[3];
  95396. var bx = Math.sin(rad),
  95397. bw = Math.cos(rad);
  95398. out[0] = ax * bw + aw * bx;
  95399. out[1] = ay * bw + az * bx;
  95400. out[2] = az * bw - ay * bx;
  95401. out[3] = aw * bw - ax * bx;
  95402. return out;
  95403. }
  95404. /**
  95405. * Rotates a quaternion by the given angle about the Y axis
  95406. *
  95407. * @param {quat} out quat receiving operation result
  95408. * @param {ReadonlyQuat} a quat to rotate
  95409. * @param {number} rad angle (in radians) to rotate
  95410. * @returns {quat} out
  95411. */
  95412. function rotateY(out, a, rad) {
  95413. rad *= 0.5;
  95414. var ax = a[0],
  95415. ay = a[1],
  95416. az = a[2],
  95417. aw = a[3];
  95418. var by = Math.sin(rad),
  95419. bw = Math.cos(rad);
  95420. out[0] = ax * bw - az * by;
  95421. out[1] = ay * bw + aw * by;
  95422. out[2] = az * bw + ax * by;
  95423. out[3] = aw * bw - ay * by;
  95424. return out;
  95425. }
  95426. /**
  95427. * Rotates a quaternion by the given angle about the Z axis
  95428. *
  95429. * @param {quat} out quat receiving operation result
  95430. * @param {ReadonlyQuat} a quat to rotate
  95431. * @param {number} rad angle (in radians) to rotate
  95432. * @returns {quat} out
  95433. */
  95434. function rotateZ(out, a, rad) {
  95435. rad *= 0.5;
  95436. var ax = a[0],
  95437. ay = a[1],
  95438. az = a[2],
  95439. aw = a[3];
  95440. var bz = Math.sin(rad),
  95441. bw = Math.cos(rad);
  95442. out[0] = ax * bw + ay * bz;
  95443. out[1] = ay * bw - ax * bz;
  95444. out[2] = az * bw + aw * bz;
  95445. out[3] = aw * bw - az * bz;
  95446. return out;
  95447. }
  95448. /**
  95449. * Calculates the W component of a quat from the X, Y, and Z components.
  95450. * Assumes that quaternion is 1 unit in length.
  95451. * Any existing W component will be ignored.
  95452. *
  95453. * @param {quat} out the receiving quaternion
  95454. * @param {ReadonlyQuat} a quat to calculate W component of
  95455. * @returns {quat} out
  95456. */
  95457. function calculateW(out, a) {
  95458. var x = a[0],
  95459. y = a[1],
  95460. z = a[2];
  95461. out[0] = x;
  95462. out[1] = y;
  95463. out[2] = z;
  95464. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  95465. return out;
  95466. }
  95467. /**
  95468. * Performs a spherical linear interpolation between two quat
  95469. *
  95470. * @param {quat} out the receiving quaternion
  95471. * @param {ReadonlyQuat} a the first operand
  95472. * @param {ReadonlyQuat} b the second operand
  95473. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  95474. * @returns {quat} out
  95475. */
  95476. function slerp(out, a, b, t) {
  95477. // benchmarks:
  95478. // http://jsperf.com/quaternion-slerp-implementations
  95479. var ax = a[0],
  95480. ay = a[1],
  95481. az = a[2],
  95482. aw = a[3];
  95483. var bx = b[0],
  95484. by = b[1],
  95485. bz = b[2],
  95486. bw = b[3];
  95487. var omega, cosom, sinom, scale0, scale1; // calc cosine
  95488. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  95489. if (cosom < 0.0) {
  95490. cosom = -cosom;
  95491. bx = -bx;
  95492. by = -by;
  95493. bz = -bz;
  95494. bw = -bw;
  95495. } // calculate coefficients
  95496. if (1.0 - cosom > EPSILON) {
  95497. // standard case (slerp)
  95498. omega = Math.acos(cosom);
  95499. sinom = Math.sin(omega);
  95500. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  95501. scale1 = Math.sin(t * omega) / sinom;
  95502. } else {
  95503. // "from" and "to" quaternions are very close
  95504. // ... so we can do a linear interpolation
  95505. scale0 = 1.0 - t;
  95506. scale1 = t;
  95507. } // calculate final values
  95508. out[0] = scale0 * ax + scale1 * bx;
  95509. out[1] = scale0 * ay + scale1 * by;
  95510. out[2] = scale0 * az + scale1 * bz;
  95511. out[3] = scale0 * aw + scale1 * bw;
  95512. return out;
  95513. }
  95514. /**
  95515. * Calculates the inverse of a quat
  95516. *
  95517. * @param {quat} out the receiving quaternion
  95518. * @param {ReadonlyQuat} a quat to calculate inverse of
  95519. * @returns {quat} out
  95520. */
  95521. function invert(out, a) {
  95522. var a0 = a[0],
  95523. a1 = a[1],
  95524. a2 = a[2],
  95525. a3 = a[3];
  95526. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  95527. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  95528. out[0] = -a0 * invDot;
  95529. out[1] = -a1 * invDot;
  95530. out[2] = -a2 * invDot;
  95531. out[3] = a3 * invDot;
  95532. return out;
  95533. }
  95534. /**
  95535. * Calculates the conjugate of a quat
  95536. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  95537. *
  95538. * @param {quat} out the receiving quaternion
  95539. * @param {ReadonlyQuat} a quat to calculate conjugate of
  95540. * @returns {quat} out
  95541. */
  95542. function conjugate(out, a) {
  95543. out[0] = -a[0];
  95544. out[1] = -a[1];
  95545. out[2] = -a[2];
  95546. out[3] = a[3];
  95547. return out;
  95548. }
  95549. /**
  95550. * Creates a quaternion from the given 3x3 rotation matrix.
  95551. *
  95552. * NOTE: The resultant quaternion is not normalized, so you should be sure
  95553. * to renormalize the quaternion yourself where necessary.
  95554. *
  95555. * @param {quat} out the receiving quaternion
  95556. * @param {ReadonlyMat3} m rotation matrix
  95557. * @returns {quat} out
  95558. * @function
  95559. */
  95560. function fromMat3(out, m) {
  95561. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  95562. // article "Quaternion Calculus and Fast Animation".
  95563. var fTrace = m[0] + m[4] + m[8];
  95564. var fRoot;
  95565. if (fTrace > 0.0) {
  95566. // |w| > 1/2, may as well choose w > 1/2
  95567. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  95568. out[3] = 0.5 * fRoot;
  95569. fRoot = 0.5 / fRoot; // 1/(4w)
  95570. out[0] = (m[5] - m[7]) * fRoot;
  95571. out[1] = (m[6] - m[2]) * fRoot;
  95572. out[2] = (m[1] - m[3]) * fRoot;
  95573. } else {
  95574. // |w| <= 1/2
  95575. var i = 0;
  95576. if (m[4] > m[0]) i = 1;
  95577. if (m[8] > m[i * 3 + i]) i = 2;
  95578. var j = (i + 1) % 3;
  95579. var k = (i + 2) % 3;
  95580. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  95581. out[i] = 0.5 * fRoot;
  95582. fRoot = 0.5 / fRoot;
  95583. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  95584. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  95585. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  95586. }
  95587. return out;
  95588. }
  95589. /**
  95590. * Adds two quat's
  95591. *
  95592. * @param {quat} out the receiving quaternion
  95593. * @param {ReadonlyQuat} a the first operand
  95594. * @param {ReadonlyQuat} b the second operand
  95595. * @returns {quat} out
  95596. * @function
  95597. */
  95598. var add = add$1;
  95599. /**
  95600. * Scales a quat by a scalar number
  95601. *
  95602. * @param {quat} out the receiving vector
  95603. * @param {ReadonlyQuat} a the vector to scale
  95604. * @param {Number} b amount to scale the vector by
  95605. * @returns {quat} out
  95606. * @function
  95607. */
  95608. var scale = scale$1;
  95609. /**
  95610. * Calculates the dot product of two quat's
  95611. *
  95612. * @param {ReadonlyQuat} a the first operand
  95613. * @param {ReadonlyQuat} b the second operand
  95614. * @returns {Number} dot product of a and b
  95615. * @function
  95616. */
  95617. var dot = dot$1;
  95618. /**
  95619. * Performs a linear interpolation between two quat's
  95620. *
  95621. * @param {quat} out the receiving quaternion
  95622. * @param {ReadonlyQuat} a the first operand
  95623. * @param {ReadonlyQuat} b the second operand
  95624. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  95625. * @returns {quat} out
  95626. * @function
  95627. */
  95628. var lerp$2 = lerp$1;
  95629. /**
  95630. * Calculates the length of a quat
  95631. *
  95632. * @param {ReadonlyQuat} a vector to calculate length of
  95633. * @returns {Number} length of a
  95634. */
  95635. var length = length$1;
  95636. /**
  95637. * Calculates the squared length of a quat
  95638. *
  95639. * @param {ReadonlyQuat} a vector to calculate squared length of
  95640. * @returns {Number} squared length of a
  95641. * @function
  95642. */
  95643. var squaredLength = squaredLength$1;
  95644. /**
  95645. * Normalize a quat
  95646. *
  95647. * @param {quat} out the receiving quaternion
  95648. * @param {ReadonlyQuat} a quaternion to normalize
  95649. * @returns {quat} out
  95650. * @function
  95651. */
  95652. var normalize = normalize$1;
  95653. /**
  95654. * Sets a quaternion to represent the shortest rotation from one
  95655. * vector to another.
  95656. *
  95657. * Both vectors are assumed to be unit length.
  95658. *
  95659. * @param {quat} out the receiving quaternion.
  95660. * @param {ReadonlyVec3} a the initial vector
  95661. * @param {ReadonlyVec3} b the destination vector
  95662. * @returns {quat} out
  95663. */
  95664. var rotationTo = function () {
  95665. var tmpvec3 = create$3();
  95666. var xUnitVec3 = fromValues(1, 0, 0);
  95667. var yUnitVec3 = fromValues(0, 1, 0);
  95668. return function (out, a, b) {
  95669. var dot = dot$2(a, b);
  95670. if (dot < -0.999999) {
  95671. cross(tmpvec3, xUnitVec3, a);
  95672. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  95673. normalize$2(tmpvec3, tmpvec3);
  95674. setAxisAngle(out, tmpvec3, Math.PI);
  95675. return out;
  95676. } else if (dot > 0.999999) {
  95677. out[0] = 0;
  95678. out[1] = 0;
  95679. out[2] = 0;
  95680. out[3] = 1;
  95681. return out;
  95682. } else {
  95683. cross(tmpvec3, a, b);
  95684. out[0] = tmpvec3[0];
  95685. out[1] = tmpvec3[1];
  95686. out[2] = tmpvec3[2];
  95687. out[3] = 1 + dot;
  95688. return normalize(out, out);
  95689. }
  95690. };
  95691. }();
  95692. /**
  95693. * Performs a spherical linear interpolation with two control points
  95694. *
  95695. * @param {quat} out the receiving quaternion
  95696. * @param {ReadonlyQuat} a the first operand
  95697. * @param {ReadonlyQuat} b the second operand
  95698. * @param {ReadonlyQuat} c the third operand
  95699. * @param {ReadonlyQuat} d the fourth operand
  95700. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  95701. * @returns {quat} out
  95702. */
  95703. (function () {
  95704. var temp1 = create();
  95705. var temp2 = create();
  95706. return function (out, a, b, c, d, t) {
  95707. slerp(temp1, a, d, t);
  95708. slerp(temp2, b, c, t);
  95709. slerp(out, temp1, temp2, 2 * t * (1 - t));
  95710. return out;
  95711. };
  95712. })();
  95713. /**
  95714. * Sets the specified quaternion with values corresponding to the given
  95715. * axes. Each axis is a vec3 and is expected to be unit length and
  95716. * perpendicular to all other specified axes.
  95717. *
  95718. * @param {ReadonlyVec3} view the vector representing the viewing direction
  95719. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  95720. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  95721. * @returns {quat} out
  95722. */
  95723. (function () {
  95724. var matr = create$2();
  95725. return function (out, view, right, up) {
  95726. matr[0] = right[0];
  95727. matr[3] = right[1];
  95728. matr[6] = right[2];
  95729. matr[1] = up[0];
  95730. matr[4] = up[1];
  95731. matr[7] = up[2];
  95732. matr[2] = -view[0];
  95733. matr[5] = -view[1];
  95734. matr[8] = -view[2];
  95735. return normalize(out, fromMat3(out, matr));
  95736. };
  95737. })();
  95738. const IDENTITY_QUATERNION = [0, 0, 0, 1];
  95739. class Quaternion$1 extends MathArray {
  95740. constructor(x = 0, y = 0, z = 0, w = 1) {
  95741. super(-0, -0, -0, -0);
  95742. if (Array.isArray(x) && arguments.length === 1) {
  95743. this.copy(x);
  95744. } else {
  95745. this.set(x, y, z, w);
  95746. }
  95747. }
  95748. copy(array) {
  95749. this[0] = array[0];
  95750. this[1] = array[1];
  95751. this[2] = array[2];
  95752. this[3] = array[3];
  95753. return this.check();
  95754. }
  95755. set(x, y, z, w) {
  95756. this[0] = x;
  95757. this[1] = y;
  95758. this[2] = z;
  95759. this[3] = w;
  95760. return this.check();
  95761. }
  95762. fromMatrix3(m) {
  95763. fromMat3(this, m);
  95764. return this.check();
  95765. }
  95766. identity() {
  95767. identity(this);
  95768. return this.check();
  95769. }
  95770. fromAxisRotation(axis, rad) {
  95771. setAxisAngle(this, axis, rad);
  95772. return this.check();
  95773. }
  95774. setAxisAngle(axis, rad) {
  95775. return this.fromAxisRotation(axis, rad);
  95776. }
  95777. get ELEMENTS() {
  95778. return 4;
  95779. }
  95780. get x() {
  95781. return this[0];
  95782. }
  95783. set x(value) {
  95784. this[0] = checkNumber(value);
  95785. }
  95786. get y() {
  95787. return this[1];
  95788. }
  95789. set y(value) {
  95790. this[1] = checkNumber(value);
  95791. }
  95792. get z() {
  95793. return this[2];
  95794. }
  95795. set z(value) {
  95796. this[2] = checkNumber(value);
  95797. }
  95798. get w() {
  95799. return this[3];
  95800. }
  95801. set w(value) {
  95802. this[3] = checkNumber(value);
  95803. }
  95804. len() {
  95805. return length(this);
  95806. }
  95807. lengthSquared() {
  95808. return squaredLength(this);
  95809. }
  95810. dot(a, b) {
  95811. if (b !== undefined) {
  95812. throw new Error('Quaternion.dot only takes one argument');
  95813. }
  95814. return dot(this, a);
  95815. }
  95816. rotationTo(vectorA, vectorB) {
  95817. rotationTo(this, vectorA, vectorB);
  95818. return this.check();
  95819. }
  95820. add(a, b) {
  95821. if (b !== undefined) {
  95822. throw new Error('Quaternion.add only takes one argument');
  95823. }
  95824. add(this, this, a);
  95825. return this.check();
  95826. }
  95827. calculateW() {
  95828. calculateW(this, this);
  95829. return this.check();
  95830. }
  95831. conjugate() {
  95832. conjugate(this, this);
  95833. return this.check();
  95834. }
  95835. invert() {
  95836. invert(this, this);
  95837. return this.check();
  95838. }
  95839. lerp(a, b, t) {
  95840. lerp$2(this, a, b, t);
  95841. return this.check();
  95842. }
  95843. multiplyRight(a, b) {
  95844. assert$4(!b);
  95845. multiply(this, this, a);
  95846. return this.check();
  95847. }
  95848. multiplyLeft(a, b) {
  95849. assert$4(!b);
  95850. multiply(this, a, this);
  95851. return this.check();
  95852. }
  95853. normalize() {
  95854. const length = this.len();
  95855. const l = length > 0 ? 1 / length : 0;
  95856. this[0] = this[0] * l;
  95857. this[1] = this[1] * l;
  95858. this[2] = this[2] * l;
  95859. this[3] = this[3] * l;
  95860. if (length === 0) {
  95861. this[3] = 1;
  95862. }
  95863. return this.check();
  95864. }
  95865. rotateX(rad) {
  95866. rotateX(this, this, rad);
  95867. return this.check();
  95868. }
  95869. rotateY(rad) {
  95870. rotateY(this, this, rad);
  95871. return this.check();
  95872. }
  95873. rotateZ(rad) {
  95874. rotateZ(this, this, rad);
  95875. return this.check();
  95876. }
  95877. scale(b) {
  95878. scale(this, this, b);
  95879. return this.check();
  95880. }
  95881. slerp(start, target, ratio) {
  95882. switch (arguments.length) {
  95883. case 1:
  95884. ({
  95885. start = IDENTITY_QUATERNION,
  95886. target,
  95887. ratio
  95888. } = arguments[0]);
  95889. break;
  95890. case 2:
  95891. [target, ratio] = arguments;
  95892. start = this;
  95893. break;
  95894. }
  95895. slerp(this, start, target, ratio);
  95896. return this.check();
  95897. }
  95898. transformVector4(vector, result = vector) {
  95899. transformQuat(result, vector, this);
  95900. return checkVector(result, 4);
  95901. }
  95902. lengthSq() {
  95903. return this.lengthSquared();
  95904. }
  95905. setFromAxisAngle(axis, rad) {
  95906. return this.setAxisAngle(axis, rad);
  95907. }
  95908. premultiply(a, b) {
  95909. return this.multiplyLeft(a, b);
  95910. }
  95911. multiply(a, b) {
  95912. return this.multiplyRight(a, b);
  95913. }
  95914. }
  95915. var _MathUtils = {
  95916. EPSILON1: 1e-1,
  95917. EPSILON2: 1e-2,
  95918. EPSILON3: 1e-3,
  95919. EPSILON4: 1e-4,
  95920. EPSILON5: 1e-5,
  95921. EPSILON6: 1e-6,
  95922. EPSILON7: 1e-7,
  95923. EPSILON8: 1e-8,
  95924. EPSILON9: 1e-9,
  95925. EPSILON10: 1e-10,
  95926. EPSILON11: 1e-11,
  95927. EPSILON12: 1e-12,
  95928. EPSILON13: 1e-13,
  95929. EPSILON14: 1e-14,
  95930. EPSILON15: 1e-15,
  95931. EPSILON16: 1e-16,
  95932. EPSILON17: 1e-17,
  95933. EPSILON18: 1e-18,
  95934. EPSILON19: 1e-19,
  95935. EPSILON20: 1e-20,
  95936. PI_OVER_TWO: Math.PI / 2,
  95937. PI_OVER_FOUR: Math.PI / 4,
  95938. PI_OVER_SIX: Math.PI / 6,
  95939. TWO_PI: Math.PI * 2
  95940. };
  95941. const WGS84_RADIUS_X$1 = 6378137.0;
  95942. const WGS84_RADIUS_Y$1 = 6378137.0;
  95943. const WGS84_RADIUS_Z$1 = 6356752.3142451793;
  95944. const noop$2 = x => x;
  95945. const scratchVector$6 = new Vector3$1();
  95946. function fromCartographic(cartographic, result, map = noop$2) {
  95947. if (isArray(cartographic)) {
  95948. result[0] = map(cartographic[0]);
  95949. result[1] = map(cartographic[1]);
  95950. result[2] = cartographic[2];
  95951. } else if ('longitude' in cartographic) {
  95952. result[0] = map(cartographic.longitude);
  95953. result[1] = map(cartographic.latitude);
  95954. result[2] = cartographic.height;
  95955. } else {
  95956. result[0] = map(cartographic.x);
  95957. result[1] = map(cartographic.y);
  95958. result[2] = cartographic.z;
  95959. }
  95960. return result;
  95961. }
  95962. function fromCartographicToRadians(cartographic, vector = scratchVector$6) {
  95963. return fromCartographic(cartographic, vector, config$2._cartographicRadians ? noop$2 : toRadians);
  95964. }
  95965. function toCartographic(vector, cartographic, map = noop$2) {
  95966. if (isArray(cartographic)) {
  95967. cartographic[0] = map(vector[0]);
  95968. cartographic[1] = map(vector[1]);
  95969. cartographic[2] = vector[2];
  95970. } else if ('longitude' in cartographic) {
  95971. cartographic.longitude = map(vector[0]);
  95972. cartographic.latitude = map(vector[1]);
  95973. cartographic.height = vector[2];
  95974. } else {
  95975. cartographic.x = map(vector[0]);
  95976. cartographic.y = map(vector[1]);
  95977. cartographic.z = vector[2];
  95978. }
  95979. return cartographic;
  95980. }
  95981. function toCartographicFromRadians(vector, cartographic) {
  95982. return toCartographic(vector, cartographic, config$2._cartographicRadians ? noop$2 : toDegrees);
  95983. }
  95984. const scratchVector$5 = new Vector3$1();
  95985. const scaleToGeodeticSurfaceIntersection = new Vector3$1();
  95986. const scaleToGeodeticSurfaceGradient = new Vector3$1();
  95987. function scaleToGeodeticSurface(cartesian, ellipsoid, result = new Vector3$1()) {
  95988. const {
  95989. oneOverRadii,
  95990. oneOverRadiiSquared,
  95991. centerToleranceSquared
  95992. } = ellipsoid;
  95993. scratchVector$5.from(cartesian);
  95994. const positionX = cartesian.x;
  95995. const positionY = cartesian.y;
  95996. const positionZ = cartesian.z;
  95997. const oneOverRadiiX = oneOverRadii.x;
  95998. const oneOverRadiiY = oneOverRadii.y;
  95999. const oneOverRadiiZ = oneOverRadii.z;
  96000. const x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  96001. const y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  96002. const z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  96003. const squaredNorm = x2 + y2 + z2;
  96004. const ratio = Math.sqrt(1.0 / squaredNorm);
  96005. if (!Number.isFinite(ratio)) {
  96006. return undefined;
  96007. }
  96008. const intersection = scaleToGeodeticSurfaceIntersection;
  96009. intersection.copy(cartesian).scale(ratio);
  96010. if (squaredNorm < centerToleranceSquared) {
  96011. return intersection.to(result);
  96012. }
  96013. const oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  96014. const oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  96015. const oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  96016. const gradient = scaleToGeodeticSurfaceGradient;
  96017. gradient.set(intersection.x * oneOverRadiiSquaredX * 2.0, intersection.y * oneOverRadiiSquaredY * 2.0, intersection.z * oneOverRadiiSquaredZ * 2.0);
  96018. let lambda = (1.0 - ratio) * cartesian.len() / (0.5 * gradient.len());
  96019. let correction = 0.0;
  96020. let xMultiplier;
  96021. let yMultiplier;
  96022. let zMultiplier;
  96023. let func;
  96024. do {
  96025. lambda -= correction;
  96026. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  96027. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  96028. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  96029. const xMultiplier2 = xMultiplier * xMultiplier;
  96030. const yMultiplier2 = yMultiplier * yMultiplier;
  96031. const zMultiplier2 = zMultiplier * zMultiplier;
  96032. const xMultiplier3 = xMultiplier2 * xMultiplier;
  96033. const yMultiplier3 = yMultiplier2 * yMultiplier;
  96034. const zMultiplier3 = zMultiplier2 * zMultiplier;
  96035. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  96036. const denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  96037. const derivative = -2.0 * denominator;
  96038. correction = func / derivative;
  96039. } while (Math.abs(func) > _MathUtils.EPSILON12);
  96040. return scratchVector$5.scale([xMultiplier, yMultiplier, zMultiplier]).to(result);
  96041. }
  96042. const EPSILON14 = 1e-14;
  96043. const scratchOrigin = new Vector3$1();
  96044. const VECTOR_PRODUCT_LOCAL_FRAME = {
  96045. up: {
  96046. south: 'east',
  96047. north: 'west',
  96048. west: 'south',
  96049. east: 'north'
  96050. },
  96051. down: {
  96052. south: 'west',
  96053. north: 'east',
  96054. west: 'north',
  96055. east: 'south'
  96056. },
  96057. south: {
  96058. up: 'west',
  96059. down: 'east',
  96060. west: 'down',
  96061. east: 'up'
  96062. },
  96063. north: {
  96064. up: 'east',
  96065. down: 'west',
  96066. west: 'up',
  96067. east: 'down'
  96068. },
  96069. west: {
  96070. up: 'north',
  96071. down: 'south',
  96072. north: 'down',
  96073. south: 'up'
  96074. },
  96075. east: {
  96076. up: 'south',
  96077. down: 'north',
  96078. north: 'up',
  96079. south: 'down'
  96080. }
  96081. };
  96082. const degeneratePositionLocalFrame = {
  96083. north: [-1, 0, 0],
  96084. east: [0, 1, 0],
  96085. up: [0, 0, 1],
  96086. south: [1, 0, 0],
  96087. west: [0, -1, 0],
  96088. down: [0, 0, -1]
  96089. };
  96090. const scratchAxisVectors = {
  96091. east: new Vector3$1(),
  96092. north: new Vector3$1(),
  96093. up: new Vector3$1(),
  96094. west: new Vector3$1(),
  96095. south: new Vector3$1(),
  96096. down: new Vector3$1()
  96097. };
  96098. const scratchVector1 = new Vector3$1();
  96099. const scratchVector2$1 = new Vector3$1();
  96100. const scratchVector3$1 = new Vector3$1();
  96101. function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, cartesianOrigin, result) {
  96102. const thirdAxisInferred = VECTOR_PRODUCT_LOCAL_FRAME[firstAxis] && VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];
  96103. assert$4(thirdAxisInferred && (!thirdAxis || thirdAxis === thirdAxisInferred));
  96104. let firstAxisVector;
  96105. let secondAxisVector;
  96106. let thirdAxisVector;
  96107. const origin = scratchOrigin.copy(cartesianOrigin);
  96108. const atPole = equals$1(origin.x, 0.0, EPSILON14) && equals$1(origin.y, 0.0, EPSILON14);
  96109. if (atPole) {
  96110. const sign = Math.sign(origin.z);
  96111. firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
  96112. if (firstAxis !== 'east' && firstAxis !== 'west') {
  96113. firstAxisVector.scale(sign);
  96114. }
  96115. secondAxisVector = scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);
  96116. if (secondAxis !== 'east' && secondAxis !== 'west') {
  96117. secondAxisVector.scale(sign);
  96118. }
  96119. thirdAxisVector = scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);
  96120. if (thirdAxis !== 'east' && thirdAxis !== 'west') {
  96121. thirdAxisVector.scale(sign);
  96122. }
  96123. } else {
  96124. const {
  96125. up,
  96126. east,
  96127. north
  96128. } = scratchAxisVectors;
  96129. east.set(-origin.y, origin.x, 0.0).normalize();
  96130. ellipsoid.geodeticSurfaceNormal(origin, up);
  96131. north.copy(up).cross(east);
  96132. const {
  96133. down,
  96134. west,
  96135. south
  96136. } = scratchAxisVectors;
  96137. down.copy(up).scale(-1);
  96138. west.copy(east).scale(-1);
  96139. south.copy(north).scale(-1);
  96140. firstAxisVector = scratchAxisVectors[firstAxis];
  96141. secondAxisVector = scratchAxisVectors[secondAxis];
  96142. thirdAxisVector = scratchAxisVectors[thirdAxis];
  96143. }
  96144. result[0] = firstAxisVector.x;
  96145. result[1] = firstAxisVector.y;
  96146. result[2] = firstAxisVector.z;
  96147. result[3] = 0.0;
  96148. result[4] = secondAxisVector.x;
  96149. result[5] = secondAxisVector.y;
  96150. result[6] = secondAxisVector.z;
  96151. result[7] = 0.0;
  96152. result[8] = thirdAxisVector.x;
  96153. result[9] = thirdAxisVector.y;
  96154. result[10] = thirdAxisVector.z;
  96155. result[11] = 0.0;
  96156. result[12] = origin.x;
  96157. result[13] = origin.y;
  96158. result[14] = origin.z;
  96159. result[15] = 1.0;
  96160. return result;
  96161. }
  96162. const scratchVector$4 = new Vector3$1();
  96163. const scratchNormal$2 = new Vector3$1();
  96164. const scratchK = new Vector3$1();
  96165. const scratchPosition$2 = new Vector3$1();
  96166. const scratchHeight = new Vector3$1();
  96167. const scratchCartesian = new Vector3$1();
  96168. let wgs84;
  96169. class Ellipsoid {
  96170. static get WGS84() {
  96171. wgs84 = wgs84 || new Ellipsoid(WGS84_RADIUS_X$1, WGS84_RADIUS_Y$1, WGS84_RADIUS_Z$1);
  96172. return wgs84;
  96173. }
  96174. constructor(x = 0.0, y = 0.0, z = 0.0) {
  96175. assert$4(x >= 0.0);
  96176. assert$4(y >= 0.0);
  96177. assert$4(z >= 0.0);
  96178. this.radii = new Vector3$1(x, y, z);
  96179. this.radiiSquared = new Vector3$1(x * x, y * y, z * z);
  96180. this.radiiToTheFourth = new Vector3$1(x * x * x * x, y * y * y * y, z * z * z * z);
  96181. 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);
  96182. 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));
  96183. this.minimumRadius = Math.min(x, y, z);
  96184. this.maximumRadius = Math.max(x, y, z);
  96185. this.centerToleranceSquared = _MathUtils.EPSILON1;
  96186. if (this.radiiSquared.z !== 0) {
  96187. this.squaredXOverSquaredZ = this.radiiSquared.x / this.radiiSquared.z;
  96188. }
  96189. Object.freeze(this);
  96190. }
  96191. equals(right) {
  96192. return this === right || Boolean(right && this.radii.equals(right.radii));
  96193. }
  96194. toString() {
  96195. return this.radii.toString();
  96196. }
  96197. cartographicToCartesian(cartographic, result = [0, 0, 0]) {
  96198. const normal = scratchNormal$2;
  96199. const k = scratchK;
  96200. const [,, height] = cartographic;
  96201. this.geodeticSurfaceNormalCartographic(cartographic, normal);
  96202. k.copy(this.radiiSquared).scale(normal);
  96203. const gamma = Math.sqrt(normal.dot(k));
  96204. k.scale(1 / gamma);
  96205. normal.scale(height);
  96206. k.add(normal);
  96207. return k.to(result);
  96208. }
  96209. cartesianToCartographic(cartesian, result = [0, 0, 0]) {
  96210. scratchCartesian.from(cartesian);
  96211. const point = this.scaleToGeodeticSurface(scratchCartesian, scratchPosition$2);
  96212. if (!point) {
  96213. return undefined;
  96214. }
  96215. const normal = this.geodeticSurfaceNormal(point, scratchNormal$2);
  96216. const h = scratchHeight;
  96217. h.copy(scratchCartesian).subtract(point);
  96218. const longitude = Math.atan2(normal.y, normal.x);
  96219. const latitude = Math.asin(normal.z);
  96220. const height = Math.sign(dot$2(h, scratchCartesian)) * length$2(h);
  96221. return toCartographicFromRadians([longitude, latitude, height], result);
  96222. }
  96223. eastNorthUpToFixedFrame(origin, result = new Matrix4$1()) {
  96224. return localFrameToFixedFrame(this, 'east', 'north', 'up', origin, result);
  96225. }
  96226. localFrameToFixedFrame(firstAxis, secondAxis, thirdAxis, origin, result = new Matrix4$1()) {
  96227. return localFrameToFixedFrame(this, firstAxis, secondAxis, thirdAxis, origin, result);
  96228. }
  96229. geocentricSurfaceNormal(cartesian, result = [0, 0, 0]) {
  96230. return scratchVector$4.from(cartesian).normalize().to(result);
  96231. }
  96232. geodeticSurfaceNormalCartographic(cartographic, result = [0, 0, 0]) {
  96233. const cartographicVectorRadians = fromCartographicToRadians(cartographic);
  96234. const longitude = cartographicVectorRadians[0];
  96235. const latitude = cartographicVectorRadians[1];
  96236. const cosLatitude = Math.cos(latitude);
  96237. scratchVector$4.set(cosLatitude * Math.cos(longitude), cosLatitude * Math.sin(longitude), Math.sin(latitude)).normalize();
  96238. return scratchVector$4.to(result);
  96239. }
  96240. geodeticSurfaceNormal(cartesian, result = [0, 0, 0]) {
  96241. return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);
  96242. }
  96243. scaleToGeodeticSurface(cartesian, result) {
  96244. return scaleToGeodeticSurface(cartesian, this, result);
  96245. }
  96246. scaleToGeocentricSurface(cartesian, result = [0, 0, 0]) {
  96247. scratchPosition$2.from(cartesian);
  96248. const positionX = scratchPosition$2.x;
  96249. const positionY = scratchPosition$2.y;
  96250. const positionZ = scratchPosition$2.z;
  96251. const oneOverRadiiSquared = this.oneOverRadiiSquared;
  96252. const beta = 1.0 / Math.sqrt(positionX * positionX * oneOverRadiiSquared.x + positionY * positionY * oneOverRadiiSquared.y + positionZ * positionZ * oneOverRadiiSquared.z);
  96253. return scratchPosition$2.multiplyScalar(beta).to(result);
  96254. }
  96255. transformPositionToScaledSpace(position, result = [0, 0, 0]) {
  96256. return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);
  96257. }
  96258. transformPositionFromScaledSpace(position, result = [0, 0, 0]) {
  96259. return scratchPosition$2.from(position).scale(this.radii).to(result);
  96260. }
  96261. getSurfaceNormalIntersectionWithZAxis(position, buffer = 0.0, result = [0, 0, 0]) {
  96262. assert$4(equals$1(this.radii.x, this.radii.y, _MathUtils.EPSILON15));
  96263. assert$4(this.radii.z > 0);
  96264. scratchPosition$2.from(position);
  96265. const z = scratchPosition$2.z * (1 - this.squaredXOverSquaredZ);
  96266. if (Math.abs(z) >= this.radii.z - buffer) {
  96267. return undefined;
  96268. }
  96269. return scratchPosition$2.set(0.0, 0.0, z).to(result);
  96270. }
  96271. }
  96272. class DoublyLinkedListNode {
  96273. constructor(item, previous, next) {
  96274. _defineProperty(this, "item", void 0);
  96275. _defineProperty(this, "previous", void 0);
  96276. _defineProperty(this, "next", void 0);
  96277. this.item = item;
  96278. this.previous = previous;
  96279. this.next = next;
  96280. }
  96281. }
  96282. class DoublyLinkedList {
  96283. constructor() {
  96284. _defineProperty(this, "head", null);
  96285. _defineProperty(this, "tail", null);
  96286. _defineProperty(this, "_length", 0);
  96287. }
  96288. get length() {
  96289. return this._length;
  96290. }
  96291. add(item) {
  96292. const node = new DoublyLinkedListNode(item, this.tail, null);
  96293. if (this.tail) {
  96294. this.tail.next = node;
  96295. this.tail = node;
  96296. } else {
  96297. this.head = node;
  96298. this.tail = node;
  96299. }
  96300. ++this._length;
  96301. return node;
  96302. }
  96303. remove(node) {
  96304. if (!node) {
  96305. return;
  96306. }
  96307. if (node.previous && node.next) {
  96308. node.previous.next = node.next;
  96309. node.next.previous = node.previous;
  96310. } else if (node.previous) {
  96311. node.previous.next = null;
  96312. this.tail = node.previous;
  96313. } else if (node.next) {
  96314. node.next.previous = null;
  96315. this.head = node.next;
  96316. } else {
  96317. this.head = null;
  96318. this.tail = null;
  96319. }
  96320. node.next = null;
  96321. node.previous = null;
  96322. --this._length;
  96323. }
  96324. splice(node, nextNode) {
  96325. if (node === nextNode) {
  96326. return;
  96327. }
  96328. this.remove(nextNode);
  96329. this._insert(node, nextNode);
  96330. }
  96331. _insert(node, nextNode) {
  96332. const oldNodeNext = node.next;
  96333. node.next = nextNode;
  96334. if (this.tail === node) {
  96335. this.tail = nextNode;
  96336. } else {
  96337. oldNodeNext.previous = nextNode;
  96338. }
  96339. nextNode.next = oldNodeNext;
  96340. nextNode.previous = node;
  96341. ++this._length;
  96342. }
  96343. }
  96344. function defined$5(x) {
  96345. return x !== undefined && x !== null;
  96346. }
  96347. class TilesetCache {
  96348. constructor() {
  96349. _defineProperty(this, "_list", void 0);
  96350. _defineProperty(this, "_sentinel", void 0);
  96351. _defineProperty(this, "_trimTiles", void 0);
  96352. this._list = new DoublyLinkedList();
  96353. this._sentinel = this._list.add('sentinel');
  96354. this._trimTiles = false;
  96355. }
  96356. reset() {
  96357. this._list.splice(this._list.tail, this._sentinel);
  96358. }
  96359. touch(tile) {
  96360. const node = tile._cacheNode;
  96361. if (defined$5(node)) {
  96362. this._list.splice(this._sentinel, node);
  96363. }
  96364. }
  96365. add(tileset, tile, addCallback) {
  96366. if (!defined$5(tile._cacheNode)) {
  96367. tile._cacheNode = this._list.add(tile);
  96368. if (addCallback) {
  96369. addCallback(tileset, tile);
  96370. }
  96371. }
  96372. }
  96373. unloadTile(tileset, tile, unloadCallback) {
  96374. const node = tile._cacheNode;
  96375. if (!defined$5(node)) {
  96376. return;
  96377. }
  96378. this._list.remove(node);
  96379. tile._cacheNode = undefined;
  96380. if (unloadCallback) {
  96381. unloadCallback(tileset, tile);
  96382. }
  96383. }
  96384. unloadTiles(tileset, unloadCallback) {
  96385. const trimTiles = this._trimTiles;
  96386. this._trimTiles = false;
  96387. const list = this._list;
  96388. const maximumMemoryUsageInBytes = (Potree.settings.tiles3DMaxMemory || tileset.maximumMemoryUsage) * 1024 * 1024;
  96389. const sentinel = this._sentinel;
  96390. let node = list.head;
  96391. /* while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  96392. const tile = node.item;
  96393. node = node.next;
  96394. this.unloadTile(tileset, tile, unloadCallback);
  96395. } */
  96396. //改
  96397. while (node !== sentinel && ( getGpuMemoryUsage() > maximumMemoryUsageInBytes || trimTiles)) {
  96398. const tile = node.item;
  96399. node = node.next;
  96400. this.unloadTile(tileset, tile, unloadCallback);
  96401. }
  96402. }
  96403. trim() {
  96404. this._trimTiles = true;
  96405. }
  96406. }
  96407. function calculateTransformProps(tileHeader, tile) {
  96408. assert$7(tileHeader);
  96409. assert$7(tile);
  96410. const {
  96411. rtcCenter,
  96412. gltfUpAxis
  96413. } = tile;
  96414. const {
  96415. computedTransform,
  96416. boundingVolume: {
  96417. center
  96418. }
  96419. } = tileHeader;
  96420. let modelMatrix = new Matrix4$1(computedTransform);
  96421. if (rtcCenter) {
  96422. modelMatrix.translate(rtcCenter);
  96423. }
  96424. switch (gltfUpAxis) {
  96425. case 'Z':
  96426. break;
  96427. case 'Y':
  96428. const rotationY = new Matrix4$1().rotateX(Math.PI / 2);
  96429. modelMatrix = modelMatrix.multiplyRight(rotationY);
  96430. break;
  96431. case 'X':
  96432. const rotationX = new Matrix4$1().rotateY(-Math.PI / 2);
  96433. modelMatrix = modelMatrix.multiplyRight(rotationX);
  96434. break;
  96435. }
  96436. if (tile.isQuantized) {
  96437. modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);
  96438. }
  96439. const cartesianOrigin = new Vector3$1(center);
  96440. tile.cartesianModelMatrix = modelMatrix;
  96441. tile.cartesianOrigin = cartesianOrigin;
  96442. const cartographicOrigin = Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin, new Vector3$1());
  96443. const fromFixedFrameMatrix = Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);
  96444. const toFixedFrameMatrix = fromFixedFrameMatrix.invert();
  96445. tile.cartographicModelMatrix = toFixedFrameMatrix.multiplyRight(modelMatrix);
  96446. tile.cartographicOrigin = cartographicOrigin;
  96447. if (!tile.coordinateSystem) {
  96448. tile.modelMatrix = tile.cartographicModelMatrix;
  96449. }
  96450. }
  96451. const INTERSECTION = Object.freeze({
  96452. OUTSIDE: -1,
  96453. INTERSECTING: 0,
  96454. INSIDE: 1
  96455. });
  96456. new Vector3$1();
  96457. new Vector3$1();
  96458. const scratchVector$3 = new Vector3$1();
  96459. const scratchVector2 = new Vector3$1();
  96460. class BoundingSphere {
  96461. constructor(center = [0, 0, 0], radius = 0.0) {
  96462. this.radius = -0;
  96463. this.center = new Vector3$1();
  96464. this.fromCenterRadius(center, radius);
  96465. }
  96466. fromCenterRadius(center, radius) {
  96467. this.center.from(center);
  96468. this.radius = radius;
  96469. return this;
  96470. }
  96471. fromCornerPoints(corner, oppositeCorner) {
  96472. oppositeCorner = scratchVector$3.from(oppositeCorner);
  96473. this.center = new Vector3$1().from(corner).add(oppositeCorner).scale(0.5);
  96474. this.radius = this.center.distance(oppositeCorner);
  96475. return this;
  96476. }
  96477. equals(right) {
  96478. return this === right || Boolean(right) && this.center.equals(right.center) && this.radius === right.radius;
  96479. }
  96480. clone() {
  96481. return new BoundingSphere(this.center, this.radius);
  96482. }
  96483. union(boundingSphere) {
  96484. const leftCenter = this.center;
  96485. const leftRadius = this.radius;
  96486. const rightCenter = boundingSphere.center;
  96487. const rightRadius = boundingSphere.radius;
  96488. const toRightCenter = scratchVector$3.copy(rightCenter).subtract(leftCenter);
  96489. const centerSeparation = toRightCenter.magnitude();
  96490. if (leftRadius >= centerSeparation + rightRadius) {
  96491. return this.clone();
  96492. }
  96493. if (rightRadius >= centerSeparation + leftRadius) {
  96494. return boundingSphere.clone();
  96495. }
  96496. const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  96497. scratchVector2.copy(toRightCenter).scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation).add(leftCenter);
  96498. this.center.copy(scratchVector2);
  96499. this.radius = halfDistanceBetweenTangentPoints;
  96500. return this;
  96501. }
  96502. expand(point) {
  96503. point = scratchVector$3.from(point);
  96504. const radius = point.subtract(this.center).magnitude();
  96505. if (radius > this.radius) {
  96506. this.radius = radius;
  96507. }
  96508. return this;
  96509. }
  96510. transform(transform) {
  96511. this.center.transform(transform);
  96512. const scale = getScaling(scratchVector$3, transform);
  96513. this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;
  96514. return this;
  96515. }
  96516. distanceSquaredTo(point) {
  96517. const d = this.distanceTo(point);
  96518. return d * d;
  96519. }
  96520. distanceTo(point) {
  96521. point = scratchVector$3.from(point);
  96522. const delta = point.subtract(this.center);
  96523. return Math.max(0, delta.len() - this.radius);
  96524. }
  96525. intersectPlane(plane) {
  96526. const center = this.center;
  96527. const radius = this.radius;
  96528. const normal = plane.normal;
  96529. const distanceToPlane = normal.dot(center) + plane.distance;
  96530. if (distanceToPlane < -radius) {
  96531. return INTERSECTION.OUTSIDE;
  96532. }
  96533. if (distanceToPlane < radius) {
  96534. return INTERSECTION.INTERSECTING;
  96535. }
  96536. return INTERSECTION.INSIDE;
  96537. }
  96538. }
  96539. const scratchVector3 = new Vector3$1();
  96540. const scratchOffset = new Vector3$1();
  96541. const scratchVectorU = new Vector3$1();
  96542. const scratchVectorV = new Vector3$1();
  96543. const scratchVectorW = new Vector3$1();
  96544. const scratchCorner = new Vector3$1();
  96545. const scratchToCenter = new Vector3$1();
  96546. const MATRIX3 = {
  96547. COLUMN0ROW0: 0,
  96548. COLUMN0ROW1: 1,
  96549. COLUMN0ROW2: 2,
  96550. COLUMN1ROW0: 3,
  96551. COLUMN1ROW1: 4,
  96552. COLUMN1ROW2: 5,
  96553. COLUMN2ROW0: 6,
  96554. COLUMN2ROW1: 7,
  96555. COLUMN2ROW2: 8
  96556. };
  96557. class OrientedBoundingBox {
  96558. constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  96559. this.center = new Vector3$1().from(center);
  96560. this.halfAxes = new Matrix3$1(halfAxes);
  96561. }
  96562. get halfSize() {
  96563. const xAxis = this.halfAxes.getColumn(0);
  96564. const yAxis = this.halfAxes.getColumn(1);
  96565. const zAxis = this.halfAxes.getColumn(2);
  96566. return [new Vector3$1(xAxis).len(), new Vector3$1(yAxis).len(), new Vector3$1(zAxis).len()];
  96567. }
  96568. get quaternion() {
  96569. const xAxis = this.halfAxes.getColumn(0);
  96570. const yAxis = this.halfAxes.getColumn(1);
  96571. const zAxis = this.halfAxes.getColumn(2);
  96572. const normXAxis = new Vector3$1(xAxis).normalize();
  96573. const normYAxis = new Vector3$1(yAxis).normalize();
  96574. const normZAxis = new Vector3$1(zAxis).normalize();
  96575. return new Quaternion$1().fromMatrix3(new Matrix3$1([...normXAxis, ...normYAxis, ...normZAxis]));
  96576. }
  96577. fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {
  96578. const quaternionObject = new Quaternion$1(quaternion);
  96579. const directionsMatrix = new Matrix3$1().fromQuaternion(quaternionObject);
  96580. directionsMatrix[0] = directionsMatrix[0] * halfSize[0];
  96581. directionsMatrix[1] = directionsMatrix[1] * halfSize[0];
  96582. directionsMatrix[2] = directionsMatrix[2] * halfSize[0];
  96583. directionsMatrix[3] = directionsMatrix[3] * halfSize[1];
  96584. directionsMatrix[4] = directionsMatrix[4] * halfSize[1];
  96585. directionsMatrix[5] = directionsMatrix[5] * halfSize[1];
  96586. directionsMatrix[6] = directionsMatrix[6] * halfSize[2];
  96587. directionsMatrix[7] = directionsMatrix[7] * halfSize[2];
  96588. directionsMatrix[8] = directionsMatrix[8] * halfSize[2];
  96589. this.center = new Vector3$1().from(center);
  96590. this.halfAxes = directionsMatrix;
  96591. return this;
  96592. }
  96593. clone() {
  96594. return new OrientedBoundingBox(this.center, this.halfAxes);
  96595. }
  96596. equals(right) {
  96597. return this === right || Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes);
  96598. }
  96599. getBoundingSphere(result = new BoundingSphere()) {
  96600. const halfAxes = this.halfAxes;
  96601. const u = halfAxes.getColumn(0, scratchVectorU);
  96602. const v = halfAxes.getColumn(1, scratchVectorV);
  96603. const w = halfAxes.getColumn(2, scratchVectorW);
  96604. const cornerVector = scratchVector3.copy(u).add(v).add(w);
  96605. result.center.copy(this.center);
  96606. result.radius = cornerVector.magnitude();
  96607. return result;
  96608. }
  96609. intersectPlane(plane) {
  96610. const center = this.center;
  96611. const normal = plane.normal;
  96612. const halfAxes = this.halfAxes;
  96613. const normalX = normal.x;
  96614. const normalY = normal.y;
  96615. const normalZ = normal.z;
  96616. const radEffective = Math.abs(normalX * halfAxes[MATRIX3.COLUMN0ROW0] + normalY * halfAxes[MATRIX3.COLUMN0ROW1] + normalZ * halfAxes[MATRIX3.COLUMN0ROW2]) + Math.abs(normalX * halfAxes[MATRIX3.COLUMN1ROW0] + normalY * halfAxes[MATRIX3.COLUMN1ROW1] + normalZ * halfAxes[MATRIX3.COLUMN1ROW2]) + Math.abs(normalX * halfAxes[MATRIX3.COLUMN2ROW0] + normalY * halfAxes[MATRIX3.COLUMN2ROW1] + normalZ * halfAxes[MATRIX3.COLUMN2ROW2]);
  96617. const distanceToPlane = normal.dot(center) + plane.distance;
  96618. if (distanceToPlane <= -radEffective) {
  96619. return INTERSECTION.OUTSIDE;
  96620. } else if (distanceToPlane >= radEffective) {
  96621. return INTERSECTION.INSIDE;
  96622. }
  96623. return INTERSECTION.INTERSECTING; //在相机frustum内
  96624. }
  96625. distanceTo(point) {
  96626. return Math.sqrt(this.distanceSquaredTo(point));
  96627. }
  96628. distanceSquaredTo(point) {
  96629. const offset = scratchOffset.from(point).subtract(this.center);
  96630. const halfAxes = this.halfAxes;
  96631. const u = halfAxes.getColumn(0, scratchVectorU);
  96632. const v = halfAxes.getColumn(1, scratchVectorV);
  96633. const w = halfAxes.getColumn(2, scratchVectorW);
  96634. const uHalf = u.magnitude();
  96635. const vHalf = v.magnitude();
  96636. const wHalf = w.magnitude();
  96637. u.normalize();
  96638. v.normalize();
  96639. w.normalize();
  96640. let distanceSquared = 0.0;
  96641. let d;
  96642. d = Math.abs(offset.dot(u)) - uHalf;
  96643. if (d > 0) {
  96644. distanceSquared += d * d;
  96645. }
  96646. d = Math.abs(offset.dot(v)) - vHalf;
  96647. if (d > 0) {
  96648. distanceSquared += d * d;
  96649. }
  96650. d = Math.abs(offset.dot(w)) - wHalf;
  96651. if (d > 0) {
  96652. distanceSquared += d * d;
  96653. }
  96654. return distanceSquared;
  96655. }
  96656. computePlaneDistances(position, direction, result = [-0, -0]) {
  96657. let minDist = Number.POSITIVE_INFINITY;
  96658. let maxDist = Number.NEGATIVE_INFINITY;
  96659. const center = this.center;
  96660. const halfAxes = this.halfAxes;
  96661. const u = halfAxes.getColumn(0, scratchVectorU);
  96662. const v = halfAxes.getColumn(1, scratchVectorV);
  96663. const w = halfAxes.getColumn(2, scratchVectorW);
  96664. const corner = scratchCorner.copy(u).add(v).add(w).add(center);
  96665. const toCenter = scratchToCenter.copy(corner).subtract(position);
  96666. let mag = direction.dot(toCenter);
  96667. minDist = Math.min(mag, minDist);
  96668. maxDist = Math.max(mag, maxDist);
  96669. corner.copy(center).add(u).add(v).subtract(w);
  96670. toCenter.copy(corner).subtract(position);
  96671. mag = direction.dot(toCenter);
  96672. minDist = Math.min(mag, minDist);
  96673. maxDist = Math.max(mag, maxDist);
  96674. corner.copy(center).add(u).subtract(v).add(w);
  96675. toCenter.copy(corner).subtract(position);
  96676. mag = direction.dot(toCenter);
  96677. minDist = Math.min(mag, minDist);
  96678. maxDist = Math.max(mag, maxDist);
  96679. corner.copy(center).add(u).subtract(v).subtract(w);
  96680. toCenter.copy(corner).subtract(position);
  96681. mag = direction.dot(toCenter);
  96682. minDist = Math.min(mag, minDist);
  96683. maxDist = Math.max(mag, maxDist);
  96684. center.copy(corner).subtract(u).add(v).add(w);
  96685. toCenter.copy(corner).subtract(position);
  96686. mag = direction.dot(toCenter);
  96687. minDist = Math.min(mag, minDist);
  96688. maxDist = Math.max(mag, maxDist);
  96689. center.copy(corner).subtract(u).add(v).subtract(w);
  96690. toCenter.copy(corner).subtract(position);
  96691. mag = direction.dot(toCenter);
  96692. minDist = Math.min(mag, minDist);
  96693. maxDist = Math.max(mag, maxDist);
  96694. center.copy(corner).subtract(u).subtract(v).add(w);
  96695. toCenter.copy(corner).subtract(position);
  96696. mag = direction.dot(toCenter);
  96697. minDist = Math.min(mag, minDist);
  96698. maxDist = Math.max(mag, maxDist);
  96699. center.copy(corner).subtract(u).subtract(v).subtract(w);
  96700. toCenter.copy(corner).subtract(position);
  96701. mag = direction.dot(toCenter);
  96702. minDist = Math.min(mag, minDist);
  96703. maxDist = Math.max(mag, maxDist);
  96704. result[0] = minDist;
  96705. result[1] = maxDist;
  96706. return result;
  96707. }
  96708. transform(transformation) {
  96709. this.center.transformAsPoint(transformation);
  96710. const xAxis = this.halfAxes.getColumn(0, scratchVectorU);
  96711. xAxis.transformAsPoint(transformation);
  96712. const yAxis = this.halfAxes.getColumn(1, scratchVectorV);
  96713. yAxis.transformAsPoint(transformation);
  96714. const zAxis = this.halfAxes.getColumn(2, scratchVectorW);
  96715. zAxis.transformAsPoint(transformation);
  96716. this.halfAxes = new Matrix3$1([...xAxis, ...yAxis, ...zAxis]);
  96717. return this;
  96718. }
  96719. getTransform() {
  96720. throw new Error('not implemented');
  96721. }
  96722. }
  96723. const scratchPosition$1 = new Vector3$1();
  96724. const scratchNormal$1 = new Vector3$1();
  96725. class Plane$1 {
  96726. constructor(normal = [0, 0, 1], distance = 0) {
  96727. this.normal = new Vector3$1();
  96728. this.distance = -0;
  96729. this.fromNormalDistance(normal, distance);
  96730. }
  96731. fromNormalDistance(normal, distance) {
  96732. assert$4(Number.isFinite(distance));
  96733. this.normal.from(normal).normalize();
  96734. this.distance = distance;
  96735. return this;
  96736. }
  96737. fromPointNormal(point, normal) {
  96738. point = scratchPosition$1.from(point);
  96739. this.normal.from(normal).normalize();
  96740. const distance = -this.normal.dot(point);
  96741. this.distance = distance;
  96742. return this;
  96743. }
  96744. fromCoefficients(a, b, c, d) {
  96745. this.normal.set(a, b, c);
  96746. assert$4(equals$1(this.normal.len(), 1));
  96747. this.distance = d;
  96748. return this;
  96749. }
  96750. clone(plane) {
  96751. return new Plane$1(this.normal, this.distance);
  96752. }
  96753. equals(right) {
  96754. return equals$1(this.distance, right.distance) && equals$1(this.normal, right.normal);
  96755. }
  96756. getPointDistance(point) {
  96757. return this.normal.dot(point) + this.distance;
  96758. }
  96759. transform(matrix4) {
  96760. const normal = scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();
  96761. const point = this.normal.scale(-this.distance).transform(matrix4);
  96762. return this.fromPointNormal(point, normal);
  96763. }
  96764. projectPointOntoPlane(point, result = [0, 0, 0]) {
  96765. point = scratchPosition$1.from(point);
  96766. const pointDistance = this.getPointDistance(point);
  96767. const scaledNormal = scratchNormal$1.copy(this.normal).scale(pointDistance);
  96768. return point.subtract(scaledNormal).to(result);
  96769. }
  96770. }
  96771. const faces = [new Vector3$1([1, 0, 0]), new Vector3$1([0, 1, 0]), new Vector3$1([0, 0, 1])];
  96772. const scratchPlaneCenter = new Vector3$1();
  96773. const scratchPlaneNormal$1 = new Vector3$1();
  96774. new Plane$1(new Vector3$1(1.0, 0.0, 0.0), 0.0);
  96775. class CullingVolume {
  96776. static get MASK_OUTSIDE() {
  96777. return 0xffffffff;
  96778. }
  96779. static get MASK_INSIDE() {
  96780. return 0x00000000;
  96781. }
  96782. static get MASK_INDETERMINATE() {
  96783. return 0x7fffffff;
  96784. }
  96785. constructor(planes = []) {
  96786. this.planes = planes;
  96787. assert$4(this.planes.every(plane => plane instanceof Plane$1));
  96788. }
  96789. fromBoundingSphere(boundingSphere) {
  96790. this.planes.length = 2 * faces.length;
  96791. const center = boundingSphere.center;
  96792. const radius = boundingSphere.radius;
  96793. let planeIndex = 0;
  96794. for (const faceNormal of faces) {
  96795. let plane0 = this.planes[planeIndex];
  96796. let plane1 = this.planes[planeIndex + 1];
  96797. if (!plane0) {
  96798. plane0 = this.planes[planeIndex] = new Plane$1();
  96799. }
  96800. if (!plane1) {
  96801. plane1 = this.planes[planeIndex + 1] = new Plane$1();
  96802. }
  96803. const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);
  96804. -faceNormal.dot(plane0Center);
  96805. plane0.fromPointNormal(plane0Center, faceNormal);
  96806. const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);
  96807. const negatedFaceNormal = scratchPlaneNormal$1.copy(faceNormal).negate();
  96808. -negatedFaceNormal.dot(plane1Center);
  96809. plane1.fromPointNormal(plane1Center, negatedFaceNormal);
  96810. planeIndex += 2;
  96811. }
  96812. return this;
  96813. }
  96814. computeVisibility(boundingVolume) {
  96815. assert$4(boundingVolume);
  96816. let intersect = INTERSECTION.INSIDE;
  96817. for (const plane of this.planes) {
  96818. const result = boundingVolume.intersectPlane(plane);
  96819. switch (result) {
  96820. case INTERSECTION.OUTSIDE:
  96821. return INTERSECTION.OUTSIDE;
  96822. case INTERSECTION.INTERSECTING:
  96823. intersect = INTERSECTION.INTERSECTING;
  96824. break;
  96825. }
  96826. }
  96827. return intersect;
  96828. }
  96829. computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {
  96830. assert$4(boundingVolume, 'boundingVolume is required.');
  96831. assert$4(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');
  96832. if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
  96833. return parentPlaneMask;
  96834. }
  96835. let mask = CullingVolume.MASK_INSIDE;
  96836. const planes = this.planes;
  96837. for (let k = 0; k < this.planes.length; ++k) {
  96838. const flag = k < 31 ? 1 << k : 0;
  96839. if (k < 31 && (parentPlaneMask & flag) === 0) {
  96840. continue;
  96841. }
  96842. const plane = planes[k];
  96843. const result = boundingVolume.intersectPlane(plane);
  96844. if (result === INTERSECTION.OUTSIDE) {
  96845. return CullingVolume.MASK_OUTSIDE;
  96846. } else if (result === INTERSECTION.INTERSECTING) {
  96847. mask |= flag;
  96848. }
  96849. }
  96850. return mask;
  96851. }
  96852. }
  96853. const scratchPlaneUpVector = new Vector3$1();
  96854. const scratchPlaneRightVector = new Vector3$1();
  96855. const scratchPlaneNearCenter = new Vector3$1();
  96856. const scratchPlaneFarCenter = new Vector3$1();
  96857. const scratchPlaneNormal = new Vector3$1();
  96858. class PerspectiveOffCenterFrustum {
  96859. constructor(options = {}) {
  96860. options = {
  96861. near: 1.0,
  96862. far: 500000000.0,
  96863. ...options
  96864. };
  96865. this.left = options.left;
  96866. this._left = undefined;
  96867. this.right = options.right;
  96868. this._right = undefined;
  96869. this.top = options.top;
  96870. this._top = undefined;
  96871. this.bottom = options.bottom;
  96872. this._bottom = undefined;
  96873. this.near = options.near;
  96874. this._near = this.near;
  96875. this.far = options.far;
  96876. this._far = this.far;
  96877. this._cullingVolume = new CullingVolume([new Plane$1(), new Plane$1(), new Plane$1(), new Plane$1(), new Plane$1(), new Plane$1()]);
  96878. this._perspectiveMatrix = new Matrix4$1();
  96879. this._infinitePerspective = new Matrix4$1();
  96880. }
  96881. clone() {
  96882. return new PerspectiveOffCenterFrustum({
  96883. right: this.right,
  96884. left: this.left,
  96885. top: this.top,
  96886. bottom: this.bottom,
  96887. near: this.near,
  96888. far: this.far
  96889. });
  96890. }
  96891. equals(other) {
  96892. 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;
  96893. }
  96894. get projectionMatrix() {
  96895. update$1(this);
  96896. return this._perspectiveMatrix;
  96897. }
  96898. get infiniteProjectionMatrix() {
  96899. update$1(this);
  96900. return this._infinitePerspective;
  96901. }
  96902. computeCullingVolume(position, direction, up) {
  96903. assert$4(position, 'position is required.');
  96904. assert$4(direction, 'direction is required.');
  96905. assert$4(up, 'up is required.');
  96906. const planes = this._cullingVolume.planes;
  96907. up = scratchPlaneUpVector.copy(up).normalize();
  96908. const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();
  96909. const nearCenter = scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);
  96910. const farCenter = scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);
  96911. let normal = scratchPlaneNormal;
  96912. normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);
  96913. planes[0].fromPointNormal(position, normal);
  96914. normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();
  96915. planes[1].fromPointNormal(position, normal);
  96916. normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();
  96917. planes[2].fromPointNormal(position, normal);
  96918. normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);
  96919. planes[3].fromPointNormal(position, normal);
  96920. normal = new Vector3$1().copy(direction);
  96921. planes[4].fromPointNormal(nearCenter, normal);
  96922. normal.negate();
  96923. planes[5].fromPointNormal(farCenter, normal);
  96924. return this._cullingVolume;
  96925. }
  96926. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  96927. update$1(this);
  96928. assert$4(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));
  96929. assert$4(drawingBufferWidth > 0);
  96930. assert$4(drawingBufferHeight > 0);
  96931. assert$4(distance > 0);
  96932. assert$4(result);
  96933. const inverseNear = 1.0 / this.near;
  96934. let tanTheta = this.top * inverseNear;
  96935. const pixelHeight = 2.0 * distance * tanTheta / drawingBufferHeight;
  96936. tanTheta = this.right * inverseNear;
  96937. const pixelWidth = 2.0 * distance * tanTheta / drawingBufferWidth;
  96938. result.x = pixelWidth;
  96939. result.y = pixelHeight;
  96940. return result;
  96941. }
  96942. }
  96943. function update$1(frustum) {
  96944. 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));
  96945. const {
  96946. top,
  96947. bottom,
  96948. right,
  96949. left,
  96950. near,
  96951. far
  96952. } = frustum;
  96953. if (top !== frustum._top || bottom !== frustum._bottom || left !== frustum._left || right !== frustum._right || near !== frustum._near || far !== frustum._far) {
  96954. assert$4(frustum.near > 0 && frustum.near < frustum.far, 'near must be greater than zero and less than far.');
  96955. frustum._left = left;
  96956. frustum._right = right;
  96957. frustum._top = top;
  96958. frustum._bottom = bottom;
  96959. frustum._near = near;
  96960. frustum._far = far;
  96961. frustum._perspectiveMatrix = new Matrix4$1().frustum({
  96962. left,
  96963. right,
  96964. bottom,
  96965. top,
  96966. near,
  96967. far
  96968. });
  96969. frustum._infinitePerspective = new Matrix4$1().frustum({
  96970. left,
  96971. right,
  96972. bottom,
  96973. top,
  96974. near,
  96975. far: Infinity
  96976. });
  96977. }
  96978. }
  96979. const defined$4 = val => val !== null && typeof val !== 'undefined';
  96980. class PerspectiveFrustum {
  96981. constructor(options = {}) {
  96982. options = {
  96983. near: 1.0,
  96984. far: 500000000.0,
  96985. xOffset: 0.0,
  96986. yOffset: 0.0,
  96987. ...options
  96988. };
  96989. this._offCenterFrustum = new PerspectiveOffCenterFrustum();
  96990. this.fov = options.fov;
  96991. this._fov = undefined;
  96992. this._fovy = undefined;
  96993. this._sseDenominator = undefined;
  96994. this.aspectRatio = options.aspectRatio;
  96995. this._aspectRatio = undefined;
  96996. this.near = options.near;
  96997. this._near = this.near;
  96998. this.far = options.far;
  96999. this._far = this.far;
  97000. this.xOffset = options.xOffset;
  97001. this._xOffset = this.xOffset;
  97002. this.yOffset = options.yOffset;
  97003. this._yOffset = this.yOffset;
  97004. }
  97005. clone() {
  97006. return new PerspectiveFrustum({
  97007. aspectRatio: this.aspectRatio,
  97008. fov: this.fov,
  97009. near: this.near,
  97010. far: this.far
  97011. });
  97012. }
  97013. equals(other) {
  97014. if (!defined$4(other) || !(other instanceof PerspectiveFrustum)) {
  97015. return false;
  97016. }
  97017. update(this);
  97018. update(other);
  97019. return this.fov === other.fov && this.aspectRatio === other.aspectRatio && this.near === other.near && this.far === other.far && this._offCenterFrustum.equals(other._offCenterFrustum);
  97020. }
  97021. get projectionMatrix() {
  97022. update(this);
  97023. return this._offCenterFrustum.projectionMatrix;
  97024. }
  97025. get infiniteProjectionMatrix() {
  97026. update(this);
  97027. return this._offCenterFrustum.infiniteProjectionMatrix;
  97028. }
  97029. get fovy() {
  97030. update(this);
  97031. return this._fovy;
  97032. }
  97033. get sseDenominator() {
  97034. update(this);
  97035. return this._sseDenominator;
  97036. }
  97037. computeCullingVolume(position, direction, up) {
  97038. update(this);
  97039. return this._offCenterFrustum.computeCullingVolume(position, direction, up);
  97040. }
  97041. getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {
  97042. update(this);
  97043. return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result);
  97044. }
  97045. }
  97046. function update(frustum) {
  97047. assert$4(Number.isFinite(frustum.fov) && Number.isFinite(frustum.aspectRatio) && Number.isFinite(frustum.near) && Number.isFinite(frustum.far));
  97048. const f = frustum._offCenterFrustum;
  97049. 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) {
  97050. assert$4(frustum.fov >= 0 && frustum.fov < Math.PI);
  97051. //assert$4(frustum.aspectRatio > 0);
  97052. if(frustum.aspectRatio == 0){
  97053. console.log(1);
  97054. }
  97055. assert$4(frustum.near >= 0 && frustum.near < frustum.far);
  97056. frustum._aspectRatio = Math.max(0.001, frustum.aspectRatio);
  97057. frustum._fov = frustum.fov;
  97058. frustum._fovy = frustum._aspectRatio <= 1 ? frustum.fov : Math.atan(Math.tan(frustum.fov * 0.5) / frustum._aspectRatio) * 2.0;
  97059. frustum._near = frustum.near;
  97060. frustum._far = frustum.far;
  97061. frustum._sseDenominator = 2.0 * Math.tan(0.5 * frustum._fovy);
  97062. frustum._xOffset = frustum.xOffset;
  97063. frustum._yOffset = frustum.yOffset;
  97064. f.top = frustum.near * Math.tan(0.5 * frustum._fovy);
  97065. f.bottom = -f.top;
  97066. f.right = frustum._aspectRatio * f.top;
  97067. f.left = -f.right;
  97068. f.near = frustum.near;
  97069. f.far = frustum.far;
  97070. f.right += frustum.xOffset;
  97071. f.left += frustum.xOffset;
  97072. f.top += frustum.yOffset;
  97073. f.bottom += frustum.yOffset;
  97074. }
  97075. }
  97076. new Vector3$1();
  97077. new Vector3$1();
  97078. new Vector3$1();
  97079. new Vector3$1();
  97080. new Vector3$1();
  97081. new Vector3$1();
  97082. new Vector3$1();
  97083. new Vector3$1();
  97084. new Vector3$1();
  97085. new Vector3$1();
  97086. new Vector3$1();
  97087. new Vector3$1();
  97088. new Matrix3$1();
  97089. new Matrix3$1();
  97090. new Matrix3$1();
  97091. new Matrix3$1();
  97092. new Matrix3$1();
  97093. new Vector3$1();
  97094. new Vector3$1();
  97095. new Vector3$1();
  97096. new Vector3$1();
  97097. new Vector3$1();
  97098. new Matrix3$1();
  97099. ({
  97100. diagonal: new Matrix3$1(),
  97101. unitary: new Matrix3$1()
  97102. });
  97103. const scratchVector$2 = new Vector3$1();
  97104. const scratchPosition = new Vector3$1();
  97105. const cullingVolume = new CullingVolume([new Plane$1(), new Plane$1(), new Plane$1(), new Plane$1(), new Plane$1(), new Plane$1()]);
  97106. function getFrameState(viewport, frameNumber) {
  97107. const {
  97108. cameraDirection,
  97109. cameraUp,
  97110. height
  97111. } = viewport;
  97112. const {
  97113. metersPerUnit
  97114. } = viewport.distanceScales;
  97115. const viewportCenterCartographic = viewport.unprojectPosition(viewport.center);
  97116. const viewportCenterCartesian = Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic, new Vector3$1());
  97117. const enuToFixedTransform = Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);
  97118. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  97119. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3$1());
  97120. const cameraDirectionCartesian = new Vector3$1(enuToFixedTransform.transformAsVector(new Vector3$1(cameraDirection).scale(metersPerUnit))).normalize();
  97121. const cameraUpCartesian = new Vector3$1(enuToFixedTransform.transformAsVector(new Vector3$1(cameraUp).scale(metersPerUnit))).normalize();
  97122. commonSpacePlanesToWGS84(viewport, viewportCenterCartesian);
  97123. return {
  97124. camera: {
  97125. position: cameraPositionCartesian,
  97126. direction: cameraDirectionCartesian,
  97127. up: cameraUpCartesian
  97128. },
  97129. viewport,
  97130. height,
  97131. cullingVolume,
  97132. frameNumber,
  97133. sseDenominator: 1.15
  97134. };
  97135. }
  97136. function commonSpacePlanesToWGS84(viewport, viewportCenterCartesian) {
  97137. const frustumPlanes = viewport.getFrustumPlanes();
  97138. let i = 0;
  97139. for (const dir in frustumPlanes) {
  97140. const plane = frustumPlanes[dir];
  97141. const distanceToCenter = plane.normal.dot(viewport.center);
  97142. scratchPosition.copy(plane.normal).scale(plane.distance - distanceToCenter).add(viewport.center);
  97143. const cartographicPos = viewport.unprojectPosition(scratchPosition);
  97144. const cartesianPos = Ellipsoid.WGS84.cartographicToCartesian(cartographicPos, new Vector3$1());
  97145. cullingVolume.planes[i++].fromPointNormal(cartesianPos, scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));
  97146. }
  97147. }
  97148. const WGS84_RADIUS_X = 6378137.0;
  97149. const WGS84_RADIUS_Y = 6378137.0;
  97150. const WGS84_RADIUS_Z = 6356752.3142451793;
  97151. const scratchVector$1 = new Vector3$1();
  97152. function getZoomFromBoundingVolume(boundingVolume) {
  97153. const {
  97154. halfAxes,
  97155. radius,
  97156. width,
  97157. height
  97158. } = boundingVolume;
  97159. if (halfAxes) {
  97160. const obbSize = getObbSize(halfAxes);
  97161. return Math.log2(WGS84_RADIUS_Z / obbSize);
  97162. } else if (radius) {
  97163. return Math.log2(WGS84_RADIUS_Z / radius);
  97164. } else if (height && width) {
  97165. const zoomX = Math.log2(WGS84_RADIUS_X / width);
  97166. const zoomY = Math.log2(WGS84_RADIUS_Y / height);
  97167. return (zoomX + zoomY) / 2;
  97168. }
  97169. return 1;
  97170. }
  97171. function getObbSize(halfAxes) {
  97172. halfAxes.getColumn(0, scratchVector$1);
  97173. const axeY = halfAxes.getColumn(1);
  97174. const axeZ = halfAxes.getColumn(2);
  97175. const farthestVertex = scratchVector$1.add(axeY).add(axeZ);
  97176. const size = farthestVertex.len();
  97177. return size;
  97178. }
  97179. const TILE_CONTENT_STATE = {
  97180. UNLOADED: 0,
  97181. LOADING: 1,
  97182. PROCESSING: 2,
  97183. READY: 3,
  97184. EXPIRED: 4,
  97185. FAILED: 5
  97186. };
  97187. const TILE_REFINEMENT = {
  97188. ADD: 1,
  97189. REPLACE: 2
  97190. };
  97191. const TILE_TYPE = {
  97192. EMPTY: 'empty',
  97193. SCENEGRAPH: 'scenegraph',
  97194. POINTCLOUD: 'pointcloud',
  97195. MESH: 'mesh'
  97196. };
  97197. const TILESET_TYPE = {
  97198. I3S: 'I3S',
  97199. TILES3D: 'TILES3D'
  97200. };
  97201. const LOD_METRIC_TYPE = {
  97202. GEOMETRIC_ERROR: 'geometricError',
  97203. MAX_SCREEN_THRESHOLD: 'maxScreenThreshold'
  97204. };
  97205. const TILE3D_OPTIMIZATION_HINT = {
  97206. NOT_COMPUTED: -1,
  97207. USE_OPTIMIZATION: 1,
  97208. SKIP_OPTIMIZATION: 0
  97209. };
  97210. function defined$3(x) {
  97211. return x !== undefined && x !== null;
  97212. }
  97213. const scratchScale = new Vector3$1();
  97214. const scratchNorthWest = new Vector3$1();
  97215. const scratchSouthEast = new Vector3$1();
  97216. function createBoundingVolume(boundingVolumeHeader, transform, result) {
  97217. assert$7(boundingVolumeHeader, '3D Tile: boundingVolume must be defined');
  97218. if (boundingVolumeHeader.box) {
  97219. return createBox(boundingVolumeHeader.box, transform, result);
  97220. }
  97221. if (boundingVolumeHeader.region) {
  97222. const [west, south, east, north, minHeight, maxHeight] = boundingVolumeHeader.region;
  97223. const northWest = Ellipsoid.WGS84.cartographicToCartesian([degrees(west), degrees(north), minHeight], scratchNorthWest);
  97224. const southEast = Ellipsoid.WGS84.cartographicToCartesian([degrees(east), degrees(south), maxHeight], scratchSouthEast);
  97225. const centerInCartesian = new Vector3$1().addVectors(northWest, southEast).multiplyScalar(0.5);
  97226. const radius = new Vector3$1().subVectors(northWest, southEast).len() / 2.0;
  97227. return createSphere([centerInCartesian[0], centerInCartesian[1], centerInCartesian[2], radius], new Matrix4$1());
  97228. }
  97229. if (boundingVolumeHeader.sphere) {
  97230. return createSphere(boundingVolumeHeader.sphere, transform, result);
  97231. }
  97232. throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');
  97233. }
  97234. function createBox(box, transform, result) {
  97235. const center = new Vector3$1(box[0], box[1], box[2]);
  97236. result && (result.oriCenter = center);//add
  97237. transform.transform(center, center);
  97238. let origin = [];
  97239. if (box.length === 10) {
  97240. const halfSize = box.slice(3, 6);
  97241. const quaternion = new Quaternion$1();
  97242. quaternion.fromArray(box, 6);
  97243. const x = new Vector3$1([1, 0, 0]);
  97244. const y = new Vector3$1([0, 1, 0]);
  97245. const z = new Vector3$1([0, 0, 1]);
  97246. x.transformByQuaternion(quaternion);
  97247. x.scale(halfSize[0]);
  97248. y.transformByQuaternion(quaternion);
  97249. y.scale(halfSize[1]);
  97250. z.transformByQuaternion(quaternion);
  97251. z.scale(halfSize[2]);
  97252. origin = [...x.toArray(), ...y.toArray(), ...z.toArray()];
  97253. } else {
  97254. origin = [...box.slice(3, 6), ...box.slice(6, 9), ...box.slice(9, 12)];
  97255. }
  97256. const xAxis = transform.transformAsVector(origin.slice(0, 3));
  97257. const yAxis = transform.transformAsVector(origin.slice(3, 6));
  97258. const zAxis = transform.transformAsVector(origin.slice(6, 9));
  97259. const halfAxes = new Matrix3$1([xAxis[0], xAxis[1], xAxis[2], yAxis[0], yAxis[1], yAxis[2], zAxis[0], zAxis[1], zAxis[2]]);
  97260. if (defined$3(result)) {
  97261. result.center = center;
  97262. result.halfAxes = halfAxes;
  97263. return result;
  97264. }
  97265. return new OrientedBoundingBox(center, halfAxes);
  97266. }
  97267. function createSphere(sphere, transform, result) {
  97268. const center = new Vector3$1(sphere[0], sphere[1], sphere[2]);
  97269. transform.transform(center, center);
  97270. const scale = transform.getScale(scratchScale);
  97271. const uniformScale = Math.max(Math.max(scale[0], scale[1]), scale[2]);
  97272. const radius = sphere[3] * uniformScale;
  97273. if (defined$3(result)) {
  97274. result.center = center;
  97275. result.radius = radius;
  97276. return result;
  97277. }
  97278. return new BoundingSphere(center, radius);
  97279. }
  97280. new Vector3$1();
  97281. new Vector3$1();
  97282. new Matrix4$1();
  97283. new Vector3$1();
  97284. new Vector3$1();
  97285. new Vector3$1();
  97286. function fog(distanceToCamera, density) {
  97287. const scalar = distanceToCamera * density;
  97288. return 1.0 - Math.exp(-(scalar * scalar));
  97289. }
  97290. function getDynamicScreenSpaceError(tileset, distanceToCamera) {
  97291. if (tileset.dynamicScreenSpaceError && tileset.dynamicScreenSpaceErrorComputedDensity) {
  97292. const density = tileset.dynamicScreenSpaceErrorComputedDensity;
  97293. const factor = tileset.dynamicScreenSpaceErrorFactor;
  97294. const dynamicError = fog(distanceToCamera, density) * factor;
  97295. return dynamicError;
  97296. }
  97297. return 0;
  97298. }
  97299. function getTiles3DScreenSpaceError(tile, frameState, useParentLodMetric) {
  97300. const tileset = tile.tileset;
  97301. const parentLodMetricValue = tile.parent && tile.parent.lodMetricValue || tile.lodMetricValue;
  97302. const lodMetricValue = useParentLodMetric ? parentLodMetricValue : tile.lodMetricValue;
  97303. if (lodMetricValue === 0.0) {
  97304. return 0.0;
  97305. }
  97306. const distance = Math.max(tile._distanceToCamera, 1e-7);
  97307. const {
  97308. height,
  97309. sseDenominator
  97310. } = frameState;
  97311. const {
  97312. viewDistanceScale
  97313. } = tileset.options;
  97314. let error = lodMetricValue * height * (viewDistanceScale || 1.0) / (distance * sseDenominator);
  97315. error -= getDynamicScreenSpaceError(tileset, distance);
  97316. return error;
  97317. }
  97318. function getLodStatus(tile, frameState) {
  97319. if (tile.lodMetricValue === 0 || isNaN(tile.lodMetricValue)) {
  97320. return 'DIG';
  97321. }
  97322. const screenSize = 2 * getProjectedRadius(tile, frameState);
  97323. if (screenSize < 2) {
  97324. return 'OUT';
  97325. }
  97326. if (!tile.header.children || screenSize <= tile.lodMetricValue) {
  97327. return 'DRAW';
  97328. } else if (tile.header.children) {
  97329. return 'DIG';
  97330. }
  97331. return 'OUT';
  97332. }
  97333. function getProjectedRadius(tile, frameState) {
  97334. const originalViewport = frameState.viewport;
  97335. const ViewportClass = originalViewport.constructor;
  97336. const {
  97337. longitude,
  97338. latitude,
  97339. height,
  97340. width,
  97341. bearing,
  97342. zoom
  97343. } = originalViewport;
  97344. const viewport = new ViewportClass({
  97345. longitude,
  97346. latitude,
  97347. height,
  97348. width,
  97349. bearing,
  97350. zoom,
  97351. pitch: 0
  97352. });
  97353. const mbsLat = tile.header.mbs[1];
  97354. const mbsLon = tile.header.mbs[0];
  97355. const mbsZ = tile.header.mbs[2];
  97356. const mbsR = tile.header.mbs[3];
  97357. const mbsCenterCartesian = [...tile.boundingVolume.center];
  97358. const cameraPositionCartographic = viewport.unprojectPosition(viewport.cameraPosition);
  97359. const cameraPositionCartesian = Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic, new Vector3$1());
  97360. const toEye = new Vector3$1(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();
  97361. const enuToCartesianMatrix = new Matrix4$1();
  97362. Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian, enuToCartesianMatrix);
  97363. const cartesianToEnuMatrix = new Matrix4$1(enuToCartesianMatrix).invert();
  97364. const cameraPositionEnu = new Vector3$1(cameraPositionCartesian).transform(cartesianToEnuMatrix);
  97365. const projection = Math.sqrt(cameraPositionEnu[0] * cameraPositionEnu[0] + cameraPositionEnu[1] * cameraPositionEnu[1]);
  97366. const extraZ = projection * projection / cameraPositionEnu[2];
  97367. const extraVertexEnu = new Vector3$1([cameraPositionEnu[0], cameraPositionEnu[1], extraZ]);
  97368. const extraVertexCartesian = extraVertexEnu.transform(enuToCartesianMatrix);
  97369. const extraVectorCartesian = new Vector3$1(extraVertexCartesian).subtract(mbsCenterCartesian).normalize();
  97370. const radiusVector = toEye.cross(extraVectorCartesian).normalize().scale(mbsR);
  97371. const sphereMbsBorderVertexCartesian = new Vector3$1(mbsCenterCartesian).add(radiusVector);
  97372. const sphereMbsBorderVertexCartographic = Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);
  97373. const projectedOrigin = viewport.project([mbsLon, mbsLat, mbsZ]);
  97374. const projectedMbsBorderVertex = viewport.project(sphereMbsBorderVertexCartographic);
  97375. const projectedRadius = new Vector3$1(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();
  97376. return projectedRadius;
  97377. }
  97378. function get3dTilesOptions(tileset) {
  97379. return {
  97380. assetGltfUpAxis: tileset.asset && tileset.asset.gltfUpAxis || 'Y'
  97381. };
  97382. }
  97383. class ManagedArray {
  97384. constructor(length = 0) {
  97385. _defineProperty(this, "_map", new Map());
  97386. _defineProperty(this, "_array", void 0);
  97387. _defineProperty(this, "_length", void 0);
  97388. this._array = new Array(length);
  97389. this._length = length;
  97390. }
  97391. get length() {
  97392. return this._length;
  97393. }
  97394. set length(length) {
  97395. this._length = length;
  97396. if (length > this._array.length) {
  97397. this._array.length = length;
  97398. }
  97399. }
  97400. get values() {
  97401. return this._array;
  97402. }
  97403. get(index) {
  97404. assert$7(index < this._array.length);
  97405. return this._array[index];
  97406. }
  97407. set(index, element) {
  97408. assert$7(index >= 0);
  97409. if (index >= this.length) {
  97410. this.length = index + 1;
  97411. }
  97412. if (this._map.has(this._array[index])) {
  97413. this._map.delete(this._array[index]);
  97414. }
  97415. this._array[index] = element;
  97416. this._map.set(element, index);
  97417. }
  97418. delete(element) {
  97419. const index = this._map.get(element);
  97420. if (index >= 0) {
  97421. this._array.splice(index, 1);
  97422. this._map.delete(element);
  97423. this.length--;
  97424. }
  97425. }
  97426. peek() {
  97427. return this._array[this._length - 1];
  97428. }
  97429. push(element) {
  97430. if (!this._map.has(element)) {
  97431. const index = this.length++;
  97432. this._array[index] = element;
  97433. this._map.set(element, index);
  97434. }
  97435. }
  97436. pop() {
  97437. const element = this._array[--this.length];
  97438. this._map.delete(element);
  97439. return element;
  97440. }
  97441. reserve(length) {
  97442. assert$7(length >= 0);
  97443. if (length > this._array.length) {
  97444. this._array.length = length;
  97445. }
  97446. }
  97447. resize(length) {
  97448. assert$7(length >= 0);
  97449. this.length = length;
  97450. }
  97451. trim(length) {
  97452. if (length === null || length === undefined) {
  97453. length = this.length;
  97454. }
  97455. this._array.length = length;
  97456. }
  97457. reset() {
  97458. this._array = [];
  97459. this._map = new Map();
  97460. this._length = 0;
  97461. }
  97462. find(target) {
  97463. return this._map.has(target);
  97464. }
  97465. }
  97466. const DEFAULT_PROPS$1 = {
  97467. loadSiblings: false,
  97468. skipLevelOfDetail: false,
  97469. maximumScreenSpaceError: 2,
  97470. updateTransforms: true,
  97471. onTraversalEnd: () => {},
  97472. viewportTraversersMap: {},
  97473. basePath: ''
  97474. };
  97475. class TilesetTraverser {
  97476. constructor(options) {
  97477. _defineProperty(this, "options", void 0);
  97478. _defineProperty(this, "root", void 0);
  97479. _defineProperty(this, "requestedTiles", void 0);
  97480. _defineProperty(this, "selectedTiles", void 0);
  97481. _defineProperty(this, "emptyTiles", void 0);
  97482. _defineProperty(this, "_traversalStack", void 0);
  97483. _defineProperty(this, "_emptyTraversalStack", void 0);
  97484. _defineProperty(this, "_frameNumber", void 0);
  97485. this.options = { ...DEFAULT_PROPS$1,
  97486. ...options
  97487. };
  97488. this._traversalStack = new ManagedArray();
  97489. this._emptyTraversalStack = new ManagedArray();
  97490. this._frameNumber = null;
  97491. this.root = null;
  97492. this.selectedTiles = {};
  97493. this.requestedTiles = {};
  97494. this.emptyTiles = {};
  97495. }
  97496. traverse(root, frameState, options) {
  97497. this.root = root;
  97498. this.options = { ...this.options,
  97499. ...options
  97500. };
  97501. this.reset();
  97502. this.updateTile(root, frameState);
  97503. this._frameNumber = frameState.frameNumber;
  97504. this.executeTraversal(root, frameState);
  97505. }
  97506. reset() {
  97507. this.requestedTiles = {};
  97508. this.selectedTiles = {};
  97509. this.emptyTiles = {};
  97510. this._traversalStack.reset();
  97511. this._emptyTraversalStack.reset();
  97512. }
  97513. executeTraversal(root, frameState) {// 遍历root
  97514. const stack = this._traversalStack;
  97515. root._selectionDepth = 1;
  97516. stack.push(root);
  97517. while (stack.length > 0) {
  97518. const tile = stack.pop();
  97519. let shouldRefine = false;
  97520. // !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度
  97521. if (this.canTraverse(tile, frameState) && tile.depth < this.options.maxDepth) {//add maxDepth
  97522. this.updateChildTiles(tile, frameState);
  97523. shouldRefine = this.updateAndPushChildren(tile, frameState, stack, tile.hasRenderContent ? tile._selectionDepth + 1 : tile._selectionDepth);
  97524. }
  97525. const parent = tile.parent;
  97526. const parentRefines = Boolean(!parent || parent._shouldRefine);
  97527. const stoppedRefining = !shouldRefine;
  97528. if (!tile.hasRenderContent) {
  97529. this.emptyTiles[tile.id] = tile;
  97530. this.loadTile(tile, frameState);
  97531. if (stoppedRefining) {
  97532. this.selectTile(tile, frameState);
  97533. }
  97534. } else if (tile.refine === TILE_REFINEMENT.ADD) {
  97535. this.loadTile(tile, frameState);
  97536. this.selectTile(tile, frameState);
  97537. } else if (tile.refine === TILE_REFINEMENT.REPLACE) {
  97538. this.loadTile(tile, frameState);
  97539. if (stoppedRefining) {
  97540. this.selectTile(tile, frameState);
  97541. }
  97542. }
  97543. this.touchTile(tile, frameState);
  97544. tile._shouldRefine = shouldRefine && parentRefines;
  97545. }
  97546. this.options.onTraversalEnd(frameState);
  97547. }
  97548. updateChildTiles(tile, frameState) {
  97549. const children = tile.children;
  97550. for (const child of children) {
  97551. this.updateTile(child, frameState);
  97552. }
  97553. return true;
  97554. }
  97555. updateAndPushChildren(tile, frameState, stack, depth) {
  97556. const {
  97557. loadSiblings,
  97558. skipLevelOfDetail
  97559. } = this.options;
  97560. const children = tile.children;
  97561. children.sort(this.compareDistanceToCamera.bind(this));
  97562. const checkRefines = tile.refine === TILE_REFINEMENT.REPLACE && tile.hasRenderContent && !skipLevelOfDetail;
  97563. let hasVisibleChild = false;
  97564. let refines = true;
  97565. for (const child of children) {
  97566. child._selectionDepth = depth;
  97567. if (child.isVisibleAndInRequestVolume) {
  97568. if (stack.find(child)) {
  97569. stack.delete(child);
  97570. }
  97571. stack.push(child);
  97572. hasVisibleChild = true;
  97573. } else if (checkRefines || loadSiblings) {
  97574. this.loadTile(child, frameState);
  97575. this.touchTile(child, frameState);
  97576. }
  97577. if (checkRefines) {
  97578. let childRefines;
  97579. if (!child._inRequestVolume) {
  97580. childRefines = false;
  97581. } else if (!child.hasRenderContent) {
  97582. childRefines = this.executeEmptyTraversal(child, frameState);
  97583. } else {
  97584. childRefines = child.contentAvailable;
  97585. }
  97586. refines = refines && childRefines;
  97587. if (!refines) {
  97588. return false;
  97589. }
  97590. }
  97591. }
  97592. if (!hasVisibleChild) {
  97593. refines = false;
  97594. }
  97595. return refines;
  97596. }
  97597. updateTile(tile, frameState) {
  97598. this.updateTileVisibility(tile, frameState);
  97599. }
  97600. selectTile(tile, frameState) {
  97601. if (this.shouldSelectTile(tile)) {
  97602. tile._selectedFrame = frameState.frameNumber;
  97603. this.selectedTiles[tile.id] = tile;
  97604. }
  97605. }
  97606. loadTile(tile, frameState) {
  97607. if (this.shouldLoadTile(tile)) {
  97608. tile._requestedFrame = frameState.frameNumber;
  97609. tile._priority = tile._getPriority();
  97610. this.requestedTiles[tile.id] = tile;
  97611. }
  97612. }
  97613. touchTile(tile, frameState) {
  97614. tile.tileset._cache.touch(tile);
  97615. tile._touchedFrame = frameState.frameNumber;
  97616. }
  97617. canTraverse(tile, frameState, useParentMetric = false, ignoreVisibility = false) {
  97618. if (!tile.hasChildren) {
  97619. return false;
  97620. }
  97621. if (tile.hasTilesetContent) {
  97622. return !tile.contentExpired;
  97623. }
  97624. if (!ignoreVisibility && !tile.isVisibleAndInRequestVolume) {
  97625. return false;
  97626. }
  97627. return this.shouldRefine(tile, frameState, useParentMetric);
  97628. }
  97629. shouldLoadTile(tile) {
  97630. return tile.hasUnloadedContent || tile.contentExpired;
  97631. }
  97632. shouldSelectTile(tile) {
  97633. return tile.contentAvailable && !this.options.skipLevelOfDetail;
  97634. }
  97635. shouldRefine(tile, frameState, useParentMetric) {
  97636. let screenSpaceError = tile._screenSpaceError;
  97637. if (useParentMetric) {
  97638. screenSpaceError = tile.getScreenSpaceError(frameState, true);
  97639. }
  97640. return screenSpaceError > this.options.maximumScreenSpaceError;
  97641. }
  97642. updateTileVisibility(tile, frameState) {
  97643. const viewportIds = [];
  97644. if (this.options.viewportTraversersMap) {
  97645. for (const key in this.options.viewportTraversersMap) {
  97646. const value = this.options.viewportTraversersMap[key];
  97647. if (value === frameState.viewport.id) {
  97648. viewportIds.push(key);
  97649. }
  97650. }
  97651. } else {
  97652. viewportIds.push(frameState.viewport.id);
  97653. }
  97654. tile.updateVisibility(frameState, viewportIds);
  97655. }
  97656. compareDistanceToCamera(b, a) {
  97657. return b._distanceToCamera - a._distanceToCamera;
  97658. }
  97659. anyChildrenVisible(tile, frameState) {
  97660. let anyVisible = false;
  97661. for (const child of tile.children) {
  97662. child.updateVisibility(frameState);
  97663. anyVisible = anyVisible || child.isVisibleAndInRequestVolume;
  97664. }
  97665. return anyVisible;
  97666. }
  97667. executeEmptyTraversal(root, frameState) {
  97668. let allDescendantsLoaded = true;
  97669. const stack = this._emptyTraversalStack;
  97670. stack.push(root);
  97671. while (stack.length > 0 && allDescendantsLoaded) {
  97672. const tile = stack.pop();
  97673. this.updateTile(tile, frameState);
  97674. if (!tile.isVisibleAndInRequestVolume) {
  97675. this.loadTile(tile, frameState);
  97676. }
  97677. this.touchTile(tile, frameState);
  97678. const traverse = !tile.hasRenderContent && this.canTraverse(tile, frameState, false, true);
  97679. if (traverse) {
  97680. const children = tile.children;
  97681. for (const child of children) {
  97682. if (stack.find(child)) {
  97683. stack.delete(child);
  97684. }
  97685. stack.push(child);
  97686. }
  97687. } else if (!tile.contentAvailable) {
  97688. allDescendantsLoaded = false;
  97689. }
  97690. }
  97691. return allDescendantsLoaded;
  97692. }
  97693. }
  97694. const scratchVector = new Vector3$1();
  97695. function defined$2(x) {
  97696. return x !== undefined && x !== null;
  97697. }
  97698. class TileHeader {
  97699. constructor(tileset, header, parentHeader, extendedId = '') {
  97700. _defineProperty(this, "tileset", void 0);
  97701. _defineProperty(this, "header", void 0);
  97702. _defineProperty(this, "id", void 0);
  97703. _defineProperty(this, "url", void 0);
  97704. _defineProperty(this, "parent", void 0);
  97705. _defineProperty(this, "refine", void 0);
  97706. _defineProperty(this, "type", void 0);
  97707. _defineProperty(this, "contentUrl", void 0);
  97708. _defineProperty(this, "lodMetricType", void 0);
  97709. _defineProperty(this, "lodMetricValue", void 0);
  97710. _defineProperty(this, "boundingVolume", void 0);
  97711. _defineProperty(this, "content", void 0);
  97712. _defineProperty(this, "contentState", void 0);
  97713. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  97714. _defineProperty(this, "children", void 0);
  97715. _defineProperty(this, "depth", void 0);
  97716. _defineProperty(this, "viewportIds", void 0);
  97717. _defineProperty(this, "transform", void 0);
  97718. _defineProperty(this, "extensions", void 0);
  97719. _defineProperty(this, "userData", void 0);
  97720. _defineProperty(this, "computedTransform", void 0);
  97721. _defineProperty(this, "hasEmptyContent", void 0);
  97722. _defineProperty(this, "hasTilesetContent", void 0);
  97723. _defineProperty(this, "traverser", void 0);
  97724. _defineProperty(this, "_cacheNode", void 0);
  97725. _defineProperty(this, "_frameNumber", void 0);
  97726. _defineProperty(this, "_lodJudge", void 0);
  97727. _defineProperty(this, "_expireDate", void 0);
  97728. _defineProperty(this, "_expiredContent", void 0);
  97729. _defineProperty(this, "_shouldRefine", void 0);
  97730. _defineProperty(this, "_distanceToCamera", void 0);
  97731. _defineProperty(this, "_centerZDepth", void 0);
  97732. _defineProperty(this, "_screenSpaceError", void 0);
  97733. _defineProperty(this, "_visibilityPlaneMask", void 0);
  97734. _defineProperty(this, "_visible", void 0);
  97735. _defineProperty(this, "_inRequestVolume", void 0);
  97736. _defineProperty(this, "_stackLength", void 0);
  97737. _defineProperty(this, "_selectionDepth", void 0);
  97738. _defineProperty(this, "_touchedFrame", void 0);
  97739. _defineProperty(this, "_visitedFrame", void 0);
  97740. _defineProperty(this, "_selectedFrame", void 0);
  97741. _defineProperty(this, "_requestedFrame", void 0);
  97742. _defineProperty(this, "_priority", void 0);
  97743. _defineProperty(this, "_contentBoundingVolume", void 0);
  97744. _defineProperty(this, "_viewerRequestVolume", void 0);
  97745. _defineProperty(this, "_initialTransform", void 0);
  97746. _defineProperty(this, "tilesetMatrix", void 0);//add
  97747. this.header = header;
  97748. this.tileset = tileset;
  97749. this.id = extendedId || header.id;
  97750. this.url = header.url;
  97751. this.parent = parentHeader;
  97752. this.refine = this._getRefine(header.refine);
  97753. this.type = header.type;
  97754. this.contentUrl = header.contentUrl;
  97755. this.lodMetricType = 'geometricError';
  97756. this.lodMetricValue = 0;
  97757. this.boundingVolume = null;
  97758. this.content = null;
  97759. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  97760. this.gpuMemoryUsageInBytes = 0;
  97761. this.children = [];
  97762. this.hasEmptyContent = false;
  97763. this.hasTilesetContent = false;
  97764. this.depth = 0;
  97765. this.viewportIds = [];
  97766. this.userData = {};
  97767. this.extensions = null;
  97768. this._priority = 0;
  97769. this._touchedFrame = 0;
  97770. this._visitedFrame = 0;
  97771. this._selectedFrame = 0;
  97772. this._requestedFrame = 0;
  97773. this._screenSpaceError = 0;
  97774. this._cacheNode = null;
  97775. this._frameNumber = null;
  97776. this._cacheNode = null;
  97777. this.traverser = new TilesetTraverser({});
  97778. this._shouldRefine = false;
  97779. this._distanceToCamera = 0;
  97780. this._centerZDepth = 0;
  97781. this._visible = undefined;
  97782. this._inRequestVolume = false;
  97783. this._stackLength = 0;
  97784. this._selectionDepth = 0;
  97785. this._initialTransform = new Matrix4$1();
  97786. this.transform = new Matrix4$1();
  97787. this._initializeLodMetric(header);
  97788. this._initializeTransforms(header);
  97789. this._initializeBoundingVolumes(header);
  97790. this._initializeContent(header);
  97791. this._initializeRenderingState(header);
  97792. this._lodJudge = null;
  97793. this._expireDate = null;
  97794. this._expiredContent = null;
  97795. Object.seal(this);
  97796. }
  97797. destroy() {
  97798. this.header = null;
  97799. }
  97800. isDestroyed() {
  97801. return this.header === null;
  97802. }
  97803. get selected() {
  97804. return this._selectedFrame === this.tileset._frameNumber;
  97805. }
  97806. get isVisible() {
  97807. return this._visible;
  97808. }
  97809. get isVisibleAndInRequestVolume() {
  97810. let v = /* this._visible && */this.tileset.visible && this._inRequestVolume; //用_updateBoundingVolume这个算的在相机靠近时不准确,容易缺块
  97811. if(window.tileVisi2)v = this._visible && v;
  97812. return v
  97813. }
  97814. get hasRenderContent() {
  97815. return !this.hasEmptyContent && !this.hasTilesetContent;
  97816. }
  97817. get hasChildren() {
  97818. return this.children.length > 0 || this.header.children && this.header.children.length > 0;
  97819. }
  97820. get contentReady() {
  97821. return this.contentState === TILE_CONTENT_STATE.READY || this.hasEmptyContent;
  97822. }
  97823. get contentAvailable() {
  97824. return Boolean(this.contentReady && this.hasRenderContent || this._expiredContent && !this.contentFailed);
  97825. }
  97826. get hasUnloadedContent() {
  97827. return this.hasRenderContent && this.contentUnloaded;
  97828. }
  97829. get contentUnloaded() {
  97830. return this.contentState === TILE_CONTENT_STATE.UNLOADED;
  97831. }
  97832. get contentExpired() {
  97833. return this.contentState === TILE_CONTENT_STATE.EXPIRED;
  97834. }
  97835. get contentFailed() {
  97836. return this.contentState === TILE_CONTENT_STATE.FAILED;
  97837. }
  97838. getScreenSpaceError(frameState, useParentLodMetric) {
  97839. switch (this.tileset.type) {
  97840. case TILESET_TYPE.I3S:
  97841. return getProjectedRadius(this, frameState);
  97842. case TILESET_TYPE.TILES3D:
  97843. return getTiles3DScreenSpaceError(this, frameState, useParentLodMetric);
  97844. default:
  97845. throw new Error('Unsupported tileset type');
  97846. }
  97847. }
  97848. _getPriority() {
  97849. const traverser = this.tileset._traverser;
  97850. const {
  97851. skipLevelOfDetail
  97852. } = traverser.options;
  97853. const maySkipTile = this.refine === TILE_REFINEMENT.ADD || skipLevelOfDetail;
  97854. if (maySkipTile && !this.isVisible && this._visible !== undefined) {
  97855. return -1;
  97856. }
  97857. if (this.tileset._frameNumber - this._touchedFrame >= 1) {
  97858. return -1;
  97859. }
  97860. if (this.contentState === TILE_CONTENT_STATE.UNLOADED) {
  97861. return -1;
  97862. }
  97863. const parent = this.parent;
  97864. const useParentScreenSpaceError = parent && (!maySkipTile || this._screenSpaceError === 0.0 || parent.hasTilesetContent);
  97865. const screenSpaceError = useParentScreenSpaceError ? parent._screenSpaceError : this._screenSpaceError;
  97866. const rootScreenSpaceError = traverser.root ? traverser.root._screenSpaceError : 0.0;
  97867. let v = Math.max(rootScreenSpaceError - screenSpaceError, 0);
  97868. if(!this._visible){
  97869. v = THREE.Math.clamp(v * 0.1, -0.9, 100);//xzw add 因为this._visible我也令其显示所以这里降低这些的优先级
  97870. }
  97871. return v
  97872. }
  97873. async loadContent() {
  97874. if (this.hasEmptyContent) {
  97875. return false;
  97876. }
  97877. if (this.content) {
  97878. return true;
  97879. }
  97880. const expired = this.contentExpired;
  97881. if (expired) {
  97882. this._expireDate = null;
  97883. }
  97884. this.contentState = TILE_CONTENT_STATE.LOADING;
  97885. const requestToken = await this.tileset._requestScheduler.scheduleRequest(this.id, this._getPriority.bind(this));
  97886. if (!requestToken) {
  97887. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  97888. return false;
  97889. }
  97890. try {
  97891. const contentUrl = this.tileset.getTileUrl(this.contentUrl);
  97892. const loader = this.tileset.loader;
  97893. const options = { ...this.tileset.loadOptions,
  97894. [loader.id]: { ...this.tileset.loadOptions[loader.id],
  97895. isTileset: this.type === 'json',
  97896. ...this._getLoaderSpecificOptions(loader.id)
  97897. }
  97898. };
  97899. this.content = await load(contentUrl, loader, options);
  97900. // !zeg改
  97901. if (this.tileset.options.maxDepth < this.depth) {
  97902. this.unloadContent();
  97903. return false
  97904. }
  97905. if (this.tileset.options.contentLoader) {
  97906. await this.tileset.options.contentLoader(this);
  97907. }
  97908. if (this._isTileset()) {
  97909. this.tileset._initializeTileHeaders(this.content, this);
  97910. }
  97911. this.contentState = TILE_CONTENT_STATE.READY;
  97912. this._onContentLoaded();
  97913. return true;
  97914. } catch (error) {
  97915. this.contentState = TILE_CONTENT_STATE.FAILED;
  97916. throw error;
  97917. } finally {
  97918. requestToken.done();
  97919. }
  97920. }
  97921. unloadContent() {
  97922. if (this.content && this.content.destroy) {
  97923. this.content.destroy();
  97924. }
  97925. this.content = null;
  97926. if (this.header.content && this.header.content.destroy) {
  97927. this.header.content.destroy();
  97928. }
  97929. this.header.content = null;
  97930. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  97931. return true;
  97932. }
  97933. updateVisibility(frameState, viewportIds) {
  97934. if (this._frameNumber === frameState.frameNumber) {
  97935. return;
  97936. }
  97937. const parent = this.parent;
  97938. const parentVisibilityPlaneMask = parent ? parent._visibilityPlaneMask : CullingVolume.MASK_INDETERMINATE;
  97939. if (this.tileset._traverser.options.updateTransforms) {
  97940. const parentTransform = parent ? parent.computedTransform : new Matrix4$1().elements; //this.tileset.modelMatrix; 改:去掉左乘modelMatrix
  97941. this._updateTransform(parentTransform);
  97942. }
  97943. this._distanceToCamera = this.distanceToTile(frameState);
  97944. this._screenSpaceError = this.getScreenSpaceError(frameState, false);
  97945. this._visibilityPlaneMask = this.visibility(frameState, parentVisibilityPlaneMask);
  97946. this._visible = this._visibilityPlaneMask !== CullingVolume.MASK_OUTSIDE;
  97947. this._inRequestVolume = this.insideViewerRequestVolume(frameState);
  97948. this._frameNumber = frameState.frameNumber;
  97949. this.viewportIds = viewportIds;
  97950. }
  97951. visibility(frameState, parentVisibilityPlaneMask) {
  97952. const {
  97953. cullingVolume
  97954. } = frameState;
  97955. const {
  97956. boundingVolume
  97957. } = this;
  97958. return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume, parentVisibilityPlaneMask);
  97959. }
  97960. contentVisibility() {
  97961. return true;
  97962. }
  97963. distanceToTile(frameState) {
  97964. const boundingVolume = this.boundingVolume;
  97965. return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position), 0));
  97966. }
  97967. cameraSpaceZDepth({
  97968. camera
  97969. }) {
  97970. const boundingVolume = this.boundingVolume;
  97971. scratchVector.subVectors(boundingVolume.center, camera.position);
  97972. return camera.direction.dot(scratchVector);
  97973. }
  97974. insideViewerRequestVolume(frameState) {
  97975. const viewerRequestVolume = this._viewerRequestVolume;
  97976. return !viewerRequestVolume || viewerRequestVolume.distanceSquaredTo(frameState.camera.position) <= 0;
  97977. }
  97978. updateExpiration() {
  97979. if (defined$2(this._expireDate) && this.contentReady && !this.hasEmptyContent) {
  97980. const now = Date.now();
  97981. if (Date.lessThan(this._expireDate, now)) {
  97982. this.contentState = TILE_CONTENT_STATE.EXPIRED;
  97983. this._expiredContent = this.content;
  97984. }
  97985. }
  97986. }
  97987. get extras() {
  97988. return this.header.extras;
  97989. }
  97990. _initializeLodMetric(header) {
  97991. if ('lodMetricType' in header) {
  97992. this.lodMetricType = header.lodMetricType;
  97993. } else {
  97994. this.lodMetricType = this.parent && this.parent.lodMetricType || this.tileset.lodMetricType;
  97995. console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");
  97996. }
  97997. if ('lodMetricValue' in header) {
  97998. this.lodMetricValue = header.lodMetricValue;
  97999. } else {
  98000. this.lodMetricValue = this.parent && this.parent.lodMetricValue || this.tileset.lodMetricValue;
  98001. console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');
  98002. }
  98003. }
  98004. _initializeTransforms(tileHeader) {
  98005. this.transform = tileHeader.transform ? new Matrix4$1(tileHeader.transform) : new Matrix4$1();
  98006. const parent = this.parent;
  98007. const tileset = this.tileset;
  98008. const parentTransform = parent && parent.computedTransform ? parent.computedTransform.clone() : new Matrix4$1().elements; // tileset.modelMatrix.clone(); 改:去掉左乘modelMatrix
  98009. this.computedTransform = new Matrix4$1(parentTransform).multiplyRight(this.transform);
  98010. const parentInitialTransform = parent && parent._initialTransform ? parent._initialTransform.clone() : new Matrix4$1();
  98011. this._initialTransform = new Matrix4$1(parentInitialTransform).multiplyRight(this.transform);
  98012. }
  98013. _initializeBoundingVolumes(tileHeader) {
  98014. this._contentBoundingVolume = null;
  98015. this._viewerRequestVolume = null;
  98016. this._updateBoundingVolume(tileHeader);
  98017. }
  98018. _initializeContent(tileHeader) {
  98019. this.content = {
  98020. _tileset: this.tileset,
  98021. _tile: this
  98022. };
  98023. this.hasEmptyContent = true;
  98024. this.contentState = TILE_CONTENT_STATE.UNLOADED;
  98025. this.hasTilesetContent = false;
  98026. if (tileHeader.contentUrl) {
  98027. this.content = null;
  98028. this.hasEmptyContent = false;
  98029. }
  98030. }
  98031. _initializeRenderingState(header) {
  98032. this.depth = header.level || (this.parent ? this.parent.depth + 1 : 0);
  98033. this._shouldRefine = false;
  98034. this._distanceToCamera = 0;
  98035. this._centerZDepth = 0;
  98036. this._screenSpaceError = 0;
  98037. this._visibilityPlaneMask = CullingVolume.MASK_INDETERMINATE;
  98038. this._visible = undefined;
  98039. this._inRequestVolume = false;
  98040. this._stackLength = 0;
  98041. this._selectionDepth = 0;
  98042. this._frameNumber = 0;
  98043. this._touchedFrame = 0;
  98044. this._visitedFrame = 0;
  98045. this._selectedFrame = 0;
  98046. this._requestedFrame = 0;
  98047. this._priority = 0.0;
  98048. }
  98049. _getRefine(refine) {
  98050. return refine || this.parent && this.parent.refine || TILE_REFINEMENT.REPLACE;
  98051. }
  98052. _isTileset() {
  98053. return this.contentUrl.indexOf('.json') !== -1;
  98054. }
  98055. _onContentLoaded() {
  98056. switch (this.content && this.content.type) {
  98057. case 'vctr':
  98058. case 'geom':
  98059. this.tileset._traverser.disableSkipLevelOfDetail = true;
  98060. break;
  98061. }
  98062. if (this._isTileset()) {
  98063. this.hasTilesetContent = true;
  98064. }
  98065. }
  98066. _updateBoundingVolume(header) {
  98067. let computedTransform = new Matrix4$1(this.tileset.modelMatrix).multiplyRight(this.computedTransform); //add
  98068. //console.log('_updateBoundingVolume computedTransform', this.tileset.modelMatrix, computedTransform)
  98069. this.boundingVolume = createBoundingVolume(header.boundingVolume, computedTransform/* this.computedTransform */, this.boundingVolume);
  98070. const content = header.content;
  98071. if (!content) {
  98072. return;
  98073. }
  98074. if (content.boundingVolume) {
  98075. this._contentBoundingVolume = createBoundingVolume(content.boundingVolume, computedTransform, this._contentBoundingVolume);
  98076. }
  98077. if (header.viewerRequestVolume) {
  98078. this._viewerRequestVolume = createBoundingVolume(header.viewerRequestVolume, computedTransform, this._viewerRequestVolume);
  98079. }
  98080. }
  98081. _updateTransform(parentTransform = new Matrix4$1()) {
  98082. const computedTransform = parentTransform.clone().multiplyRight(this.transform);
  98083. const didTransformChange = !computedTransform.equals(this.computedTransform) || !this.tilesetMatrix || !this.tilesetMatrix.equals(this.tileset.modelMatrix); //改 后面加了两个判断,为了在模型移动后更新_updateBoundingVolume
  98084. if (!didTransformChange) {
  98085. return;
  98086. }
  98087. this.tileset.modelMatrix;
  98088. this.computedTransform = computedTransform;
  98089. this.tilesetMatrix = this.tileset.modelMatrix; //add 标记
  98090. this._updateBoundingVolume(this.header);
  98091. }
  98092. _getLoaderSpecificOptions(loaderId) {
  98093. switch (loaderId) {
  98094. case 'i3s':
  98095. return { ...this.tileset.options.i3s,
  98096. tile: this.header,
  98097. tileset: this.tileset.tileset,
  98098. isTileHeader: false
  98099. };
  98100. case '3d-tiles':
  98101. case 'cesium-ion':
  98102. default:
  98103. return get3dTilesOptions(this.tileset.tileset);
  98104. }
  98105. }
  98106. }
  98107. class Tileset3DTraverser extends TilesetTraverser {
  98108. compareDistanceToCamera(a, b) {
  98109. return b._distanceToCamera === 0 && a._distanceToCamera === 0 ? b._centerZDepth - a._centerZDepth : b._distanceToCamera - a._distanceToCamera;
  98110. }
  98111. updateTileVisibility(tile, frameState) {
  98112. super.updateTileVisibility(tile, frameState);
  98113. if (!tile.isVisibleAndInRequestVolume) {
  98114. return;
  98115. }
  98116. const hasChildren = tile.children.length > 0;
  98117. if (tile.hasTilesetContent && hasChildren) {
  98118. const firstChild = tile.children[0];
  98119. this.updateTileVisibility(firstChild, frameState);
  98120. tile._visible = firstChild._visible;
  98121. return;
  98122. }
  98123. if (this.meetsScreenSpaceErrorEarly(tile, frameState)) {
  98124. tile._visible = false;
  98125. return;
  98126. }
  98127. const replace = tile.refine === TILE_REFINEMENT.REPLACE;
  98128. const useOptimization = tile._optimChildrenWithinParent === TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;
  98129. if (replace && useOptimization && hasChildren) {
  98130. if (!this.anyChildrenVisible(tile, frameState)) {
  98131. tile._visible = false;
  98132. return;
  98133. }
  98134. }
  98135. }
  98136. meetsScreenSpaceErrorEarly(tile, frameState) {
  98137. const {
  98138. parent
  98139. } = tile;
  98140. if (!parent || parent.hasTilesetContent || parent.refine !== TILE_REFINEMENT.ADD) {
  98141. return false;
  98142. }
  98143. return !this.shouldRefine(tile, frameState, true);
  98144. }
  98145. }
  98146. const STATUS = {
  98147. REQUESTED: 'REQUESTED',
  98148. COMPLETED: 'COMPLETED',
  98149. ERROR: 'ERROR'
  98150. };
  98151. class I3STileManager {
  98152. constructor() {
  98153. _defineProperty(this, "_statusMap", void 0);
  98154. this._statusMap = {};
  98155. }
  98156. add(request, key, callback, frameState) {
  98157. if (!this._statusMap[key]) {
  98158. this._statusMap[key] = {
  98159. request,
  98160. callback,
  98161. key,
  98162. frameState,
  98163. status: STATUS.REQUESTED
  98164. };
  98165. request().then(data => {
  98166. this._statusMap[key].status = STATUS.COMPLETED;
  98167. this._statusMap[key].callback(data, frameState);
  98168. }).catch(error => {
  98169. this._statusMap[key].status = STATUS.ERROR;
  98170. callback(error);
  98171. });
  98172. }
  98173. }
  98174. update(key, frameState) {
  98175. if (this._statusMap[key]) {
  98176. this._statusMap[key].frameState = frameState;
  98177. }
  98178. }
  98179. find(key) {
  98180. return this._statusMap[key];
  98181. }
  98182. }
  98183. class I3STilesetTraverser extends TilesetTraverser {
  98184. constructor(options) {
  98185. super(options);
  98186. _defineProperty(this, "_tileManager", void 0);
  98187. this._tileManager = new I3STileManager();
  98188. }
  98189. shouldRefine(tile, frameState) {
  98190. tile._lodJudge = getLodStatus(tile, frameState);
  98191. return tile._lodJudge === 'DIG';
  98192. }
  98193. updateChildTiles(tile, frameState) {
  98194. const children = tile.header.children || [];
  98195. const childTiles = tile.children;
  98196. const tileset = tile.tileset;
  98197. for (const child of children) {
  98198. const extendedId = "".concat(child.id, "-").concat(frameState.viewport.id);
  98199. const childTile = childTiles && childTiles.find(t => t.id === extendedId);
  98200. if (!childTile) {
  98201. let request = () => this._loadTile(child.id, tileset);
  98202. const cachedRequest = this._tileManager.find(extendedId);
  98203. if (!cachedRequest) {
  98204. if (tileset.tileset.nodePages) {
  98205. request = () => tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);
  98206. }
  98207. this._tileManager.add(request, extendedId, header => this._onTileLoad(header, tile, extendedId), frameState);
  98208. } else {
  98209. this._tileManager.update(extendedId, frameState);
  98210. }
  98211. } else if (childTile) {
  98212. this.updateTile(childTile, frameState);
  98213. }
  98214. }
  98215. return false;
  98216. }
  98217. async _loadTile(nodeId, tileset) {
  98218. const {
  98219. loader
  98220. } = tileset;
  98221. const nodeUrl = tileset.getTileUrl("".concat(tileset.url, "/nodes/").concat(nodeId));
  98222. const options = { ...tileset.loadOptions,
  98223. i3s: { ...tileset.loadOptions.i3s,
  98224. isTileHeader: true,
  98225. loadContent: false
  98226. }
  98227. };
  98228. return await load(nodeUrl, loader, options);
  98229. }
  98230. _onTileLoad(header, tile, extendedId) {
  98231. const childTile = new TileHeader(tile.tileset, header, tile, extendedId);
  98232. tile.children.push(childTile);
  98233. const frameState = this._tileManager.find(childTile.id).frameState;
  98234. this.updateTile(childTile, frameState);
  98235. if (this._frameNumber === frameState.frameNumber) {
  98236. this.executeTraversal(childTile, frameState);
  98237. }
  98238. }
  98239. }
  98240. const DEFAULT_PROPS = {
  98241. description: '',
  98242. ellipsoid: Ellipsoid.WGS84,
  98243. modelMatrix: new Matrix4$1(),
  98244. throttleRequests: true,
  98245. maxRequests: 64,
  98246. maximumMemoryUsage: 32,
  98247. onTileLoad: () => {},
  98248. onTileUnload: () => {},
  98249. onTileError: () => {},
  98250. onTraversalComplete: selectedTiles => selectedTiles,
  98251. contentLoader: undefined,
  98252. viewDistanceScale: 1.0,
  98253. maximumScreenSpaceError: 8,
  98254. loadTiles: true,
  98255. updateTransforms: true,
  98256. viewportTraversersMap: null,
  98257. loadOptions: {
  98258. fetch: {}
  98259. },
  98260. attributions: [],
  98261. basePath: '',
  98262. i3s: {}
  98263. };
  98264. const TILES_TOTAL = 'Tiles In Tileset(s)';
  98265. const TILES_IN_MEMORY = 'Tiles In Memory';
  98266. const TILES_IN_VIEW = 'Tiles In View';
  98267. const TILES_RENDERABLE = 'Tiles To Render';
  98268. const TILES_LOADED = 'Tiles Loaded';
  98269. const TILES_LOADING = 'Tiles Loading';
  98270. const TILES_UNLOADED = 'Tiles Unloaded';
  98271. const TILES_LOAD_FAILED = 'Failed Tile Loads';
  98272. const POINTS_COUNT = 'Points';
  98273. const TILES_GPU_MEMORY = 'Tile Memory Use';
  98274. let tilesetSid = 0;//add
  98275. class Tileset3D extends EventDispatcher{//xzw add EventDispatcher
  98276. constructor(json, options) {
  98277. super();
  98278. _defineProperty(this, "options", void 0);
  98279. _defineProperty(this, "loadOptions", void 0);
  98280. _defineProperty(this, "type", void 0);
  98281. _defineProperty(this, "tileset", void 0);
  98282. _defineProperty(this, "loader", void 0);
  98283. _defineProperty(this, "url", void 0);
  98284. _defineProperty(this, "basePath", void 0);
  98285. _defineProperty(this, "modelMatrix", void 0);
  98286. _defineProperty(this, "ellipsoid", void 0);
  98287. _defineProperty(this, "lodMetricType", void 0);
  98288. _defineProperty(this, "lodMetricValue", void 0);
  98289. _defineProperty(this, "refine", void 0);
  98290. _defineProperty(this, "root", void 0);
  98291. _defineProperty(this, "roots", void 0);
  98292. _defineProperty(this, "asset", void 0);
  98293. _defineProperty(this, "description", void 0);
  98294. _defineProperty(this, "properties", void 0);
  98295. _defineProperty(this, "extras", void 0);
  98296. _defineProperty(this, "attributions", void 0);
  98297. _defineProperty(this, "credits", void 0);
  98298. _defineProperty(this, "stats", void 0);
  98299. _defineProperty(this, "traverseCounter", void 0);
  98300. _defineProperty(this, "geometricError", void 0);
  98301. _defineProperty(this, "selectedTiles", void 0);
  98302. _defineProperty(this, "cartographicCenter", void 0);
  98303. _defineProperty(this, "cartesianCenter", void 0);
  98304. _defineProperty(this, "zoom", void 0);
  98305. _defineProperty(this, "boundingVolume", void 0);
  98306. _defineProperty(this, "gpuMemoryUsageInBytes", void 0);
  98307. _defineProperty(this, "dynamicScreenSpaceErrorComputedDensity", void 0);
  98308. _defineProperty(this, "_traverser", void 0);
  98309. _defineProperty(this, "_cache", void 0);
  98310. _defineProperty(this, "_requestScheduler", void 0);
  98311. _defineProperty(this, "_frameNumber", void 0);
  98312. _defineProperty(this, "_queryParamsString", void 0);
  98313. _defineProperty(this, "_queryParams", void 0);
  98314. _defineProperty(this, "_extensionsUsed", void 0);
  98315. _defineProperty(this, "_tiles", void 0);
  98316. _defineProperty(this, "_pendingCount", void 0);
  98317. _defineProperty(this, "lastUpdatedVieports", void 0);
  98318. _defineProperty(this, "_requestedTiles", void 0);
  98319. _defineProperty(this, "_emptyTiles", void 0);
  98320. _defineProperty(this, "frameStateData", void 0);
  98321. _defineProperty(this, "maximumMemoryUsage", void 0);
  98322. _defineProperty(this, "visible", true);//add
  98323. assert$7(json);
  98324. this.options = { ...DEFAULT_PROPS,
  98325. ...options
  98326. };
  98327. this.tileset = json;
  98328. this.loader = json.loader;
  98329. this.type = json.type;
  98330. this.url = json.url;
  98331. this.basePath = json.basePath || dirname(this.url);
  98332. this.modelMatrix = this.options.modelMatrix;
  98333. this.ellipsoid = this.options.ellipsoid;
  98334. this.lodMetricType = json.lodMetricType;
  98335. this.lodMetricValue = json.lodMetricValue;
  98336. this.refine = json.root.refine;
  98337. this.loadOptions = this.options.loadOptions || {};
  98338. this.root = null;
  98339. this.roots = {};
  98340. this.cartographicCenter = null;
  98341. this.cartesianCenter = null;
  98342. this.zoom = 1;
  98343. this.boundingVolume = null;
  98344. this.traverseCounter = 0;
  98345. this.geometricError = 0;
  98346. this._traverser = this._initializeTraverser();
  98347. this._cache = new TilesetCache();
  98348. this._requestScheduler = new RequestScheduler({
  98349. throttleRequests: this.options.throttleRequests,
  98350. maxRequests: this.options.maxRequests
  98351. });
  98352. this._frameNumber = 0;
  98353. this._pendingCount = 0;
  98354. this._tiles = {};
  98355. this.selectedTiles = [];
  98356. this._emptyTiles = [];
  98357. this._requestedTiles = [];
  98358. this.frameStateData = {};
  98359. this.lastUpdatedVieports = null;
  98360. this._queryParams = {};
  98361. this._queryParamsString = '';
  98362. this.maximumMemoryUsage = this.options.maximumMemoryUsage || 32;
  98363. this.gpuMemoryUsageInBytes = 0;
  98364. this.stats = new Stats$1({
  98365. id: this.url
  98366. });
  98367. this._initializeStats();
  98368. this._extensionsUsed = undefined;
  98369. this.dynamicScreenSpaceErrorComputedDensity = 0.0;
  98370. this.extras = null;
  98371. this.asset = {};
  98372. this.credits = {};
  98373. this.description = this.options.description || '';
  98374. this._initializeTileSet(json);
  98375. }
  98376. destroy() {
  98377. this._destroy();
  98378. }
  98379. isLoaded() {
  98380. return this._pendingCount === 0 && this._frameNumber !== 0;
  98381. }
  98382. get tiles() {
  98383. return Object.values(this._tiles);
  98384. }
  98385. get frameNumber() {
  98386. return this._frameNumber;
  98387. }
  98388. get queryParams() {
  98389. if (!this._queryParamsString) {
  98390. this._queryParamsString = getQueryParamString(this._queryParams);
  98391. }
  98392. return this._queryParamsString;
  98393. }
  98394. setProps(props) {
  98395. this.options = { ...this.options,
  98396. ...props
  98397. };
  98398. }
  98399. setOptions(options) {
  98400. this.options = { ...this.options,
  98401. ...options
  98402. };
  98403. }
  98404. getTileUrl(tilePath) {
  98405. const isDataUrl = tilePath.startsWith('data:');
  98406. tilePath = Potree.Common.dealURL(tilePath); //add 去除'+'
  98407. if (isDataUrl) {
  98408. return tilePath;
  98409. }
  98410. return "".concat(tilePath).concat(this.queryParams);
  98411. }
  98412. hasExtension(extensionName) {
  98413. return Boolean(this._extensionsUsed && this._extensionsUsed.indexOf(extensionName) > -1);
  98414. }
  98415. update(viewports) {
  98416. if ('loadTiles' in this.options && !this.options.loadTiles) {
  98417. return;
  98418. }
  98419. if (this.traverseCounter > 0) {
  98420. return;
  98421. }
  98422. if (!viewports && this.lastUpdatedVieports) {
  98423. viewports = this.lastUpdatedVieports;
  98424. } else {
  98425. this.lastUpdatedVieports = viewports;
  98426. }
  98427. if (!(viewports instanceof Array)) {
  98428. viewports = [viewports];
  98429. }
  98430. this._cache.reset();
  98431. this._frameNumber++;
  98432. this.traverseCounter = viewports.length;
  98433. const viewportsToTraverse = [];
  98434. for (const viewport of viewports) {
  98435. const id = viewport.id;
  98436. if (this._needTraverse(id)) {
  98437. viewportsToTraverse.push(id);
  98438. } else {
  98439. this.traverseCounter--;
  98440. }
  98441. }
  98442. for (const viewport of viewports) {
  98443. const id = viewport.id;
  98444. if (!this.roots[id]) {
  98445. this.roots[id] = this._initializeTileHeaders(this.tileset, null);
  98446. }
  98447. if (!viewportsToTraverse.includes(id)) {
  98448. continue;
  98449. }
  98450. const frameState = getFrameState(viewport, this._frameNumber);
  98451. this._traverser.traverse(this.roots[id], frameState, this.options);
  98452. }
  98453. }
  98454. _needTraverse(viewportId) {
  98455. let traverserId = viewportId;
  98456. if (this.options.viewportTraversersMap) {
  98457. traverserId = this.options.viewportTraversersMap[viewportId];
  98458. }
  98459. if (traverserId !== viewportId) {
  98460. return false;
  98461. }
  98462. return true;
  98463. }
  98464. _onTraversalEnd(frameState) {
  98465. const id = frameState.viewport.id;
  98466. if (!this.frameStateData[id]) {
  98467. this.frameStateData[id] = {
  98468. selectedTiles: [],
  98469. _requestedTiles: [],
  98470. _emptyTiles: []
  98471. };
  98472. }
  98473. const currentFrameStateData = this.frameStateData[id];
  98474. const selectedTiles = Object.values(this._traverser.selectedTiles);
  98475. currentFrameStateData.selectedTiles = selectedTiles;
  98476. currentFrameStateData._requestedTiles = Object.values(this._traverser.requestedTiles);
  98477. currentFrameStateData._emptyTiles = Object.values(this._traverser.emptyTiles);
  98478. this.traverseCounter--;
  98479. if (this.traverseCounter > 0) {
  98480. return;
  98481. }
  98482. this._updateTiles();
  98483. }
  98484. _updateTiles() {
  98485. this.selectedTiles = [];
  98486. this._requestedTiles = [];
  98487. this._emptyTiles = [];
  98488. for (const frameStateKey in this.frameStateData) {
  98489. const frameStateDataValue = this.frameStateData[frameStateKey];
  98490. this.selectedTiles = this.selectedTiles.concat(frameStateDataValue.selectedTiles);
  98491. this._requestedTiles = this._requestedTiles.concat(frameStateDataValue._requestedTiles);
  98492. this._emptyTiles = this._emptyTiles.concat(frameStateDataValue._emptyTiles);
  98493. }
  98494. this.selectedTiles = this.options.onTraversalComplete(this.selectedTiles);
  98495. for (const tile of this.selectedTiles) {
  98496. this._tiles[tile.id] = tile;
  98497. }
  98498. this._loadTiles();
  98499. this._unloadTiles();
  98500. this._updateStats();
  98501. }
  98502. _tilesChanged(oldSelectedTiles, selectedTiles) {
  98503. if (oldSelectedTiles.length !== selectedTiles.length) {
  98504. return true;
  98505. }
  98506. const set1 = new Set(oldSelectedTiles.map(t => t.id));
  98507. const set2 = new Set(selectedTiles.map(t => t.id));
  98508. let changed = oldSelectedTiles.filter(x => !set2.has(x.id)).length > 0;
  98509. changed = changed || selectedTiles.filter(x => !set1.has(x.id)).length > 0;
  98510. return changed;
  98511. }
  98512. _loadTiles() {
  98513. for (const tile of this._requestedTiles) {
  98514. if (tile.contentUnloaded) {
  98515. this._loadTile(tile);
  98516. }
  98517. }
  98518. }
  98519. _unloadTiles() {
  98520. this._cache.unloadTiles(this, (tileset, tile) => tileset._unloadTile(tile));
  98521. }
  98522. _updateStats() {
  98523. let tilesRenderable = 0;
  98524. let pointsRenderable = 0;
  98525. for (const tile of this.selectedTiles) {
  98526. if (tile.contentAvailable && tile.content) {
  98527. tilesRenderable++;
  98528. if (tile.content.pointCount) {
  98529. pointsRenderable += tile.content.pointCount;
  98530. }
  98531. }
  98532. }
  98533. this.stats.get(TILES_IN_VIEW).count = this.selectedTiles.length;
  98534. this.stats.get(TILES_RENDERABLE).count = tilesRenderable;
  98535. this.stats.get(POINTS_COUNT).count = pointsRenderable;
  98536. }
  98537. _initializeTileSet(tilesetJson) {
  98538. this.root = this._initializeTileHeaders(tilesetJson, null);
  98539. if (this.type === TILESET_TYPE.TILES3D) {
  98540. this._initializeCesiumTileset(tilesetJson);
  98541. }
  98542. if (this.type === TILESET_TYPE.I3S) {
  98543. this._initializeI3STileset();
  98544. }
  98545. this._calculateViewProps();
  98546. }
  98547. _calculateViewProps() {
  98548. const root = this.root;
  98549. assert$7(root);
  98550. const {
  98551. center
  98552. } = root.boundingVolume;
  98553. if (!center) {
  98554. console.warn('center was not pre-calculated for the root tile');
  98555. this.cartographicCenter = new Vector3$1();
  98556. this.zoom = 1;
  98557. return;
  98558. }
  98559. this.cartographicCenter = Ellipsoid.WGS84.cartesianToCartographic(center, new Vector3$1());
  98560. this.cartesianCenter = center;
  98561. this.zoom = getZoomFromBoundingVolume(root.boundingVolume);
  98562. }
  98563. _initializeStats() {
  98564. this.stats.get(TILES_TOTAL);
  98565. this.stats.get(TILES_LOADING);
  98566. this.stats.get(TILES_IN_MEMORY);
  98567. this.stats.get(TILES_IN_VIEW);
  98568. this.stats.get(TILES_RENDERABLE);
  98569. this.stats.get(TILES_LOADED);
  98570. this.stats.get(TILES_UNLOADED);
  98571. this.stats.get(TILES_LOAD_FAILED);
  98572. this.stats.get(POINTS_COUNT, 'memory');
  98573. this.stats.get(TILES_GPU_MEMORY, 'memory');
  98574. }
  98575. _initializeTileHeaders(tilesetJson, parentTileHeader) {
  98576. const rootTile = new TileHeader(this, tilesetJson.root, parentTileHeader, parentTileHeader == void 0 && 'root_'+tilesetSid++);
  98577. if (parentTileHeader) {
  98578. parentTileHeader.children.push(rootTile);
  98579. rootTile.depth = parentTileHeader.depth + 1;
  98580. }
  98581. if (this.type === TILESET_TYPE.TILES3D) {
  98582. const stack = [];
  98583. stack.push(rootTile);
  98584. while (stack.length > 0) {
  98585. const tile = stack.pop();
  98586. this.stats.get(TILES_TOTAL).incrementCount();
  98587. const children = tile.header.children || [];
  98588. // !zeg改
  98589. if(tile.depth < this.options.maxDepth){
  98590. for (const childHeader of children) {
  98591. const childTile = new TileHeader(this, childHeader, tile);
  98592. tile.children.push(childTile);
  98593. childTile.depth = tile.depth + 1;
  98594. stack.push(childTile);
  98595. }
  98596. }
  98597. window.maxDepth = Math.max(window.maxDepth||0,tile.depth);
  98598. }
  98599. }
  98600. return rootTile;
  98601. }
  98602. _initializeTraverser() {
  98603. let TraverserClass;
  98604. const type = this.type;
  98605. switch (type) {
  98606. case TILESET_TYPE.TILES3D:
  98607. TraverserClass = Tileset3DTraverser;
  98608. break;
  98609. case TILESET_TYPE.I3S:
  98610. TraverserClass = I3STilesetTraverser;
  98611. break;
  98612. default:
  98613. TraverserClass = TilesetTraverser;
  98614. }
  98615. return new TraverserClass({
  98616. basePath: this.basePath,
  98617. onTraversalEnd: this._onTraversalEnd.bind(this)
  98618. });
  98619. }
  98620. _destroyTileHeaders(parentTile) {
  98621. this._destroySubtree(parentTile);
  98622. }
  98623. async _loadTile(tile) {
  98624. let loaded;
  98625. try {
  98626. this._onStartTileLoading();
  98627. loaded = await tile.loadContent();
  98628. } catch (error) {
  98629. this._onTileLoadError(tile, error);
  98630. } finally {
  98631. this._onEndTileLoading(tile);//
  98632. this._onTileLoad(tile, loaded);
  98633. }
  98634. }
  98635. _onTileLoadError(tile, error) {
  98636. this.stats.get(TILES_LOAD_FAILED).incrementCount();
  98637. const message = error.message || error.toString();
  98638. const url = tile.url;
  98639. console.error("A 3D tile failed to load: ".concat(tile.url, " ").concat(message));
  98640. this.options.onTileError(tile, message, url);
  98641. }
  98642. _onTileLoad(tile, loaded) {
  98643. if (!loaded) {
  98644. return;
  98645. }
  98646. if (tile && tile.content) {
  98647. calculateTransformProps(tile, tile.content);
  98648. }
  98649. this._addTileToCache(tile);
  98650. this.options.onTileLoad(tile);
  98651. }
  98652. _onStartTileLoading() {
  98653. this._pendingCount++;
  98654. this.stats.get(TILES_LOADING).incrementCount();
  98655. }
  98656. _onEndTileLoading(tile) {
  98657. this._pendingCount--;
  98658. this.stats.get(TILES_LOADING).decrementCount();
  98659. this.dispatchEvent({type:'endTileLoading', tile, loadingCount: this._pendingCount }); // !zeg改
  98660. }
  98661. _addTileToCache(tile) {
  98662. this._cache.add(this, tile, tileset => tileset._updateCacheStats(tile));
  98663. }
  98664. _updateCacheStats(tile) {
  98665. this.stats.get(TILES_LOADED).incrementCount();
  98666. this.stats.get(TILES_IN_MEMORY).incrementCount();
  98667. this.gpuMemoryUsageInBytes += tile.content.byteLength || 0;
  98668. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  98669. }
  98670. _unloadTile(tile) {
  98671. this.gpuMemoryUsageInBytes -= tile.content && tile.content.byteLength || 0;
  98672. this.stats.get(TILES_IN_MEMORY).decrementCount();
  98673. this.stats.get(TILES_UNLOADED).incrementCount();
  98674. this.stats.get(TILES_GPU_MEMORY).count = this.gpuMemoryUsageInBytes;
  98675. this.options.onTileUnload(tile);
  98676. tile.unloadContent();
  98677. }
  98678. _destroy() {
  98679. const stack = [];
  98680. if (this.root) {
  98681. stack.push(this.root);
  98682. }
  98683. while (stack.length > 0) {
  98684. const tile = stack.pop();
  98685. for (const child of tile.children) {
  98686. stack.push(child);
  98687. }
  98688. this._destroyTile(tile);
  98689. }
  98690. this.root = null;
  98691. }
  98692. _destroySubtree(tile) {
  98693. const root = tile;
  98694. const stack = [];
  98695. stack.push(root);
  98696. while (stack.length > 0) {
  98697. tile = stack.pop();
  98698. for (const child of tile.children) {
  98699. stack.push(child);
  98700. }
  98701. if (tile !== root) {
  98702. this._destroyTile(tile);
  98703. }
  98704. }
  98705. root.children = [];
  98706. }
  98707. _destroyTile(tile) {
  98708. this._cache.unloadTile(this, tile);
  98709. this._unloadTile(tile);
  98710. tile.destroy();
  98711. }
  98712. _initializeCesiumTileset(tilesetJson) {
  98713. this.asset = tilesetJson.asset;
  98714. if (!this.asset) {
  98715. throw new Error('Tileset must have an asset property.');
  98716. }
  98717. if (this.asset.version !== '0.0' && this.asset.version !== '1.0') {
  98718. throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');
  98719. }
  98720. if ('tilesetVersion' in this.asset) {
  98721. this._queryParams.v = this.asset.tilesetVersion;
  98722. }
  98723. this.credits = {
  98724. attributions: this.options.attributions || []
  98725. };
  98726. this.description = this.options.description || '';
  98727. this.properties = tilesetJson.properties;
  98728. this.geometricError = tilesetJson.geometricError;
  98729. this._extensionsUsed = tilesetJson.extensionsUsed;
  98730. this.extras = tilesetJson.extras;
  98731. }
  98732. _initializeI3STileset() {
  98733. if (this.loadOptions.i3s && 'token' in this.loadOptions.i3s) {
  98734. this._queryParams.token = this.loadOptions.i3s.token;
  98735. }
  98736. }
  98737. }
  98738. function getQueryParamString(queryParams) {
  98739. const queryParamStrings = [];
  98740. for (const key of Object.keys(queryParams)) {
  98741. queryParamStrings.push("".concat(key, "=").concat(queryParams[key]));
  98742. }
  98743. switch (queryParamStrings.length) {
  98744. case 0:
  98745. return '';
  98746. case 1:
  98747. return "?".concat(queryParamStrings[0]);
  98748. default:
  98749. return "?".concat(queryParamStrings.join('&'));
  98750. }
  98751. }
  98752. const VERSION$5 = "3.1.4" ;
  98753. const TILE3D_TYPE = {
  98754. COMPOSITE: 'cmpt',
  98755. POINT_CLOUD: 'pnts',
  98756. BATCHED_3D_MODEL: 'b3dm',
  98757. INSTANCED_3D_MODEL: 'i3dm',
  98758. GEOMETRY: 'geom',
  98759. VECTOR: 'vect',
  98760. GLTF: 'glTF'
  98761. };
  98762. function getStringFromArrayBuffer(arrayBuffer, byteOffset, byteLength) {
  98763. assert$7(arrayBuffer instanceof ArrayBuffer);
  98764. const textDecoder = new TextDecoder('utf8');
  98765. const typedArray = new Uint8Array(arrayBuffer, byteOffset, byteLength);
  98766. const string = textDecoder.decode(typedArray);
  98767. return string;
  98768. }
  98769. function getMagicString$1(arrayBuffer, byteOffset = 0) {
  98770. const dataView = new DataView(arrayBuffer);
  98771. 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)));
  98772. }
  98773. const VERSION$4 = "3.1.4" ;
  98774. const DEFAULT_DRACO_OPTIONS = {
  98775. draco: {
  98776. decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js',
  98777. libraryPath: 'libs/',
  98778. extraAttributes: {},
  98779. attributeNameEntry: undefined
  98780. }
  98781. };
  98782. const DracoLoader$1 = {
  98783. name: 'Draco',
  98784. id: 'draco',
  98785. module: 'draco',
  98786. shapes: ['mesh'],
  98787. version: VERSION$4,
  98788. worker: true,
  98789. extensions: ['drc'],
  98790. mimeTypes: ['application/octet-stream'],
  98791. binary: true,
  98792. tests: ['DRACO'],
  98793. options: DEFAULT_DRACO_OPTIONS
  98794. };
  98795. function getMeshBoundingBox(attributes) {
  98796. let minX = Infinity;
  98797. let minY = Infinity;
  98798. let minZ = Infinity;
  98799. let maxX = -Infinity;
  98800. let maxY = -Infinity;
  98801. let maxZ = -Infinity;
  98802. const positions = attributes.POSITION ? attributes.POSITION.value : [];
  98803. const len = positions && positions.length;
  98804. for (let i = 0; i < len; i += 3) {
  98805. const x = positions[i];
  98806. const y = positions[i + 1];
  98807. const z = positions[i + 2];
  98808. minX = x < minX ? x : minX;
  98809. minY = y < minY ? y : minY;
  98810. minZ = z < minZ ? z : minZ;
  98811. maxX = x > maxX ? x : maxX;
  98812. maxY = y > maxY ? y : maxY;
  98813. maxZ = z > maxZ ? z : maxZ;
  98814. }
  98815. return [[minX, minY, minZ], [maxX, maxY, maxZ]];
  98816. }
  98817. function assert$3(condition, message) {
  98818. if (!condition) {
  98819. throw new Error(message || 'loader assertion failed.');
  98820. }
  98821. }
  98822. class Schema {
  98823. constructor(fields, metadata) {
  98824. _defineProperty(this, "fields", void 0);
  98825. _defineProperty(this, "metadata", void 0);
  98826. assert$3(Array.isArray(fields));
  98827. checkNames(fields);
  98828. this.fields = fields;
  98829. this.metadata = metadata || new Map();
  98830. }
  98831. compareTo(other) {
  98832. if (this.metadata !== other.metadata) {
  98833. return false;
  98834. }
  98835. if (this.fields.length !== other.fields.length) {
  98836. return false;
  98837. }
  98838. for (let i = 0; i < this.fields.length; ++i) {
  98839. if (!this.fields[i].compareTo(other.fields[i])) {
  98840. return false;
  98841. }
  98842. }
  98843. return true;
  98844. }
  98845. select(...columnNames) {
  98846. const nameMap = Object.create(null);
  98847. for (const name of columnNames) {
  98848. nameMap[name] = true;
  98849. }
  98850. const selectedFields = this.fields.filter(field => nameMap[field.name]);
  98851. return new Schema(selectedFields, this.metadata);
  98852. }
  98853. selectAt(...columnIndices) {
  98854. const selectedFields = columnIndices.map(index => this.fields[index]).filter(Boolean);
  98855. return new Schema(selectedFields, this.metadata);
  98856. }
  98857. assign(schemaOrFields) {
  98858. let fields;
  98859. let metadata = this.metadata;
  98860. if (schemaOrFields instanceof Schema) {
  98861. const otherSchema = schemaOrFields;
  98862. fields = otherSchema.fields;
  98863. metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);
  98864. } else {
  98865. fields = schemaOrFields;
  98866. }
  98867. const fieldMap = Object.create(null);
  98868. for (const field of this.fields) {
  98869. fieldMap[field.name] = field;
  98870. }
  98871. for (const field of fields) {
  98872. fieldMap[field.name] = field;
  98873. }
  98874. const mergedFields = Object.values(fieldMap);
  98875. return new Schema(mergedFields, metadata);
  98876. }
  98877. }
  98878. function checkNames(fields) {
  98879. const usedNames = {};
  98880. for (const field of fields) {
  98881. if (usedNames[field.name]) {
  98882. console.warn('Schema: duplicated field name', field.name, field);
  98883. }
  98884. usedNames[field.name] = true;
  98885. }
  98886. }
  98887. function mergeMaps(m1, m2) {
  98888. return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
  98889. }
  98890. class Field {
  98891. constructor(name, type, nullable = false, metadata = new Map()) {
  98892. _defineProperty(this, "name", void 0);
  98893. _defineProperty(this, "type", void 0);
  98894. _defineProperty(this, "nullable", void 0);
  98895. _defineProperty(this, "metadata", void 0);
  98896. this.name = name;
  98897. this.type = type;
  98898. this.nullable = nullable;
  98899. this.metadata = metadata;
  98900. }
  98901. get typeId() {
  98902. return this.type && this.type.typeId;
  98903. }
  98904. clone() {
  98905. return new Field(this.name, this.type, this.nullable, this.metadata);
  98906. }
  98907. compareTo(other) {
  98908. return this.name === other.name && this.type === other.type && this.nullable === other.nullable && this.metadata === other.metadata;
  98909. }
  98910. toString() {
  98911. return "".concat(this.type).concat(this.nullable ? ', nullable' : '').concat(this.metadata ? ", metadata: ".concat(this.metadata) : '');
  98912. }
  98913. }
  98914. let Type$1;
  98915. (function (Type) {
  98916. Type[Type["NONE"] = 0] = "NONE";
  98917. Type[Type["Null"] = 1] = "Null";
  98918. Type[Type["Int"] = 2] = "Int";
  98919. Type[Type["Float"] = 3] = "Float";
  98920. Type[Type["Binary"] = 4] = "Binary";
  98921. Type[Type["Utf8"] = 5] = "Utf8";
  98922. Type[Type["Bool"] = 6] = "Bool";
  98923. Type[Type["Decimal"] = 7] = "Decimal";
  98924. Type[Type["Date"] = 8] = "Date";
  98925. Type[Type["Time"] = 9] = "Time";
  98926. Type[Type["Timestamp"] = 10] = "Timestamp";
  98927. Type[Type["Interval"] = 11] = "Interval";
  98928. Type[Type["List"] = 12] = "List";
  98929. Type[Type["Struct"] = 13] = "Struct";
  98930. Type[Type["Union"] = 14] = "Union";
  98931. Type[Type["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  98932. Type[Type["FixedSizeList"] = 16] = "FixedSizeList";
  98933. Type[Type["Map"] = 17] = "Map";
  98934. Type[Type["Dictionary"] = -1] = "Dictionary";
  98935. Type[Type["Int8"] = -2] = "Int8";
  98936. Type[Type["Int16"] = -3] = "Int16";
  98937. Type[Type["Int32"] = -4] = "Int32";
  98938. Type[Type["Int64"] = -5] = "Int64";
  98939. Type[Type["Uint8"] = -6] = "Uint8";
  98940. Type[Type["Uint16"] = -7] = "Uint16";
  98941. Type[Type["Uint32"] = -8] = "Uint32";
  98942. Type[Type["Uint64"] = -9] = "Uint64";
  98943. Type[Type["Float16"] = -10] = "Float16";
  98944. Type[Type["Float32"] = -11] = "Float32";
  98945. Type[Type["Float64"] = -12] = "Float64";
  98946. Type[Type["DateDay"] = -13] = "DateDay";
  98947. Type[Type["DateMillisecond"] = -14] = "DateMillisecond";
  98948. Type[Type["TimestampSecond"] = -15] = "TimestampSecond";
  98949. Type[Type["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  98950. Type[Type["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  98951. Type[Type["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  98952. Type[Type["TimeSecond"] = -19] = "TimeSecond";
  98953. Type[Type["TimeMillisecond"] = -20] = "TimeMillisecond";
  98954. Type[Type["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  98955. Type[Type["TimeNanosecond"] = -22] = "TimeNanosecond";
  98956. Type[Type["DenseUnion"] = -23] = "DenseUnion";
  98957. Type[Type["SparseUnion"] = -24] = "SparseUnion";
  98958. Type[Type["IntervalDayTime"] = -25] = "IntervalDayTime";
  98959. Type[Type["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  98960. })(Type$1 || (Type$1 = {}));
  98961. let _Symbol$toStringTag, _Symbol$toStringTag2, _Symbol$toStringTag7;
  98962. class DataType {
  98963. static isNull(x) {
  98964. return x && x.typeId === Type$1.Null;
  98965. }
  98966. static isInt(x) {
  98967. return x && x.typeId === Type$1.Int;
  98968. }
  98969. static isFloat(x) {
  98970. return x && x.typeId === Type$1.Float;
  98971. }
  98972. static isBinary(x) {
  98973. return x && x.typeId === Type$1.Binary;
  98974. }
  98975. static isUtf8(x) {
  98976. return x && x.typeId === Type$1.Utf8;
  98977. }
  98978. static isBool(x) {
  98979. return x && x.typeId === Type$1.Bool;
  98980. }
  98981. static isDecimal(x) {
  98982. return x && x.typeId === Type$1.Decimal;
  98983. }
  98984. static isDate(x) {
  98985. return x && x.typeId === Type$1.Date;
  98986. }
  98987. static isTime(x) {
  98988. return x && x.typeId === Type$1.Time;
  98989. }
  98990. static isTimestamp(x) {
  98991. return x && x.typeId === Type$1.Timestamp;
  98992. }
  98993. static isInterval(x) {
  98994. return x && x.typeId === Type$1.Interval;
  98995. }
  98996. static isList(x) {
  98997. return x && x.typeId === Type$1.List;
  98998. }
  98999. static isStruct(x) {
  99000. return x && x.typeId === Type$1.Struct;
  99001. }
  99002. static isUnion(x) {
  99003. return x && x.typeId === Type$1.Union;
  99004. }
  99005. static isFixedSizeBinary(x) {
  99006. return x && x.typeId === Type$1.FixedSizeBinary;
  99007. }
  99008. static isFixedSizeList(x) {
  99009. return x && x.typeId === Type$1.FixedSizeList;
  99010. }
  99011. static isMap(x) {
  99012. return x && x.typeId === Type$1.Map;
  99013. }
  99014. static isDictionary(x) {
  99015. return x && x.typeId === Type$1.Dictionary;
  99016. }
  99017. get typeId() {
  99018. return Type$1.NONE;
  99019. }
  99020. compareTo(other) {
  99021. return this === other;
  99022. }
  99023. }
  99024. _Symbol$toStringTag = Symbol.toStringTag;
  99025. class Int extends DataType {
  99026. constructor(isSigned, bitWidth) {
  99027. super();
  99028. _defineProperty(this, "isSigned", void 0);
  99029. _defineProperty(this, "bitWidth", void 0);
  99030. this.isSigned = isSigned;
  99031. this.bitWidth = bitWidth;
  99032. }
  99033. get typeId() {
  99034. return Type$1.Int;
  99035. }
  99036. get [_Symbol$toStringTag]() {
  99037. return 'Int';
  99038. }
  99039. toString() {
  99040. return "".concat(this.isSigned ? 'I' : 'Ui', "nt").concat(this.bitWidth);
  99041. }
  99042. }
  99043. class Int8 extends Int {
  99044. constructor() {
  99045. super(true, 8);
  99046. }
  99047. }
  99048. class Int16 extends Int {
  99049. constructor() {
  99050. super(true, 16);
  99051. }
  99052. }
  99053. class Int32 extends Int {
  99054. constructor() {
  99055. super(true, 32);
  99056. }
  99057. }
  99058. class Uint8 extends Int {
  99059. constructor() {
  99060. super(false, 8);
  99061. }
  99062. }
  99063. class Uint16 extends Int {
  99064. constructor() {
  99065. super(false, 16);
  99066. }
  99067. }
  99068. class Uint32 extends Int {
  99069. constructor() {
  99070. super(false, 32);
  99071. }
  99072. }
  99073. const Precision = {
  99074. HALF: 16,
  99075. SINGLE: 32,
  99076. DOUBLE: 64
  99077. };
  99078. _Symbol$toStringTag2 = Symbol.toStringTag;
  99079. class Float extends DataType {
  99080. constructor(precision) {
  99081. super();
  99082. _defineProperty(this, "precision", void 0);
  99083. this.precision = precision;
  99084. }
  99085. get typeId() {
  99086. return Type$1.Float;
  99087. }
  99088. get [_Symbol$toStringTag2]() {
  99089. return 'Float';
  99090. }
  99091. toString() {
  99092. return "Float".concat(this.precision);
  99093. }
  99094. }
  99095. class Float32 extends Float {
  99096. constructor() {
  99097. super(Precision.SINGLE);
  99098. }
  99099. }
  99100. class Float64 extends Float {
  99101. constructor() {
  99102. super(Precision.DOUBLE);
  99103. }
  99104. }
  99105. _Symbol$toStringTag7 = Symbol.toStringTag;
  99106. class FixedSizeList extends DataType {
  99107. constructor(listSize, child) {
  99108. super();
  99109. _defineProperty(this, "listSize", void 0);
  99110. _defineProperty(this, "children", void 0);
  99111. this.listSize = listSize;
  99112. this.children = [child];
  99113. }
  99114. get typeId() {
  99115. return Type$1.FixedSizeList;
  99116. }
  99117. get valueType() {
  99118. return this.children[0].type;
  99119. }
  99120. get valueField() {
  99121. return this.children[0];
  99122. }
  99123. get [_Symbol$toStringTag7]() {
  99124. return 'FixedSizeList';
  99125. }
  99126. toString() {
  99127. return "FixedSizeList[".concat(this.listSize, "]<").concat(this.valueType, ">");
  99128. }
  99129. }
  99130. function getArrowTypeFromTypedArray(array) {
  99131. switch (array.constructor) {
  99132. case Int8Array:
  99133. return new Int8();
  99134. case Uint8Array:
  99135. return new Uint8();
  99136. case Int16Array:
  99137. return new Int16();
  99138. case Uint16Array:
  99139. return new Uint16();
  99140. case Int32Array:
  99141. return new Int32();
  99142. case Uint32Array:
  99143. return new Uint32();
  99144. case Float32Array:
  99145. return new Float32();
  99146. case Float64Array:
  99147. return new Float64();
  99148. default:
  99149. throw new Error('array type not supported');
  99150. }
  99151. }
  99152. function deduceMeshField(attributeName, attribute, optionalMetadata) {
  99153. const type = getArrowTypeFromTypedArray(attribute.value);
  99154. const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
  99155. const field = new Field(attributeName, new FixedSizeList(attribute.size, new Field('value', type)), false, metadata);
  99156. return field;
  99157. }
  99158. function makeMeshAttributeMetadata(attribute) {
  99159. const result = new Map();
  99160. if ('byteOffset' in attribute) {
  99161. result.set('byteOffset', attribute.byteOffset.toString(10));
  99162. }
  99163. if ('byteStride' in attribute) {
  99164. result.set('byteStride', attribute.byteStride.toString(10));
  99165. }
  99166. if ('normalized' in attribute) {
  99167. result.set('normalized', attribute.normalized.toString());
  99168. }
  99169. return result;
  99170. }
  99171. function getDracoSchema(attributes, loaderData, indices) {
  99172. const metadataMap = makeMetadata(loaderData.metadata);
  99173. const fields = [];
  99174. const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
  99175. for (const attributeName in attributes) {
  99176. const attribute = attributes[attributeName];
  99177. const field = getArrowFieldFromAttribute(attributeName, attribute, namedLoaderDataAttributes[attributeName]);
  99178. fields.push(field);
  99179. }
  99180. if (indices) {
  99181. const indicesField = getArrowFieldFromAttribute('indices', indices);
  99182. fields.push(indicesField);
  99183. }
  99184. return new Schema(fields, metadataMap);
  99185. }
  99186. function transformAttributesLoaderData(loaderData) {
  99187. const result = {};
  99188. for (const key in loaderData) {
  99189. const dracoAttribute = loaderData[key];
  99190. result[dracoAttribute.name || 'undefined'] = dracoAttribute;
  99191. }
  99192. return result;
  99193. }
  99194. function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
  99195. const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;
  99196. const field = deduceMeshField(attributeName, attribute, metadataMap);
  99197. return field;
  99198. }
  99199. function makeMetadata(metadata) {
  99200. const metadataMap = new Map();
  99201. for (const key in metadata) {
  99202. metadataMap.set("".concat(key, ".string"), JSON.stringify(metadata[key]));
  99203. }
  99204. return metadataMap;
  99205. }
  99206. const DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
  99207. POSITION: 'POSITION',
  99208. NORMAL: 'NORMAL',
  99209. COLOR: 'COLOR_0',
  99210. TEX_COORD: 'TEXCOORD_0'
  99211. };
  99212. const DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
  99213. 1: Int8Array,
  99214. 2: Uint8Array,
  99215. 3: Int16Array,
  99216. 4: Uint16Array,
  99217. 5: Int32Array,
  99218. 6: Uint32Array,
  99219. 9: Float32Array
  99220. };
  99221. const INDEX_ITEM_SIZE = 4;
  99222. class DracoParser {
  99223. constructor(draco) {
  99224. _defineProperty(this, "draco", void 0);
  99225. _defineProperty(this, "decoder", void 0);
  99226. _defineProperty(this, "metadataQuerier", void 0);
  99227. this.draco = draco;
  99228. this.decoder = new this.draco.Decoder();
  99229. this.metadataQuerier = new this.draco.MetadataQuerier();
  99230. }
  99231. destroy() {
  99232. this.draco.destroy(this.decoder);
  99233. this.draco.destroy(this.metadataQuerier);
  99234. }
  99235. parseSync(arrayBuffer, options = {}) {
  99236. const buffer = new this.draco.DecoderBuffer();
  99237. buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
  99238. this._disableAttributeTransforms(options);
  99239. const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
  99240. const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
  99241. try {
  99242. let dracoStatus;
  99243. switch (geometry_type) {
  99244. case this.draco.TRIANGULAR_MESH:
  99245. dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  99246. break;
  99247. case this.draco.POINT_CLOUD:
  99248. dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  99249. break;
  99250. default:
  99251. throw new Error('DRACO: Unknown geometry type.');
  99252. }
  99253. if (!dracoStatus.ok() || !dracoGeometry.ptr) {
  99254. const message = "DRACO decompression failed: ".concat(dracoStatus.error_msg());
  99255. throw new Error(message);
  99256. }
  99257. const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
  99258. const geometry = this._getMeshData(dracoGeometry, loaderData, options);
  99259. const boundingBox = getMeshBoundingBox(geometry.attributes);
  99260. const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
  99261. const data = {
  99262. loader: 'draco',
  99263. loaderData,
  99264. header: {
  99265. vertexCount: dracoGeometry.num_points(),
  99266. boundingBox
  99267. },
  99268. ...geometry,
  99269. schema
  99270. };
  99271. return data;
  99272. } finally {
  99273. this.draco.destroy(buffer);
  99274. if (dracoGeometry) {
  99275. this.draco.destroy(dracoGeometry);
  99276. }
  99277. }
  99278. }
  99279. _getDracoLoaderData(dracoGeometry, geometry_type, options) {
  99280. const metadata = this._getTopLevelMetadata(dracoGeometry);
  99281. const attributes = this._getDracoAttributes(dracoGeometry, options);
  99282. return {
  99283. geometry_type,
  99284. num_attributes: dracoGeometry.num_attributes(),
  99285. num_points: dracoGeometry.num_points(),
  99286. num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
  99287. metadata,
  99288. attributes
  99289. };
  99290. }
  99291. _getDracoAttributes(dracoGeometry, options) {
  99292. const dracoAttributes = {};
  99293. for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
  99294. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
  99295. const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
  99296. dracoAttributes[dracoAttribute.unique_id()] = {
  99297. unique_id: dracoAttribute.unique_id(),
  99298. attribute_type: dracoAttribute.attribute_type(),
  99299. data_type: dracoAttribute.data_type(),
  99300. num_components: dracoAttribute.num_components(),
  99301. byte_offset: dracoAttribute.byte_offset(),
  99302. byte_stride: dracoAttribute.byte_stride(),
  99303. normalized: dracoAttribute.normalized(),
  99304. attribute_index: attributeId,
  99305. metadata
  99306. };
  99307. const quantization = this._getQuantizationTransform(dracoAttribute, options);
  99308. if (quantization) {
  99309. dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
  99310. }
  99311. const octahedron = this._getOctahedronTransform(dracoAttribute, options);
  99312. if (octahedron) {
  99313. dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
  99314. }
  99315. }
  99316. return dracoAttributes;
  99317. }
  99318. _getMeshData(dracoGeometry, loaderData, options) {
  99319. const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
  99320. const positionAttribute = attributes.POSITION;
  99321. if (!positionAttribute) {
  99322. throw new Error('DRACO: No position attribute found.');
  99323. }
  99324. if (dracoGeometry instanceof this.draco.Mesh) {
  99325. switch (options.topology) {
  99326. case 'triangle-strip':
  99327. return {
  99328. topology: 'triangle-strip',
  99329. mode: 4,
  99330. attributes,
  99331. indices: {
  99332. value: this._getTriangleStripIndices(dracoGeometry),
  99333. size: 1
  99334. }
  99335. };
  99336. case 'triangle-list':
  99337. default:
  99338. return {
  99339. topology: 'triangle-list',
  99340. mode: 5,
  99341. attributes,
  99342. indices: {
  99343. value: this._getTriangleListIndices(dracoGeometry),
  99344. size: 1
  99345. }
  99346. };
  99347. }
  99348. }
  99349. return {
  99350. topology: 'point-list',
  99351. mode: 0,
  99352. attributes
  99353. };
  99354. }
  99355. _getMeshAttributes(loaderData, dracoGeometry, options) {
  99356. const attributes = {};
  99357. for (const loaderAttribute of Object.values(loaderData.attributes)) {
  99358. const attributeName = this._deduceAttributeName(loaderAttribute, options);
  99359. loaderAttribute.name = attributeName;
  99360. const {
  99361. value,
  99362. size
  99363. } = this._getAttributeValues(dracoGeometry, loaderAttribute);
  99364. attributes[attributeName] = {
  99365. value,
  99366. size,
  99367. byteOffset: loaderAttribute.byte_offset,
  99368. byteStride: loaderAttribute.byte_stride,
  99369. normalized: loaderAttribute.normalized
  99370. };
  99371. }
  99372. return attributes;
  99373. }
  99374. _getTriangleListIndices(dracoGeometry) {
  99375. const numFaces = dracoGeometry.num_faces();
  99376. const numIndices = numFaces * 3;
  99377. const byteLength = numIndices * INDEX_ITEM_SIZE;
  99378. const ptr = this.draco._malloc(byteLength);
  99379. try {
  99380. this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  99381. return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
  99382. } finally {
  99383. this.draco._free(ptr);
  99384. }
  99385. }
  99386. _getTriangleStripIndices(dracoGeometry) {
  99387. const dracoArray = new this.draco.DracoInt32Array();
  99388. try {
  99389. this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
  99390. return getUint32Array(dracoArray);
  99391. } finally {
  99392. this.draco.destroy(dracoArray);
  99393. }
  99394. }
  99395. _getAttributeValues(dracoGeometry, attribute) {
  99396. const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
  99397. const numComponents = attribute.num_components;
  99398. const numPoints = dracoGeometry.num_points();
  99399. const numValues = numPoints * numComponents;
  99400. const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
  99401. const dataType = getDracoDataType(this.draco, TypedArrayCtor);
  99402. let value;
  99403. const ptr = this.draco._malloc(byteLength);
  99404. try {
  99405. const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
  99406. this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, dracoAttribute, dataType, byteLength, ptr);
  99407. value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
  99408. } finally {
  99409. this.draco._free(ptr);
  99410. }
  99411. return {
  99412. value,
  99413. size: numComponents
  99414. };
  99415. }
  99416. _deduceAttributeName(attribute, options) {
  99417. const uniqueId = attribute.unique_id;
  99418. for (const [attributeName, attributeUniqueId] of Object.entries(options.extraAttributes || {})) {
  99419. if (attributeUniqueId === uniqueId) {
  99420. return attributeName;
  99421. }
  99422. }
  99423. const thisAttributeType = attribute.attribute_type;
  99424. for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
  99425. const attributeType = this.draco[dracoAttributeConstant];
  99426. if (attributeType === thisAttributeType) {
  99427. return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
  99428. }
  99429. }
  99430. const entryName = options.attributeNameEntry || 'name';
  99431. if (attribute.metadata[entryName]) {
  99432. return attribute.metadata[entryName].string;
  99433. }
  99434. return "CUSTOM_ATTRIBUTE_".concat(uniqueId);
  99435. }
  99436. _getTopLevelMetadata(dracoGeometry) {
  99437. const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
  99438. return this._getDracoMetadata(dracoMetadata);
  99439. }
  99440. _getAttributeMetadata(dracoGeometry, attributeId) {
  99441. const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
  99442. return this._getDracoMetadata(dracoMetadata);
  99443. }
  99444. _getDracoMetadata(dracoMetadata) {
  99445. if (!dracoMetadata || !dracoMetadata.ptr) {
  99446. return {};
  99447. }
  99448. const result = {};
  99449. const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
  99450. for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
  99451. const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
  99452. result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
  99453. }
  99454. return result;
  99455. }
  99456. _getDracoMetadataField(dracoMetadata, entryName) {
  99457. const dracoArray = new this.draco.DracoInt32Array();
  99458. try {
  99459. this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
  99460. const intArray = getInt32Array(dracoArray);
  99461. return {
  99462. int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
  99463. string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
  99464. double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
  99465. intArray
  99466. };
  99467. } finally {
  99468. this.draco.destroy(dracoArray);
  99469. }
  99470. }
  99471. _disableAttributeTransforms(options) {
  99472. const {
  99473. quantizedAttributes = [],
  99474. octahedronAttributes = []
  99475. } = options;
  99476. const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
  99477. for (const dracoAttributeName of skipAttributes) {
  99478. this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
  99479. }
  99480. }
  99481. _getQuantizationTransform(dracoAttribute, options) {
  99482. const {
  99483. quantizedAttributes = []
  99484. } = options;
  99485. const attribute_type = dracoAttribute.attribute_type();
  99486. const skip = quantizedAttributes.map(type => this.decoder[type]).includes(attribute_type);
  99487. if (skip) {
  99488. const transform = new this.draco.AttributeQuantizationTransform();
  99489. try {
  99490. if (transform.InitFromAttribute(dracoAttribute)) {
  99491. return {
  99492. quantization_bits: transform.quantization_bits(),
  99493. range: transform.range(),
  99494. min_values: new Float32Array([1, 2, 3]).map(i => transform.min_value(i))
  99495. };
  99496. }
  99497. } finally {
  99498. this.draco.destroy(transform);
  99499. }
  99500. }
  99501. return null;
  99502. }
  99503. _getOctahedronTransform(dracoAttribute, options) {
  99504. const {
  99505. octahedronAttributes = []
  99506. } = options;
  99507. const attribute_type = dracoAttribute.attribute_type();
  99508. const octahedron = octahedronAttributes.map(type => this.decoder[type]).includes(attribute_type);
  99509. if (octahedron) {
  99510. const transform = new this.draco.AttributeQuantizationTransform();
  99511. try {
  99512. if (transform.InitFromAttribute(dracoAttribute)) {
  99513. return {
  99514. quantization_bits: transform.quantization_bits()
  99515. };
  99516. }
  99517. } finally {
  99518. this.draco.destroy(transform);
  99519. }
  99520. }
  99521. return null;
  99522. }
  99523. }
  99524. function getDracoDataType(draco, attributeType) {
  99525. switch (attributeType) {
  99526. case Float32Array:
  99527. return draco.DT_FLOAT32;
  99528. case Int8Array:
  99529. return draco.DT_INT8;
  99530. case Int16Array:
  99531. return draco.DT_INT16;
  99532. case Int32Array:
  99533. return draco.DT_INT32;
  99534. case Uint8Array:
  99535. return draco.DT_UINT8;
  99536. case Uint16Array:
  99537. return draco.DT_UINT16;
  99538. case Uint32Array:
  99539. return draco.DT_UINT32;
  99540. default:
  99541. return draco.DT_INVALID;
  99542. }
  99543. }
  99544. function getInt32Array(dracoArray) {
  99545. const numValues = dracoArray.size();
  99546. const intArray = new Int32Array(numValues);
  99547. for (let i = 0; i < numValues; i++) {
  99548. intArray[i] = dracoArray.GetValue(i);
  99549. }
  99550. return intArray;
  99551. }
  99552. function getUint32Array(dracoArray) {
  99553. const numValues = dracoArray.size();
  99554. const intArray = new Int32Array(numValues);
  99555. for (let i = 0; i < numValues; i++) {
  99556. intArray[i] = dracoArray.GetValue(i);
  99557. }
  99558. return intArray;
  99559. }
  99560. const DRACO_VERSION = '1.4.1';
  99561. const DRACO_JS_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.js");
  99562. const DRACO_WASM_WRAPPER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_wasm_wrapper.js");
  99563. const DRACO_WASM_DECODER_URL = "https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION, "/draco_decoder.wasm");
  99564. let loadDecoderPromise;
  99565. async function loadDracoDecoderModule(options) {
  99566. const modules = options.modules || {};
  99567. if (modules.draco3d) {
  99568. loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then(draco => {
  99569. return {
  99570. draco
  99571. };
  99572. });
  99573. } else {
  99574. loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
  99575. }
  99576. return await loadDecoderPromise;
  99577. }
  99578. async function loadDracoDecoder(options) {
  99579. let DracoDecoderModule;
  99580. let wasmBinary;
  99581. switch (options.draco && options.draco.decoderType) {
  99582. case 'js':
  99583. DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);
  99584. break;
  99585. case 'wasm':
  99586. default:
  99587. [DracoDecoderModule, wasmBinary] = await Promise.all([await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options), await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)]);
  99588. }
  99589. DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
  99590. return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
  99591. }
  99592. function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
  99593. const options = {};
  99594. if (wasmBinary) {
  99595. options.wasmBinary = wasmBinary;
  99596. }
  99597. return new Promise(resolve => {
  99598. DracoDecoderModule({ ...options,
  99599. onModuleLoaded: draco => resolve({
  99600. draco
  99601. })
  99602. });
  99603. });
  99604. }
  99605. const DracoLoader = { ...DracoLoader$1,
  99606. parse: parse$2
  99607. };
  99608. async function parse$2(arrayBuffer, options) {
  99609. const {
  99610. draco
  99611. } = await loadDracoDecoderModule(options);
  99612. const dracoParser = new DracoParser(draco);
  99613. try {
  99614. return dracoParser.parseSync(arrayBuffer, options === null || options === void 0 ? void 0 : options.draco);
  99615. } finally {
  99616. dracoParser.destroy();
  99617. }
  99618. }
  99619. const GL_PRIMITIVE_MODE = {
  99620. POINTS: 0x0000,
  99621. LINES: 0x0001,
  99622. LINE_LOOP: 0x0002,
  99623. LINE_STRIP: 0x0003,
  99624. TRIANGLES: 0x0004,
  99625. TRIANGLE_STRIP: 0x0005,
  99626. TRIANGLE_FAN: 0x0006
  99627. };
  99628. const GL_TYPE = {
  99629. BYTE: 5120,
  99630. UNSIGNED_BYTE: 5121,
  99631. SHORT: 5122,
  99632. UNSIGNED_SHORT: 5123,
  99633. INT: 5124,
  99634. UNSIGNED_INT: 5125,
  99635. FLOAT: 5126,
  99636. DOUBLE: 5130
  99637. };
  99638. const GL$1 = { ...GL_PRIMITIVE_MODE,
  99639. ...GL_TYPE
  99640. };
  99641. const GL_TYPE_TO_ARRAY_TYPE = {
  99642. [GL_TYPE.DOUBLE]: Float64Array,
  99643. [GL_TYPE.FLOAT]: Float32Array,
  99644. [GL_TYPE.UNSIGNED_SHORT]: Uint16Array,
  99645. [GL_TYPE.UNSIGNED_INT]: Uint32Array,
  99646. [GL_TYPE.UNSIGNED_BYTE]: Uint8Array,
  99647. [GL_TYPE.BYTE]: Int8Array,
  99648. [GL_TYPE.SHORT]: Int16Array,
  99649. [GL_TYPE.INT]: Int32Array
  99650. };
  99651. const NAME_TO_GL_TYPE = {
  99652. DOUBLE: GL_TYPE.DOUBLE,
  99653. FLOAT: GL_TYPE.FLOAT,
  99654. UNSIGNED_SHORT: GL_TYPE.UNSIGNED_SHORT,
  99655. UNSIGNED_INT: GL_TYPE.UNSIGNED_INT,
  99656. UNSIGNED_BYTE: GL_TYPE.UNSIGNED_BYTE,
  99657. BYTE: GL_TYPE.BYTE,
  99658. SHORT: GL_TYPE.SHORT,
  99659. INT: GL_TYPE.INT
  99660. };
  99661. const ERR_TYPE_CONVERSION = 'Failed to convert GL type';
  99662. class GLType {
  99663. static fromTypedArray(arrayOrType) {
  99664. arrayOrType = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;
  99665. for (const glType in GL_TYPE_TO_ARRAY_TYPE) {
  99666. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  99667. if (ArrayType === arrayOrType) {
  99668. return glType;
  99669. }
  99670. }
  99671. throw new Error(ERR_TYPE_CONVERSION);
  99672. }
  99673. static fromName(name) {
  99674. const glType = NAME_TO_GL_TYPE[name];
  99675. if (!glType) {
  99676. throw new Error(ERR_TYPE_CONVERSION);
  99677. }
  99678. return glType;
  99679. }
  99680. static getArrayType(glType) {
  99681. switch (glType) {
  99682. case GL_TYPE.UNSIGNED_SHORT_5_6_5:
  99683. case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:
  99684. case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:
  99685. return Uint16Array;
  99686. default:
  99687. const ArrayType = GL_TYPE_TO_ARRAY_TYPE[glType];
  99688. if (!ArrayType) {
  99689. throw new Error(ERR_TYPE_CONVERSION);
  99690. }
  99691. return ArrayType;
  99692. }
  99693. }
  99694. static getByteSize(glType) {
  99695. const ArrayType = GLType.getArrayType(glType);
  99696. return ArrayType.BYTES_PER_ELEMENT;
  99697. }
  99698. static validate(glType) {
  99699. return Boolean(GLType.getArrayType(glType));
  99700. }
  99701. static createTypedArray(glType, buffer, byteOffset = 0, length) {
  99702. if (length === undefined) {
  99703. length = (buffer.byteLength - byteOffset) / GLType.getByteSize(glType);
  99704. }
  99705. const ArrayType = GLType.getArrayType(glType);
  99706. return new ArrayType(buffer, byteOffset, length);
  99707. }
  99708. }
  99709. function assert$2(condition, message) {
  99710. if (!condition) {
  99711. throw new Error("math.gl assertion failed. ".concat(message));
  99712. }
  99713. }
  99714. function decodeRGB565(rgb565, target = [0, 0, 0]) {
  99715. const r5 = rgb565 >> 11 & 31;
  99716. const g6 = rgb565 >> 5 & 63;
  99717. const b5 = rgb565 & 31;
  99718. target[0] = r5 << 3;
  99719. target[1] = g6 << 2;
  99720. target[2] = b5 << 3;
  99721. return target;
  99722. }
  99723. new Vector2$1();
  99724. new Vector3$1();
  99725. new Vector2$1();
  99726. new Vector2$1();
  99727. function fromSNorm(value, rangeMaximum = 255) {
  99728. return clamp(value, 0.0, rangeMaximum) / rangeMaximum * 2.0 - 1.0;
  99729. }
  99730. function signNotZero(value) {
  99731. return value < 0.0 ? -1.0 : 1.0;
  99732. }
  99733. function octDecodeInRange(x, y, rangeMax, result) {
  99734. assert$2(result);
  99735. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  99736. throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));
  99737. }
  99738. result.x = fromSNorm(x, rangeMax);
  99739. result.y = fromSNorm(y, rangeMax);
  99740. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  99741. if (result.z < 0.0) {
  99742. const oldVX = result.x;
  99743. result.x = (1.0 - Math.abs(result.y)) * signNotZero(oldVX);
  99744. result.y = (1.0 - Math.abs(oldVX)) * signNotZero(result.y);
  99745. }
  99746. return result.normalize();
  99747. }
  99748. function octDecode(x, y, result) {
  99749. return octDecodeInRange(x, y, 255, result);
  99750. }
  99751. class Tile3DFeatureTable {
  99752. constructor(featureTableJson, featureTableBinary) {
  99753. _defineProperty(this, "json", void 0);
  99754. _defineProperty(this, "buffer", void 0);
  99755. _defineProperty(this, "featuresLength", 0);
  99756. _defineProperty(this, "_cachedTypedArrays", {});
  99757. this.json = featureTableJson;
  99758. this.buffer = featureTableBinary;
  99759. }
  99760. getExtension(extensionName) {
  99761. return this.json.extensions && this.json.extensions[extensionName];
  99762. }
  99763. hasProperty(propertyName) {
  99764. return Boolean(this.json[propertyName]);
  99765. }
  99766. getGlobalProperty(propertyName, componentType = GL$1.UNSIGNED_INT, componentLength = 1) {
  99767. const jsonValue = this.json[propertyName];
  99768. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  99769. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, 1, jsonValue.byteOffset);
  99770. }
  99771. return jsonValue;
  99772. }
  99773. getPropertyArray(propertyName, componentType, componentLength) {
  99774. const jsonValue = this.json[propertyName];
  99775. if (jsonValue && Number.isFinite(jsonValue.byteOffset)) {
  99776. if ('componentType' in jsonValue) {
  99777. componentType = GLType.fromName(jsonValue.componentType);
  99778. }
  99779. return this._getTypedArrayFromBinary(propertyName, componentType, componentLength, this.featuresLength, jsonValue.byteOffset);
  99780. }
  99781. return this._getTypedArrayFromArray(propertyName, componentType, jsonValue);
  99782. }
  99783. getProperty(propertyName, componentType, componentLength, featureId, result) {
  99784. const jsonValue = this.json[propertyName];
  99785. if (!jsonValue) {
  99786. return jsonValue;
  99787. }
  99788. const typedArray = this.getPropertyArray(propertyName, componentType, componentLength);
  99789. if (componentLength === 1) {
  99790. return typedArray[featureId];
  99791. }
  99792. for (let i = 0; i < componentLength; ++i) {
  99793. result[i] = typedArray[componentLength * featureId + i];
  99794. }
  99795. return result;
  99796. }
  99797. _getTypedArrayFromBinary(propertyName, componentType, componentLength, count, byteOffset) {
  99798. const cachedTypedArrays = this._cachedTypedArrays;
  99799. let typedArray = cachedTypedArrays[propertyName];
  99800. if (!typedArray) {
  99801. typedArray = GLType.createTypedArray(componentType, this.buffer.buffer, this.buffer.byteOffset + byteOffset, count * componentLength);
  99802. cachedTypedArrays[propertyName] = typedArray;
  99803. }
  99804. return typedArray;
  99805. }
  99806. _getTypedArrayFromArray(propertyName, componentType, array) {
  99807. const cachedTypedArrays = this._cachedTypedArrays;
  99808. let typedArray = cachedTypedArrays[propertyName];
  99809. if (!typedArray) {
  99810. typedArray = GLType.createTypedArray(componentType, array);
  99811. cachedTypedArrays[propertyName] = typedArray;
  99812. }
  99813. return typedArray;
  99814. }
  99815. }
  99816. const COMPONENTS_PER_ATTRIBUTE = {
  99817. SCALAR: 1,
  99818. VEC2: 2,
  99819. VEC3: 3,
  99820. VEC4: 4,
  99821. MAT2: 4,
  99822. MAT3: 9,
  99823. MAT4: 16
  99824. };
  99825. const UNPACKER = {
  99826. SCALAR: (values, i) => values[i],
  99827. VEC2: (values, i) => [values[2 * i + 0], values[2 * i + 1]],
  99828. VEC3: (values, i) => [values[3 * i + 0], values[3 * i + 1], values[3 * i + 2]],
  99829. VEC4: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  99830. MAT2: (values, i) => [values[4 * i + 0], values[4 * i + 1], values[4 * i + 2], values[4 * i + 3]],
  99831. 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]],
  99832. 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]]
  99833. };
  99834. const PACKER = {
  99835. SCALAR: (x, values, i) => {
  99836. values[i] = x;
  99837. },
  99838. VEC2: (x, values, i) => {
  99839. values[2 * i + 0] = x[0];
  99840. values[2 * i + 1] = x[1];
  99841. },
  99842. VEC3: (x, values, i) => {
  99843. values[3 * i + 0] = x[0];
  99844. values[3 * i + 1] = x[1];
  99845. values[3 * i + 2] = x[2];
  99846. },
  99847. VEC4: (x, values, i) => {
  99848. values[4 * i + 0] = x[0];
  99849. values[4 * i + 1] = x[1];
  99850. values[4 * i + 2] = x[2];
  99851. values[4 * i + 3] = x[3];
  99852. },
  99853. MAT2: (x, values, i) => {
  99854. values[4 * i + 0] = x[0];
  99855. values[4 * i + 1] = x[1];
  99856. values[4 * i + 2] = x[2];
  99857. values[4 * i + 3] = x[3];
  99858. },
  99859. MAT3: (x, values, i) => {
  99860. values[9 * i + 0] = x[0];
  99861. values[9 * i + 1] = x[1];
  99862. values[9 * i + 2] = x[2];
  99863. values[9 * i + 3] = x[3];
  99864. values[9 * i + 4] = x[4];
  99865. values[9 * i + 5] = x[5];
  99866. values[9 * i + 6] = x[6];
  99867. values[9 * i + 7] = x[7];
  99868. values[9 * i + 8] = x[8];
  99869. values[9 * i + 9] = x[9];
  99870. },
  99871. MAT4: (x, values, i) => {
  99872. values[16 * i + 0] = x[0];
  99873. values[16 * i + 1] = x[1];
  99874. values[16 * i + 2] = x[2];
  99875. values[16 * i + 3] = x[3];
  99876. values[16 * i + 4] = x[4];
  99877. values[16 * i + 5] = x[5];
  99878. values[16 * i + 6] = x[6];
  99879. values[16 * i + 7] = x[7];
  99880. values[16 * i + 8] = x[8];
  99881. values[16 * i + 9] = x[9];
  99882. values[16 * i + 10] = x[10];
  99883. values[16 * i + 11] = x[11];
  99884. values[16 * i + 12] = x[12];
  99885. values[16 * i + 13] = x[13];
  99886. values[16 * i + 14] = x[14];
  99887. values[16 * i + 15] = x[15];
  99888. }
  99889. };
  99890. function createTypedArrayFromAccessor(tile3DAccessor, buffer, byteOffset, length) {
  99891. const {
  99892. componentType
  99893. } = tile3DAccessor;
  99894. assert$7(tile3DAccessor.componentType);
  99895. const type = typeof componentType === 'string' ? GLType.fromName(componentType) : componentType;
  99896. const size = COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];
  99897. const unpacker = UNPACKER[tile3DAccessor.type];
  99898. const packer = PACKER[tile3DAccessor.type];
  99899. byteOffset += tile3DAccessor.byteOffset;
  99900. const values = GLType.createTypedArray(type, buffer, byteOffset, size * length);
  99901. return {
  99902. values,
  99903. type,
  99904. size,
  99905. unpacker,
  99906. packer
  99907. };
  99908. }
  99909. const defined$1 = x => x !== undefined;
  99910. function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
  99911. if (!jsonHeader) {
  99912. return null;
  99913. }
  99914. let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
  99915. const legacyHierarchy = jsonHeader.HIERARCHY;
  99916. if (legacyHierarchy) {
  99917. console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');
  99918. jsonHeader.extensions = jsonHeader.extensions || {};
  99919. jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
  99920. hierarchy = legacyHierarchy;
  99921. }
  99922. if (!hierarchy) {
  99923. return null;
  99924. }
  99925. return initializeHierarchyValues(hierarchy, binaryBody);
  99926. }
  99927. function initializeHierarchyValues(hierarchyJson, binaryBody) {
  99928. let i;
  99929. let classId;
  99930. let binaryAccessor;
  99931. const instancesLength = hierarchyJson.instancesLength;
  99932. const classes = hierarchyJson.classes;
  99933. let classIds = hierarchyJson.classIds;
  99934. let parentCounts = hierarchyJson.parentCounts;
  99935. let parentIds = hierarchyJson.parentIds;
  99936. let parentIdsLength = instancesLength;
  99937. if (defined$1(classIds.byteOffset)) {
  99938. classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
  99939. classIds.type = AttributeType.SCALAR;
  99940. binaryAccessor = getBinaryAccessor(classIds);
  99941. classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
  99942. }
  99943. let parentIndexes;
  99944. if (defined$1(parentCounts)) {
  99945. if (defined$1(parentCounts.byteOffset)) {
  99946. parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
  99947. parentCounts.type = AttributeType.SCALAR;
  99948. binaryAccessor = getBinaryAccessor(parentCounts);
  99949. parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
  99950. }
  99951. parentIndexes = new Uint16Array(instancesLength);
  99952. parentIdsLength = 0;
  99953. for (i = 0; i < instancesLength; ++i) {
  99954. parentIndexes[i] = parentIdsLength;
  99955. parentIdsLength += parentCounts[i];
  99956. }
  99957. }
  99958. if (defined$1(parentIds) && defined$1(parentIds.byteOffset)) {
  99959. parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
  99960. parentIds.type = AttributeType.SCALAR;
  99961. binaryAccessor = getBinaryAccessor(parentIds);
  99962. parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
  99963. }
  99964. const classesLength = classes.length;
  99965. for (i = 0; i < classesLength; ++i) {
  99966. const classInstancesLength = classes[i].length;
  99967. const properties = classes[i].instances;
  99968. const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
  99969. classes[i].instances = combine(binaryProperties, properties);
  99970. }
  99971. const classCounts = new Array(classesLength).fill(0);
  99972. const classIndexes = new Uint16Array(instancesLength);
  99973. for (i = 0; i < instancesLength; ++i) {
  99974. classId = classIds[i];
  99975. classIndexes[i] = classCounts[classId];
  99976. ++classCounts[classId];
  99977. }
  99978. const hierarchy = {
  99979. classes,
  99980. classIds,
  99981. classIndexes,
  99982. parentCounts,
  99983. parentIndexes,
  99984. parentIds
  99985. };
  99986. validateHierarchy(hierarchy);
  99987. return hierarchy;
  99988. }
  99989. function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
  99990. if (!hierarchy) {
  99991. return;
  99992. }
  99993. const parentCounts = hierarchy.parentCounts;
  99994. const parentIds = hierarchy.parentIds;
  99995. if (parentIds) {
  99996. return endConditionCallback(hierarchy, instanceIndex);
  99997. }
  99998. if (parentCounts > 0) {
  99999. return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
  100000. }
  100001. return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
  100002. }
  100003. function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
  100004. const classIds = hierarchy.classIds;
  100005. const parentCounts = hierarchy.parentCounts;
  100006. const parentIds = hierarchy.parentIds;
  100007. const parentIndexes = hierarchy.parentIndexes;
  100008. const instancesLength = classIds.length;
  100009. const visited = scratchVisited;
  100010. visited.length = Math.max(visited.length, instancesLength);
  100011. const visitedMarker = ++marker;
  100012. const stack = scratchStack;
  100013. stack.length = 0;
  100014. stack.push(instanceIndex);
  100015. while (stack.length > 0) {
  100016. instanceIndex = stack.pop();
  100017. if (visited[instanceIndex] === visitedMarker) {
  100018. continue;
  100019. }
  100020. visited[instanceIndex] = visitedMarker;
  100021. const result = endConditionCallback(hierarchy, instanceIndex);
  100022. if (defined$1(result)) {
  100023. return result;
  100024. }
  100025. const parentCount = parentCounts[instanceIndex];
  100026. const parentIndex = parentIndexes[instanceIndex];
  100027. for (let i = 0; i < parentCount; ++i) {
  100028. const parentId = parentIds[parentIndex + i];
  100029. if (parentId !== instanceIndex) {
  100030. stack.push(parentId);
  100031. }
  100032. }
  100033. }
  100034. return null;
  100035. }
  100036. function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
  100037. let hasParent = true;
  100038. while (hasParent) {
  100039. const result = endConditionCallback(hierarchy, instanceIndex);
  100040. if (defined$1(result)) {
  100041. return result;
  100042. }
  100043. const parentId = hierarchy.parentIds[instanceIndex];
  100044. hasParent = parentId !== instanceIndex;
  100045. instanceIndex = parentId;
  100046. }
  100047. throw new Error('traverseHierarchySingleParent');
  100048. }
  100049. function validateHierarchy(hierarchy) {
  100050. const classIds = hierarchy.classIds;
  100051. const instancesLength = classIds.length;
  100052. for (let i = 0; i < instancesLength; ++i) {
  100053. validateInstance(hierarchy, i, stack);
  100054. }
  100055. }
  100056. function validateInstance(hierarchy, instanceIndex, stack) {
  100057. const parentCounts = hierarchy.parentCounts;
  100058. const parentIds = hierarchy.parentIds;
  100059. const parentIndexes = hierarchy.parentIndexes;
  100060. const classIds = hierarchy.classIds;
  100061. const instancesLength = classIds.length;
  100062. if (!defined$1(parentIds)) {
  100063. return;
  100064. }
  100065. assert(instanceIndex < instancesLength, "Parent index ".concat(instanceIndex, " exceeds the total number of instances: ").concat(instancesLength));
  100066. assert(stack.indexOf(instanceIndex) === -1, 'Circular dependency detected in the batch table hierarchy.');
  100067. stack.push(instanceIndex);
  100068. const parentCount = defined$1(parentCounts) ? parentCounts[instanceIndex] : 1;
  100069. const parentIndex = defined$1(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
  100070. for (let i = 0; i < parentCount; ++i) {
  100071. const parentId = parentIds[parentIndex + i];
  100072. if (parentId !== instanceIndex) {
  100073. validateInstance(hierarchy, parentId, stack);
  100074. }
  100075. }
  100076. stack.pop(instanceIndex);
  100077. }
  100078. function defined(x) {
  100079. return x !== undefined && x !== null;
  100080. }
  100081. const clone = (x, y) => x;
  100082. const IGNORED_PROPERTY_FIELDS = {
  100083. HIERARCHY: true,
  100084. extensions: true,
  100085. extras: true
  100086. };
  100087. class Tile3DBatchTableParser {
  100088. constructor(json, binary, featureCount, options = {}) {
  100089. var _this$json;
  100090. _defineProperty(this, "json", void 0);
  100091. _defineProperty(this, "binary", void 0);
  100092. _defineProperty(this, "featureCount", void 0);
  100093. _defineProperty(this, "_extensions", void 0);
  100094. _defineProperty(this, "_properties", void 0);
  100095. _defineProperty(this, "_binaryProperties", void 0);
  100096. _defineProperty(this, "_hierarchy", void 0);
  100097. assert$7(featureCount >= 0);
  100098. this.json = json || {};
  100099. this.binary = binary;
  100100. this.featureCount = featureCount;
  100101. this._extensions = ((_this$json = this.json) === null || _this$json === void 0 ? void 0 : _this$json.extensions) || {};
  100102. this._properties = {};
  100103. for (const propertyName in this.json) {
  100104. if (!IGNORED_PROPERTY_FIELDS[propertyName]) {
  100105. this._properties[propertyName] = this.json[propertyName];
  100106. }
  100107. }
  100108. this._binaryProperties = this._initializeBinaryProperties();
  100109. if (options['3DTILES_batch_table_hierarchy']) {
  100110. this._hierarchy = initializeHierarchy(this, this.json, this.binary);
  100111. }
  100112. }
  100113. getExtension(extensionName) {
  100114. return this.json && this.json.extensions && this.json.extensions[extensionName];
  100115. }
  100116. memorySizeInBytes() {
  100117. return 0;
  100118. }
  100119. isClass(batchId, className) {
  100120. this._checkBatchId(batchId);
  100121. assert$7(typeof className === 'string', className);
  100122. if (this._hierarchy) {
  100123. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  100124. const classId = hierarchy.classIds[instanceIndex];
  100125. const instanceClass = hierarchy.classes[classId];
  100126. return instanceClass.name === className;
  100127. });
  100128. return defined(result);
  100129. }
  100130. return false;
  100131. }
  100132. isExactClass(batchId, className) {
  100133. assert$7(typeof className === 'string', className);
  100134. return this.getExactClassName(batchId) === className;
  100135. }
  100136. getExactClassName(batchId) {
  100137. this._checkBatchId(batchId);
  100138. if (this._hierarchy) {
  100139. const classId = this._hierarchy.classIds[batchId];
  100140. const instanceClass = this._hierarchy.classes[classId];
  100141. return instanceClass.name;
  100142. }
  100143. return undefined;
  100144. }
  100145. hasProperty(batchId, name) {
  100146. this._checkBatchId(batchId);
  100147. assert$7(typeof name === 'string', name);
  100148. return defined(this._properties[name]) || this._hasPropertyInHierarchy(batchId, name);
  100149. }
  100150. getPropertyNames(batchId, results) {
  100151. this._checkBatchId(batchId);
  100152. results = defined(results) ? results : [];
  100153. results.length = 0;
  100154. const propertyNames = Object.keys(this._properties);
  100155. results.push(...propertyNames);
  100156. if (this._hierarchy) {
  100157. this._getPropertyNamesInHierarchy(batchId, results);
  100158. }
  100159. return results;
  100160. }
  100161. getProperty(batchId, name) {
  100162. this._checkBatchId(batchId);
  100163. assert$7(typeof name === 'string', name);
  100164. if (this._binaryProperties) {
  100165. const binaryProperty = this._binaryProperties[name];
  100166. if (defined(binaryProperty)) {
  100167. return this._getBinaryProperty(binaryProperty, batchId);
  100168. }
  100169. }
  100170. const propertyValues = this._properties[name];
  100171. if (defined(propertyValues)) {
  100172. return clone(propertyValues[batchId]);
  100173. }
  100174. if (this._hierarchy) {
  100175. const hierarchyProperty = this._getHierarchyProperty(batchId, name);
  100176. if (defined(hierarchyProperty)) {
  100177. return hierarchyProperty;
  100178. }
  100179. }
  100180. return undefined;
  100181. }
  100182. setProperty(batchId, name, value) {
  100183. const featureCount = this.featureCount;
  100184. this._checkBatchId(batchId);
  100185. assert$7(typeof name === 'string', name);
  100186. if (this._binaryProperties) {
  100187. const binaryProperty = this._binaryProperties[name];
  100188. if (binaryProperty) {
  100189. this._setBinaryProperty(binaryProperty, batchId, value);
  100190. return;
  100191. }
  100192. }
  100193. if (this._hierarchy) {
  100194. if (this._setHierarchyProperty(this, batchId, name, value)) {
  100195. return;
  100196. }
  100197. }
  100198. let propertyValues = this._properties[name];
  100199. if (!defined(propertyValues)) {
  100200. this._properties[name] = new Array(featureCount);
  100201. propertyValues = this._properties[name];
  100202. }
  100203. propertyValues[batchId] = clone(value);
  100204. }
  100205. _checkBatchId(batchId) {
  100206. const valid = batchId >= 0 && batchId < this.featureCount;
  100207. if (!valid) {
  100208. throw new Error('batchId not in range [0, featureCount - 1].');
  100209. }
  100210. }
  100211. _getBinaryProperty(binaryProperty, index) {
  100212. return binaryProperty.unpack(binaryProperty.typedArray, index);
  100213. }
  100214. _setBinaryProperty(binaryProperty, index, value) {
  100215. binaryProperty.pack(value, binaryProperty.typedArray, index);
  100216. }
  100217. _initializeBinaryProperties() {
  100218. let binaryProperties = null;
  100219. for (const name in this._properties) {
  100220. const property = this._properties[name];
  100221. const binaryProperty = this._initializeBinaryProperty(name, property);
  100222. if (binaryProperty) {
  100223. binaryProperties = binaryProperties || {};
  100224. binaryProperties[name] = binaryProperty;
  100225. }
  100226. }
  100227. return binaryProperties;
  100228. }
  100229. _initializeBinaryProperty(name, property) {
  100230. if ('byteOffset' in property) {
  100231. const tile3DAccessor = property;
  100232. assert$7(this.binary, "Property ".concat(name, " requires a batch table binary."));
  100233. assert$7(tile3DAccessor.type, "Property ".concat(name, " requires a type."));
  100234. const accessor = createTypedArrayFromAccessor(tile3DAccessor, this.binary.buffer, this.binary.byteOffset | 0, this.featureCount);
  100235. return {
  100236. typedArray: accessor.values,
  100237. componentCount: accessor.size,
  100238. unpack: accessor.unpacker,
  100239. pack: accessor.packer
  100240. };
  100241. }
  100242. return null;
  100243. }
  100244. _hasPropertyInHierarchy(batchId, name) {
  100245. if (!this._hierarchy) {
  100246. return false;
  100247. }
  100248. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  100249. const classId = hierarchy.classIds[instanceIndex];
  100250. const instances = hierarchy.classes[classId].instances;
  100251. return defined(instances[name]);
  100252. });
  100253. return defined(result);
  100254. }
  100255. _getPropertyNamesInHierarchy(batchId, results) {
  100256. traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  100257. const classId = hierarchy.classIds[instanceIndex];
  100258. const instances = hierarchy.classes[classId].instances;
  100259. for (const name in instances) {
  100260. if (instances.hasOwnProperty(name)) {
  100261. if (results.indexOf(name) === -1) {
  100262. results.push(name);
  100263. }
  100264. }
  100265. }
  100266. });
  100267. }
  100268. _getHierarchyProperty(batchId, name) {
  100269. return traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  100270. const classId = hierarchy.classIds[instanceIndex];
  100271. const instanceClass = hierarchy.classes[classId];
  100272. const indexInClass = hierarchy.classIndexes[instanceIndex];
  100273. const propertyValues = instanceClass.instances[name];
  100274. if (defined(propertyValues)) {
  100275. if (defined(propertyValues.typedArray)) {
  100276. return this._getBinaryProperty(propertyValues, indexInClass);
  100277. }
  100278. return clone(propertyValues[indexInClass]);
  100279. }
  100280. return null;
  100281. });
  100282. }
  100283. _setHierarchyProperty(batchTable, batchId, name, value) {
  100284. const result = traverseHierarchy(this._hierarchy, batchId, (hierarchy, instanceIndex) => {
  100285. const classId = hierarchy.classIds[instanceIndex];
  100286. const instanceClass = hierarchy.classes[classId];
  100287. const indexInClass = hierarchy.classIndexes[instanceIndex];
  100288. const propertyValues = instanceClass.instances[name];
  100289. if (defined(propertyValues)) {
  100290. assert$7(instanceIndex === batchId, "Inherited property \"".concat(name, "\" is read-only."));
  100291. if (defined(propertyValues.typedArray)) {
  100292. this._setBinaryProperty(propertyValues, indexInClass, value);
  100293. } else {
  100294. propertyValues[indexInClass] = clone(value);
  100295. }
  100296. return true;
  100297. }
  100298. return false;
  100299. });
  100300. return defined(result);
  100301. }
  100302. }
  100303. const SIZEOF_UINT32$1 = 4;
  100304. function parse3DTileHeaderSync(tile, arrayBuffer, byteOffset = 0) {
  100305. const view = new DataView(arrayBuffer);
  100306. tile.magic = view.getUint32(byteOffset, true);
  100307. byteOffset += SIZEOF_UINT32$1;
  100308. tile.version = view.getUint32(byteOffset, true);
  100309. byteOffset += SIZEOF_UINT32$1;
  100310. tile.byteLength = view.getUint32(byteOffset, true);
  100311. byteOffset += SIZEOF_UINT32$1;
  100312. if (tile.version !== 1) {
  100313. throw new Error("3D Tile Version ".concat(tile.version, " not supported"));
  100314. }
  100315. return byteOffset;
  100316. }
  100317. const SIZEOF_UINT32 = 4;
  100318. const DEPRECATION_WARNING = 'b3dm tile in legacy format.';
  100319. function parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset) {
  100320. const view = new DataView(arrayBuffer);
  100321. let batchLength;
  100322. tile.header = tile.header || {};
  100323. let featureTableJsonByteLength = view.getUint32(byteOffset, true);
  100324. byteOffset += SIZEOF_UINT32;
  100325. let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
  100326. byteOffset += SIZEOF_UINT32;
  100327. let batchTableJsonByteLength = view.getUint32(byteOffset, true);
  100328. byteOffset += SIZEOF_UINT32;
  100329. let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
  100330. byteOffset += SIZEOF_UINT32;
  100331. if (batchTableJsonByteLength >= 570425344) {
  100332. byteOffset -= SIZEOF_UINT32 * 2;
  100333. batchLength = featureTableJsonByteLength;
  100334. batchTableJsonByteLength = featureTableBinaryByteLength;
  100335. batchTableBinaryByteLength = 0;
  100336. featureTableJsonByteLength = 0;
  100337. featureTableBinaryByteLength = 0;
  100338. console.warn(DEPRECATION_WARNING);
  100339. } else if (batchTableBinaryByteLength >= 570425344) {
  100340. byteOffset -= SIZEOF_UINT32;
  100341. batchLength = batchTableJsonByteLength;
  100342. batchTableJsonByteLength = featureTableJsonByteLength;
  100343. batchTableBinaryByteLength = featureTableBinaryByteLength;
  100344. featureTableJsonByteLength = 0;
  100345. featureTableBinaryByteLength = 0;
  100346. console.warn(DEPRECATION_WARNING);
  100347. }
  100348. tile.header.featureTableJsonByteLength = featureTableJsonByteLength;
  100349. tile.header.featureTableBinaryByteLength = featureTableBinaryByteLength;
  100350. tile.header.batchTableJsonByteLength = batchTableJsonByteLength;
  100351. tile.header.batchTableBinaryByteLength = batchTableBinaryByteLength;
  100352. tile.header.batchLength = batchLength;
  100353. return byteOffset;
  100354. }
  100355. function parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options) {
  100356. byteOffset = parse3DTileFeatureTable(tile, arrayBuffer, byteOffset);
  100357. byteOffset = parse3DTileBatchTable(tile, arrayBuffer, byteOffset);
  100358. return byteOffset;
  100359. }
  100360. function parse3DTileFeatureTable(tile, arrayBuffer, byteOffset, options) {
  100361. const {
  100362. featureTableJsonByteLength,
  100363. featureTableBinaryByteLength,
  100364. batchLength
  100365. } = tile.header;
  100366. tile.featureTableJson = {
  100367. BATCH_LENGTH: batchLength || 0
  100368. };
  100369. if (featureTableJsonByteLength > 0) {
  100370. const featureTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, featureTableJsonByteLength);
  100371. tile.featureTableJson = JSON.parse(featureTableString);
  100372. }
  100373. byteOffset += featureTableJsonByteLength;
  100374. tile.featureTableBinary = new Uint8Array(arrayBuffer, byteOffset, featureTableBinaryByteLength);
  100375. byteOffset += featureTableBinaryByteLength;
  100376. return byteOffset;
  100377. }
  100378. function parse3DTileBatchTable(tile, arrayBuffer, byteOffset, options) {
  100379. const {
  100380. batchTableJsonByteLength,
  100381. batchTableBinaryByteLength
  100382. } = tile.header;
  100383. if (batchTableJsonByteLength > 0) {
  100384. const batchTableString = getStringFromArrayBuffer(arrayBuffer, byteOffset, batchTableJsonByteLength);
  100385. tile.batchTableJson = JSON.parse(batchTableString);
  100386. byteOffset += batchTableJsonByteLength;
  100387. if (batchTableBinaryByteLength > 0) {
  100388. tile.batchTableBinary = new Uint8Array(arrayBuffer, byteOffset, batchTableBinaryByteLength);
  100389. tile.batchTableBinary = new Uint8Array(tile.batchTableBinary);
  100390. byteOffset += batchTableBinaryByteLength;
  100391. }
  100392. }
  100393. return byteOffset;
  100394. }
  100395. function normalize3DTileColorAttribute(tile, colors, batchTable) {
  100396. if (!colors && (!tile || !tile.batchIds || !batchTable)) {
  100397. return null;
  100398. }
  100399. const {
  100400. batchIds,
  100401. isRGB565,
  100402. pointCount
  100403. } = tile;
  100404. if (batchIds && batchTable) {
  100405. const colorArray = new Uint8ClampedArray(pointCount * 3);
  100406. for (let i = 0; i < pointCount; i++) {
  100407. const batchId = batchIds[i];
  100408. const dimensions = batchTable.getProperty(batchId, 'dimensions');
  100409. const color = dimensions.map(d => d * 255);
  100410. colorArray[i * 3] = color[0];
  100411. colorArray[i * 3 + 1] = color[1];
  100412. colorArray[i * 3 + 2] = color[2];
  100413. }
  100414. return {
  100415. type: GL$1.UNSIGNED_BYTE,
  100416. value: colorArray,
  100417. size: 3,
  100418. normalized: true
  100419. };
  100420. }
  100421. if (isRGB565) {
  100422. const colorArray = new Uint8ClampedArray(pointCount * 3);
  100423. for (let i = 0; i < pointCount; i++) {
  100424. const color = decodeRGB565(colors[i]);
  100425. colorArray[i * 3] = color[0];
  100426. colorArray[i * 3 + 1] = color[1];
  100427. colorArray[i * 3 + 2] = color[2];
  100428. }
  100429. return {
  100430. type: GL$1.UNSIGNED_BYTE,
  100431. value: colorArray,
  100432. size: 3,
  100433. normalized: true
  100434. };
  100435. }
  100436. if (colors && colors.length === pointCount * 3) {
  100437. return {
  100438. type: GL$1.UNSIGNED_BYTE,
  100439. value: colors,
  100440. size: 3,
  100441. normalized: true
  100442. };
  100443. }
  100444. return {
  100445. type: GL$1.UNSIGNED_BYTE,
  100446. value: colors,
  100447. size: 4,
  100448. normalized: true
  100449. };
  100450. }
  100451. const scratchNormal = new Vector3$1();
  100452. function normalize3DTileNormalAttribute(tile, normals) {
  100453. if (!normals) {
  100454. return null;
  100455. }
  100456. if (tile.isOctEncoded16P) {
  100457. const decodedArray = new Float32Array(tile.pointsLength * 3);
  100458. for (let i = 0; i < tile.pointsLength; i++) {
  100459. octDecode(normals[i * 2], normals[i * 2 + 1], scratchNormal);
  100460. scratchNormal.toArray(decodedArray, i * 3);
  100461. }
  100462. return {
  100463. type: GL$1.FLOAT,
  100464. size: 2,
  100465. value: decodedArray
  100466. };
  100467. }
  100468. return {
  100469. type: GL$1.FLOAT,
  100470. size: 2,
  100471. value: normals
  100472. };
  100473. }
  100474. function normalize3DTilePositionAttribute(tile, positions, options) {
  100475. if (!tile.isQuantized) {
  100476. return positions;
  100477. }
  100478. if (options['3d-tiles'] && options['3d-tiles'].decodeQuantizedPositions) {
  100479. tile.isQuantized = false;
  100480. return decodeQuantizedPositions(tile, positions);
  100481. }
  100482. return {
  100483. type: GL$1.UNSIGNED_SHORT,
  100484. value: positions,
  100485. size: 3,
  100486. normalized: true
  100487. };
  100488. }
  100489. function decodeQuantizedPositions(tile, positions) {
  100490. const scratchPosition = new Vector3$1();
  100491. const decodedArray = new Float32Array(tile.pointCount * 3);
  100492. for (let i = 0; i < tile.pointCount; i++) {
  100493. scratchPosition.set(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]).scale(1 / tile.quantizedRange).multiply(tile.quantizedVolumeScale).add(tile.quantizedVolumeOffset).toArray(decodedArray, i * 3);
  100494. }
  100495. return decodedArray;
  100496. }
  100497. async function parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context) {
  100498. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  100499. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  100500. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  100501. initializeTile(tile);
  100502. const {
  100503. featureTable,
  100504. batchTable
  100505. } = parsePointCloudTables(tile);
  100506. await parseDraco(tile, featureTable, batchTable, options, context);
  100507. parsePositions(tile, featureTable, options);
  100508. parseColors(tile, featureTable, batchTable);
  100509. parseNormals(tile, featureTable);
  100510. return byteOffset;
  100511. }
  100512. function initializeTile(tile) {
  100513. tile.attributes = {
  100514. positions: null,
  100515. colors: null,
  100516. normals: null,
  100517. batchIds: null
  100518. };
  100519. tile.isQuantized = false;
  100520. tile.isTranslucent = false;
  100521. tile.isRGB565 = false;
  100522. tile.isOctEncoded16P = false;
  100523. }
  100524. function parsePointCloudTables(tile) {
  100525. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  100526. const pointsLength = featureTable.getGlobalProperty('POINTS_LENGTH');
  100527. if (!Number.isFinite(pointsLength)) {
  100528. throw new Error('POINTS_LENGTH must be defined');
  100529. }
  100530. featureTable.featuresLength = pointsLength;
  100531. tile.featuresLength = pointsLength;
  100532. tile.pointsLength = pointsLength;
  100533. tile.pointCount = pointsLength;
  100534. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  100535. const batchTable = parseBatchIds(tile, featureTable);
  100536. return {
  100537. featureTable,
  100538. batchTable
  100539. };
  100540. }
  100541. function parsePositions(tile, featureTable, options) {
  100542. if (!tile.attributes.positions) {
  100543. if (featureTable.hasProperty('POSITION')) {
  100544. tile.attributes.positions = featureTable.getPropertyArray('POSITION', GL$1.FLOAT, 3);
  100545. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  100546. const positions = featureTable.getPropertyArray('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3);
  100547. tile.isQuantized = true;
  100548. tile.quantizedRange = (1 << 16) - 1;
  100549. tile.quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3);
  100550. if (!tile.quantizedVolumeScale) {
  100551. throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  100552. }
  100553. tile.quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3);
  100554. if (!tile.quantizedVolumeOffset) {
  100555. throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  100556. }
  100557. tile.attributes.positions = normalize3DTilePositionAttribute(tile, positions, options);
  100558. }
  100559. }
  100560. if (!tile.attributes.positions) {
  100561. throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');
  100562. }
  100563. }
  100564. function parseColors(tile, featureTable, batchTable) {
  100565. if (!tile.attributes.colors) {
  100566. let colors = null;
  100567. if (featureTable.hasProperty('RGBA')) {
  100568. colors = featureTable.getPropertyArray('RGBA', GL$1.UNSIGNED_BYTE, 4);
  100569. tile.isTranslucent = true;
  100570. } else if (featureTable.hasProperty('RGB')) {
  100571. colors = featureTable.getPropertyArray('RGB', GL$1.UNSIGNED_BYTE, 3);
  100572. } else if (featureTable.hasProperty('RGB565')) {
  100573. colors = featureTable.getPropertyArray('RGB565', GL$1.UNSIGNED_SHORT, 1);
  100574. tile.isRGB565 = true;
  100575. }
  100576. tile.attributes.colors = normalize3DTileColorAttribute(tile, colors, batchTable);
  100577. }
  100578. if (featureTable.hasProperty('CONSTANT_RGBA')) {
  100579. tile.constantRGBA = featureTable.getGlobalProperty('CONSTANT_RGBA', GL$1.UNSIGNED_BYTE, 4);
  100580. }
  100581. }
  100582. function parseNormals(tile, featureTable) {
  100583. if (!tile.attributes.normals) {
  100584. let normals = null;
  100585. if (featureTable.hasProperty('NORMAL')) {
  100586. normals = featureTable.getPropertyArray('NORMAL', GL$1.FLOAT, 3);
  100587. } else if (featureTable.hasProperty('NORMAL_OCT16P')) {
  100588. normals = featureTable.getPropertyArray('NORMAL_OCT16P', GL$1.UNSIGNED_BYTE, 2);
  100589. tile.isOctEncoded16P = true;
  100590. }
  100591. tile.attributes.normals = normalize3DTileNormalAttribute(tile, normals);
  100592. }
  100593. }
  100594. function parseBatchIds(tile, featureTable) {
  100595. let batchTable = null;
  100596. if (!tile.batchIds && featureTable.hasProperty('BATCH_ID')) {
  100597. tile.batchIds = featureTable.getPropertyArray('BATCH_ID', GL$1.UNSIGNED_SHORT, 1);
  100598. if (tile.batchIds) {
  100599. const batchFeatureLength = featureTable.getGlobalProperty('BATCH_LENGTH');
  100600. if (!batchFeatureLength) {
  100601. throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');
  100602. }
  100603. const {
  100604. batchTableJson,
  100605. batchTableBinary
  100606. } = tile;
  100607. batchTable = new Tile3DBatchTableParser(batchTableJson, batchTableBinary, batchFeatureLength);
  100608. }
  100609. }
  100610. return batchTable;
  100611. }
  100612. async function parseDraco(tile, featureTable, batchTable, options, context) {
  100613. let dracoBuffer;
  100614. let dracoFeatureTableProperties;
  100615. let dracoBatchTableProperties;
  100616. const batchTableDraco = tile.batchTableJson && tile.batchTableJson.extensions && tile.batchTableJson.extensions['3DTILES_draco_point_compression'];
  100617. if (batchTableDraco) {
  100618. dracoBatchTableProperties = batchTableDraco.properties;
  100619. }
  100620. const featureTableDraco = featureTable.getExtension('3DTILES_draco_point_compression');
  100621. if (featureTableDraco) {
  100622. dracoFeatureTableProperties = featureTableDraco.properties;
  100623. const dracoByteOffset = featureTableDraco.byteOffset;
  100624. const dracoByteLength = featureTableDraco.byteLength;
  100625. if (!dracoFeatureTableProperties || !Number.isFinite(dracoByteOffset) || !dracoByteLength) {
  100626. throw new Error('Draco properties, byteOffset, and byteLength must be defined');
  100627. }
  100628. dracoBuffer = tile.featureTableBinary.slice(dracoByteOffset, dracoByteOffset + dracoByteLength);
  100629. tile.hasPositions = Number.isFinite(dracoFeatureTableProperties.POSITION);
  100630. tile.hasColors = Number.isFinite(dracoFeatureTableProperties.RGB) || Number.isFinite(dracoFeatureTableProperties.RGBA);
  100631. tile.hasNormals = Number.isFinite(dracoFeatureTableProperties.NORMAL);
  100632. tile.hasBatchIds = Number.isFinite(dracoFeatureTableProperties.BATCH_ID);
  100633. tile.isTranslucent = Number.isFinite(dracoFeatureTableProperties.RGBA);
  100634. }
  100635. if (!dracoBuffer) {
  100636. return true;
  100637. }
  100638. const dracoData = {
  100639. buffer: dracoBuffer,
  100640. properties: { ...dracoFeatureTableProperties,
  100641. ...dracoBatchTableProperties
  100642. },
  100643. featureTableProperties: dracoFeatureTableProperties,
  100644. batchTableProperties: dracoBatchTableProperties,
  100645. dequantizeInShader: false
  100646. };
  100647. return await loadDraco(tile, dracoData, options, context);
  100648. }
  100649. async function loadDraco(tile, dracoData, options, context) {
  100650. const {
  100651. parse
  100652. } = context;
  100653. const dracoOptions = { ...options,
  100654. draco: { ...options.draco,
  100655. extraAttributes: dracoData.batchTableProperties || {}
  100656. }
  100657. };
  100658. delete dracoOptions['3d-tiles'];
  100659. const data = await parse(dracoData.buffer, DracoLoader, dracoOptions);
  100660. const decodedPositions = data.attributes.POSITION && data.attributes.POSITION.value;
  100661. const decodedColors = data.attributes.COLOR_0 && data.attributes.COLOR_0.value;
  100662. const decodedNormals = data.attributes.NORMAL && data.attributes.NORMAL.value;
  100663. const decodedBatchIds = data.attributes.BATCH_ID && data.attributes.BATCH_ID.value;
  100664. const isQuantizedDraco = decodedPositions && data.attributes.POSITION.value.quantization;
  100665. const isOctEncodedDraco = decodedNormals && data.attributes.NORMAL.value.quantization;
  100666. if (isQuantizedDraco) {
  100667. const quantization = data.POSITION.data.quantization;
  100668. const range = quantization.range;
  100669. tile.quantizedVolumeScale = new Vector3$1(range, range, range);
  100670. tile.quantizedVolumeOffset = new Vector3$1(quantization.minValues);
  100671. tile.quantizedRange = (1 << quantization.quantizationBits) - 1.0;
  100672. tile.isQuantizedDraco = true;
  100673. }
  100674. if (isOctEncodedDraco) {
  100675. tile.octEncodedRange = (1 << data.NORMAL.data.quantization.quantizationBits) - 1.0;
  100676. tile.isOctEncodedDraco = true;
  100677. }
  100678. const batchTableAttributes = {};
  100679. if (dracoData.batchTableProperties) {
  100680. for (const attributeName of Object.keys(dracoData.batchTableProperties)) {
  100681. if (data.attributes[attributeName] && data.attributes[attributeName].value) {
  100682. batchTableAttributes[attributeName.toLowerCase()] = data.attributes[attributeName].value;
  100683. }
  100684. }
  100685. }
  100686. tile.attributes = {
  100687. positions: decodedPositions,
  100688. colors: normalize3DTileColorAttribute(tile, decodedColors, undefined),
  100689. normals: decodedNormals,
  100690. batchIds: decodedBatchIds,
  100691. ...batchTableAttributes
  100692. };
  100693. }
  100694. const VERSION$3 = "3.1.4" ;
  100695. const VERSION$2 = "3.1.4" ;
  100696. const VERSION$1 = "3.1.4" ;
  100697. const BASIS_CDN_ENCODER_WASM = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.wasm");
  100698. const BASIS_CDN_ENCODER_JS = "https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1, "/dist/libs/basis_encoder.js");
  100699. let loadBasisTranscoderPromise;
  100700. async function loadBasisTrascoderModule(options) {
  100701. const modules = options.modules || {};
  100702. if (modules.basis) {
  100703. return modules.basis;
  100704. }
  100705. loadBasisTranscoderPromise = loadBasisTranscoderPromise || loadBasisTrascoder(options);
  100706. return await loadBasisTranscoderPromise;
  100707. }
  100708. async function loadBasisTrascoder(options) {
  100709. let BASIS = null;
  100710. let wasmBinary = null;
  100711. [BASIS, wasmBinary] = await Promise.all([await loadLibrary('basis_transcoder.js', 'textures', options), await loadLibrary('basis_transcoder.wasm', 'textures', options)]);
  100712. BASIS = BASIS || globalThis.BASIS;
  100713. return await initializeBasisTrascoderModule(BASIS, wasmBinary);
  100714. }
  100715. function initializeBasisTrascoderModule(BasisModule, wasmBinary) {
  100716. const options = {};
  100717. if (wasmBinary) {
  100718. options.wasmBinary = wasmBinary;
  100719. }
  100720. return new Promise(resolve => {
  100721. BasisModule(options).then(module => {
  100722. const {
  100723. BasisFile,
  100724. initializeBasis
  100725. } = module;
  100726. initializeBasis();
  100727. resolve({
  100728. BasisFile
  100729. });
  100730. });
  100731. });
  100732. }
  100733. let loadBasisEncoderPromise;
  100734. async function loadBasisEncoderModule(options) {
  100735. const modules = options.modules || {};
  100736. if (modules.basisEncoder) {
  100737. return modules.basisEncoder;
  100738. }
  100739. loadBasisEncoderPromise = loadBasisEncoderPromise || loadBasisEncoder(options);
  100740. return await loadBasisEncoderPromise;
  100741. }
  100742. async function loadBasisEncoder(options) {
  100743. let BASIS_ENCODER = null;
  100744. let wasmBinary = null;
  100745. [BASIS_ENCODER, wasmBinary] = await Promise.all([await loadLibrary(BASIS_CDN_ENCODER_JS, 'textures', options), await loadLibrary(BASIS_CDN_ENCODER_WASM, 'textures', options)]);
  100746. BASIS_ENCODER = BASIS_ENCODER || globalThis.BASIS;
  100747. return await initializeBasisEncoderModule(BASIS_ENCODER, wasmBinary);
  100748. }
  100749. function initializeBasisEncoderModule(BasisEncoderModule, wasmBinary) {
  100750. const options = {};
  100751. if (wasmBinary) {
  100752. options.wasmBinary = wasmBinary;
  100753. }
  100754. return new Promise(resolve => {
  100755. BasisEncoderModule(options).then(module => {
  100756. const {
  100757. BasisFile,
  100758. KTX2File,
  100759. initializeBasis,
  100760. BasisEncoder
  100761. } = module;
  100762. initializeBasis();
  100763. resolve({
  100764. BasisFile,
  100765. KTX2File,
  100766. BasisEncoder
  100767. });
  100768. });
  100769. });
  100770. }
  100771. const GL_EXTENSIONS_CONSTANTS = {
  100772. COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83f0,
  100773. COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83f1,
  100774. COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83f2,
  100775. COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83f3,
  100776. COMPRESSED_R11_EAC: 0x9270,
  100777. COMPRESSED_SIGNED_R11_EAC: 0x9271,
  100778. COMPRESSED_RG11_EAC: 0x9272,
  100779. COMPRESSED_SIGNED_RG11_EAC: 0x9273,
  100780. COMPRESSED_RGB8_ETC2: 0x9274,
  100781. COMPRESSED_RGBA8_ETC2_EAC: 0x9275,
  100782. COMPRESSED_SRGB8_ETC2: 0x9276,
  100783. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: 0x9277,
  100784. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9278,
  100785. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: 0x9279,
  100786. COMPRESSED_RGB_PVRTC_4BPPV1_IMG: 0x8c00,
  100787. COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: 0x8c02,
  100788. COMPRESSED_RGB_PVRTC_2BPPV1_IMG: 0x8c01,
  100789. COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: 0x8c03,
  100790. COMPRESSED_RGB_ETC1_WEBGL: 0x8d64,
  100791. COMPRESSED_RGB_ATC_WEBGL: 0x8c92,
  100792. COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL: 0x8c93,
  100793. COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL: 0x87ee,
  100794. COMPRESSED_RGBA_ASTC_4X4_KHR: 0x93b0,
  100795. COMPRESSED_RGBA_ASTC_5X4_KHR: 0x93b1,
  100796. COMPRESSED_RGBA_ASTC_5X5_KHR: 0x93b2,
  100797. COMPRESSED_RGBA_ASTC_6X5_KHR: 0x93b3,
  100798. COMPRESSED_RGBA_ASTC_6X6_KHR: 0x93b4,
  100799. COMPRESSED_RGBA_ASTC_8X5_KHR: 0x93b5,
  100800. COMPRESSED_RGBA_ASTC_8X6_KHR: 0x93b6,
  100801. COMPRESSED_RGBA_ASTC_8X8_KHR: 0x93b7,
  100802. COMPRESSED_RGBA_ASTC_10X5_KHR: 0x93b8,
  100803. COMPRESSED_RGBA_ASTC_10X6_KHR: 0x93b9,
  100804. COMPRESSED_RGBA_ASTC_10X8_KHR: 0x93ba,
  100805. COMPRESSED_RGBA_ASTC_10X10_KHR: 0x93bb,
  100806. COMPRESSED_RGBA_ASTC_12X10_KHR: 0x93bc,
  100807. COMPRESSED_RGBA_ASTC_12X12_KHR: 0x93bd,
  100808. COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR: 0x93d0,
  100809. COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR: 0x93d1,
  100810. COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR: 0x93d2,
  100811. COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR: 0x93d3,
  100812. COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR: 0x93d4,
  100813. COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR: 0x93d5,
  100814. COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR: 0x93d6,
  100815. COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR: 0x93d7,
  100816. COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR: 0x93d8,
  100817. COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR: 0x93d9,
  100818. COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR: 0x93da,
  100819. COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR: 0x93db,
  100820. COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR: 0x93dc,
  100821. COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR: 0x93dd,
  100822. COMPRESSED_RED_RGTC1_EXT: 0x8dbb,
  100823. COMPRESSED_SIGNED_RED_RGTC1_EXT: 0x8dbc,
  100824. COMPRESSED_RED_GREEN_RGTC2_EXT: 0x8dbd,
  100825. COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: 0x8dbe,
  100826. COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8c4c,
  100827. COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8c4d,
  100828. COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8c4e,
  100829. COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8c4f
  100830. };
  100831. const BROWSER_PREFIXES = ['', 'WEBKIT_', 'MOZ_'];
  100832. const WEBGL_EXTENSIONS = {
  100833. WEBGL_compressed_texture_s3tc: 'dxt',
  100834. WEBGL_compressed_texture_s3tc_srgb: 'dxt-srgb',
  100835. WEBGL_compressed_texture_etc1: 'etc1',
  100836. WEBGL_compressed_texture_etc: 'etc2',
  100837. WEBGL_compressed_texture_pvrtc: 'pvrtc',
  100838. WEBGL_compressed_texture_atc: 'atc',
  100839. WEBGL_compressed_texture_astc: 'astc',
  100840. EXT_texture_compression_rgtc: 'rgtc'
  100841. };
  100842. let formats = null;
  100843. function getSupportedGPUTextureFormats(gl) {
  100844. if (!formats) {
  100845. gl = gl || getWebGLContext() || undefined;
  100846. formats = new Set();
  100847. for (const prefix of BROWSER_PREFIXES) {
  100848. for (const extension in WEBGL_EXTENSIONS) {
  100849. if (gl && gl.getExtension("".concat(prefix).concat(extension))) {
  100850. const gpuTextureFormat = WEBGL_EXTENSIONS[extension];
  100851. formats.add(gpuTextureFormat);
  100852. }
  100853. }
  100854. }
  100855. }
  100856. return formats;
  100857. }
  100858. function getWebGLContext() {
  100859. try {
  100860. const canvas = document.createElement('canvas');
  100861. return canvas.getContext('webgl');
  100862. } catch (error) {
  100863. return null;
  100864. }
  100865. }
  100866. var n$2,i$2,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$2||(i$2={})),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={}));
  100867. const KTX2_ID = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
  100868. function isKTX(data) {
  100869. const id = new Uint8Array(data);
  100870. const notKTX = id.byteLength < KTX2_ID.length || id[0] !== KTX2_ID[0] || id[1] !== KTX2_ID[1] || id[2] !== KTX2_ID[2] || id[3] !== KTX2_ID[3] || id[4] !== KTX2_ID[4] || id[5] !== KTX2_ID[5] || id[6] !== KTX2_ID[6] || id[7] !== KTX2_ID[7] || id[8] !== KTX2_ID[8] || id[9] !== KTX2_ID[9] || id[10] !== KTX2_ID[10] || id[11] !== KTX2_ID[11];
  100871. return !notKTX;
  100872. }
  100873. const OutputFormat = {
  100874. etc1: {
  100875. basisFormat: 0,
  100876. compressed: true,
  100877. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL
  100878. },
  100879. etc2: {
  100880. basisFormat: 1,
  100881. compressed: true
  100882. },
  100883. bc1: {
  100884. basisFormat: 2,
  100885. compressed: true,
  100886. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT
  100887. },
  100888. bc3: {
  100889. basisFormat: 3,
  100890. compressed: true,
  100891. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT
  100892. },
  100893. bc4: {
  100894. basisFormat: 4,
  100895. compressed: true
  100896. },
  100897. bc5: {
  100898. basisFormat: 5,
  100899. compressed: true
  100900. },
  100901. 'bc7-m6-opaque-only': {
  100902. basisFormat: 6,
  100903. compressed: true
  100904. },
  100905. 'bc7-m5': {
  100906. basisFormat: 7,
  100907. compressed: true
  100908. },
  100909. 'pvrtc1-4-rgb': {
  100910. basisFormat: 8,
  100911. compressed: true,
  100912. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  100913. },
  100914. 'pvrtc1-4-rgba': {
  100915. basisFormat: 9,
  100916. compressed: true,
  100917. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  100918. },
  100919. 'astc-4x4': {
  100920. basisFormat: 10,
  100921. compressed: true,
  100922. format: GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR
  100923. },
  100924. 'atc-rgb': {
  100925. basisFormat: 11,
  100926. compressed: true
  100927. },
  100928. 'atc-rgba-interpolated-alpha': {
  100929. basisFormat: 12,
  100930. compressed: true
  100931. },
  100932. rgba32: {
  100933. basisFormat: 13,
  100934. compressed: false
  100935. },
  100936. rgb565: {
  100937. basisFormat: 14,
  100938. compressed: false
  100939. },
  100940. bgr565: {
  100941. basisFormat: 15,
  100942. compressed: false
  100943. },
  100944. rgba4444: {
  100945. basisFormat: 16,
  100946. compressed: false
  100947. }
  100948. };
  100949. async function parseBasis(data, options) {
  100950. if (options.basis.containerFormat === 'auto') {
  100951. if (isKTX(data)) {
  100952. const fileConstructors = await loadBasisEncoderModule(options);
  100953. return parseKTX2File(fileConstructors.KTX2File, data, options);
  100954. }
  100955. const {
  100956. BasisFile
  100957. } = await loadBasisTrascoderModule(options);
  100958. return parseBasisFile(BasisFile, data, options);
  100959. }
  100960. switch (options.basis.module) {
  100961. case 'encoder':
  100962. const fileConstructors = await loadBasisEncoderModule(options);
  100963. switch (options.basis.containerFormat) {
  100964. case 'ktx2':
  100965. return parseKTX2File(fileConstructors.KTX2File, data, options);
  100966. case 'basis':
  100967. default:
  100968. return parseBasisFile(fileConstructors.BasisFile, data, options);
  100969. }
  100970. case 'transcoder':
  100971. default:
  100972. const {
  100973. BasisFile
  100974. } = await loadBasisTrascoderModule(options);
  100975. return parseBasisFile(BasisFile, data, options);
  100976. }
  100977. }
  100978. function parseBasisFile(BasisFile, data, options) {
  100979. const basisFile = new BasisFile(new Uint8Array(data));
  100980. try {
  100981. if (!basisFile.startTranscoding()) {
  100982. return null;
  100983. }
  100984. const imageCount = basisFile.getNumImages();
  100985. const images = [];
  100986. for (let imageIndex = 0; imageIndex < imageCount; imageIndex++) {
  100987. const levelsCount = basisFile.getNumLevels(imageIndex);
  100988. const levels = [];
  100989. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  100990. levels.push(transcodeImage(basisFile, imageIndex, levelIndex, options));
  100991. }
  100992. images.push(levels);
  100993. }
  100994. return images;
  100995. } finally {
  100996. basisFile.close();
  100997. basisFile.delete();
  100998. }
  100999. }
  101000. function transcodeImage(basisFile, imageIndex, levelIndex, options) {
  101001. const width = basisFile.getImageWidth(imageIndex, levelIndex);
  101002. const height = basisFile.getImageHeight(imageIndex, levelIndex);
  101003. const hasAlpha = basisFile.getHasAlpha();
  101004. const {
  101005. compressed,
  101006. format,
  101007. basisFormat
  101008. } = getBasisOptions(options, hasAlpha);
  101009. const decodedSize = basisFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, basisFormat);
  101010. const decodedData = new Uint8Array(decodedSize);
  101011. if (!basisFile.transcodeImage(decodedData, imageIndex, levelIndex, basisFormat, 0, 0)) {
  101012. return null;
  101013. }
  101014. return {
  101015. width,
  101016. height,
  101017. data: decodedData,
  101018. compressed,
  101019. hasAlpha,
  101020. format
  101021. };
  101022. }
  101023. function parseKTX2File(KTX2File, data, options) {
  101024. const ktx2File = new KTX2File(new Uint8Array(data));
  101025. try {
  101026. if (!ktx2File.startTranscoding()) {
  101027. return null;
  101028. }
  101029. const levelsCount = ktx2File.getLevels();
  101030. const levels = [];
  101031. for (let levelIndex = 0; levelIndex < levelsCount; levelIndex++) {
  101032. levels.push(transcodeKTX2Image(ktx2File, levelIndex, options));
  101033. break;
  101034. }
  101035. return levels;
  101036. } finally {
  101037. ktx2File.close();
  101038. ktx2File.delete();
  101039. }
  101040. }
  101041. function transcodeKTX2Image(ktx2File, levelIndex, options) {
  101042. const {
  101043. alphaFlag,
  101044. height,
  101045. width
  101046. } = ktx2File.getImageLevelInfo(levelIndex, 0, 0);
  101047. const {
  101048. compressed,
  101049. format,
  101050. basisFormat
  101051. } = getBasisOptions(options, alphaFlag);
  101052. const decodedSize = ktx2File.getImageTranscodedSizeInBytes(levelIndex, 0, 0, basisFormat);
  101053. const decodedData = new Uint8Array(decodedSize);
  101054. if (!ktx2File.transcodeImage(decodedData, levelIndex, 0, 0, basisFormat, 0, -1, -1)) {
  101055. return null;
  101056. }
  101057. return {
  101058. width,
  101059. height,
  101060. data: decodedData,
  101061. compressed,
  101062. alphaFlag,
  101063. format
  101064. };
  101065. }
  101066. function getBasisOptions(options, hasAlpha) {
  101067. let format = options && options.basis && options.basis.format;
  101068. if (format === 'auto') {
  101069. format = selectSupportedBasisFormat();
  101070. }
  101071. if (typeof format === 'object') {
  101072. format = hasAlpha ? format.alpha : format.noAlpha;
  101073. }
  101074. format = format.toLowerCase();
  101075. return OutputFormat[format];
  101076. }
  101077. function selectSupportedBasisFormat() {
  101078. const supportedFormats = getSupportedGPUTextureFormats();
  101079. if (supportedFormats.has('astc')) {
  101080. return 'astc-4x4';
  101081. } else if (supportedFormats.has('dxt')) {
  101082. return {
  101083. alpha: 'bc3',
  101084. noAlpha: 'bc1'
  101085. };
  101086. } else if (supportedFormats.has('pvrtc')) {
  101087. return {
  101088. alpha: 'pvrtc1-4-rgba',
  101089. noAlpha: 'pvrtc1-4-rgb'
  101090. };
  101091. } else if (supportedFormats.has('etc1')) {
  101092. return 'etc1';
  101093. } else if (supportedFormats.has('etc2')) {
  101094. return 'etc2';
  101095. }
  101096. return 'rgb565';
  101097. }
  101098. const BasisWorkerLoader = {
  101099. name: 'Basis',
  101100. id: 'basis',
  101101. module: 'textures',
  101102. version: VERSION$2,
  101103. worker: true,
  101104. extensions: ['basis', 'ktx2'],
  101105. mimeTypes: ['application/octet-stream', 'image/ktx2'],
  101106. tests: ['sB'],
  101107. binary: true,
  101108. options: {
  101109. basis: {
  101110. format: 'auto',
  101111. libraryPath: 'libs/',
  101112. containerFormat: 'auto',
  101113. module: 'transcoder'
  101114. }
  101115. }
  101116. };
  101117. const BasisLoader = { ...BasisWorkerLoader,
  101118. parse: parseBasis
  101119. };
  101120. const VERSION = "3.1.4" ;
  101121. const {
  101122. _parseImageNode
  101123. } = globalThis;
  101124. const IMAGE_SUPPORTED = typeof Image !== 'undefined';
  101125. const IMAGE_BITMAP_SUPPORTED = typeof ImageBitmap !== 'undefined';
  101126. const NODE_IMAGE_SUPPORTED = Boolean(_parseImageNode);
  101127. const DATA_SUPPORTED = isBrowser$2 ? true : NODE_IMAGE_SUPPORTED;
  101128. function isImageTypeSupported(type) {
  101129. switch (type) {
  101130. case 'auto':
  101131. return IMAGE_BITMAP_SUPPORTED || IMAGE_SUPPORTED || DATA_SUPPORTED;
  101132. case 'imagebitmap':
  101133. return IMAGE_BITMAP_SUPPORTED;
  101134. case 'image':
  101135. return IMAGE_SUPPORTED;
  101136. case 'data':
  101137. return DATA_SUPPORTED;
  101138. default:
  101139. throw new Error("@loaders.gl/images: image ".concat(type, " not supported in this environment"));
  101140. }
  101141. }
  101142. function getDefaultImageType() {
  101143. if (IMAGE_BITMAP_SUPPORTED) {
  101144. return 'imagebitmap';
  101145. }
  101146. if (IMAGE_SUPPORTED) {
  101147. return 'image';
  101148. }
  101149. if (DATA_SUPPORTED) {
  101150. return 'data';
  101151. }
  101152. throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');
  101153. }
  101154. function getImageType(image) {
  101155. const format = getImageTypeOrNull(image);
  101156. if (!format) {
  101157. throw new Error('Not an image');
  101158. }
  101159. return format;
  101160. }
  101161. function getImageData(image) {
  101162. switch (getImageType(image)) {
  101163. case 'data':
  101164. return image;
  101165. case 'image':
  101166. case 'imagebitmap':
  101167. const canvas = document.createElement('canvas');
  101168. const context = canvas.getContext('2d');
  101169. if (!context) {
  101170. throw new Error('getImageData');
  101171. }
  101172. canvas.width = image.width;
  101173. canvas.height = image.height;
  101174. context.drawImage(image, 0, 0);
  101175. return context.getImageData(0, 0, image.width, image.height);
  101176. default:
  101177. throw new Error('getImageData');
  101178. }
  101179. }
  101180. function getImageTypeOrNull(image) {
  101181. if (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  101182. return 'imagebitmap';
  101183. }
  101184. if (typeof Image !== 'undefined' && image instanceof Image) {
  101185. return 'image';
  101186. }
  101187. if (image && typeof image === 'object' && image.data && image.width && image.height) {
  101188. return 'data';
  101189. }
  101190. return null;
  101191. }
  101192. const SVG_DATA_URL_PATTERN = /^data:image\/svg\+xml/;
  101193. const SVG_URL_PATTERN = /\.svg((\?|#).*)?$/;
  101194. function isSVG(url) {
  101195. return url && (SVG_DATA_URL_PATTERN.test(url) || SVG_URL_PATTERN.test(url));
  101196. }
  101197. function getBlobOrSVGDataUrl(arrayBuffer, url) {
  101198. if (isSVG(url)) {
  101199. const textDecoder = new TextDecoder();
  101200. let xmlText = textDecoder.decode(arrayBuffer);
  101201. try {
  101202. if (typeof unescape === 'function' && typeof encodeURIComponent === 'function') {
  101203. xmlText = unescape(encodeURIComponent(xmlText));
  101204. }
  101205. } catch (error) {
  101206. throw new Error(error.message);
  101207. }
  101208. const src = "data:image/svg+xml;base64,".concat(btoa(xmlText));
  101209. return src;
  101210. }
  101211. return getBlob(arrayBuffer, url);
  101212. }
  101213. function getBlob(arrayBuffer, url) {
  101214. if (isSVG(url)) {
  101215. throw new Error('SVG cannot be parsed directly to imagebitmap');
  101216. }
  101217. return new Blob([new Uint8Array(arrayBuffer)]);
  101218. }
  101219. async function parseToImage(arrayBuffer, options, url) {
  101220. const blobOrDataUrl = getBlobOrSVGDataUrl(arrayBuffer, url);
  101221. const URL = self.URL || self.webkitURL;
  101222. const objectUrl = typeof blobOrDataUrl !== 'string' && URL.createObjectURL(blobOrDataUrl);
  101223. try {
  101224. return await loadToImage(objectUrl || blobOrDataUrl, options);
  101225. } finally {
  101226. if (objectUrl) {
  101227. URL.revokeObjectURL(objectUrl);
  101228. }
  101229. }
  101230. }
  101231. async function loadToImage(url, options) {
  101232. const image = new Image();
  101233. image.src = url;
  101234. if (options.image && options.image.decode && image.decode) {
  101235. await image.decode();
  101236. return image;
  101237. }
  101238. return await new Promise((resolve, reject) => {
  101239. try {
  101240. image.onload = () => resolve(image);
  101241. image.onerror = err => reject(new Error("Could not load image ".concat(url, ": ").concat(err)));
  101242. } catch (error) {
  101243. reject(error);
  101244. }
  101245. });
  101246. }
  101247. const EMPTY_OBJECT = {};
  101248. let imagebitmapOptionsSupported = true;
  101249. async function parseToImageBitmap(arrayBuffer, options, url) {
  101250. let blob;
  101251. if (isSVG(url)) {
  101252. const image = await parseToImage(arrayBuffer, options, url);
  101253. blob = image;
  101254. } else {
  101255. blob = getBlob(arrayBuffer, url);
  101256. }
  101257. const imagebitmapOptions = options && options.imagebitmap;
  101258. return await safeCreateImageBitmap(blob, imagebitmapOptions);
  101259. }
  101260. async function safeCreateImageBitmap(blob, imagebitmapOptions = null) {
  101261. if (isEmptyObject(imagebitmapOptions) || !imagebitmapOptionsSupported) {
  101262. imagebitmapOptions = null;
  101263. }
  101264. if (imagebitmapOptions) {
  101265. try {
  101266. return await createImageBitmap(blob, imagebitmapOptions);
  101267. } catch (error) {
  101268. console.warn(error);
  101269. imagebitmapOptionsSupported = false;
  101270. }
  101271. }
  101272. return await createImageBitmap(blob);
  101273. }
  101274. function isEmptyObject(object) {
  101275. for (const key in object || EMPTY_OBJECT) {
  101276. return false;
  101277. }
  101278. return true;
  101279. }
  101280. const BIG_ENDIAN = false;
  101281. const LITTLE_ENDIAN = true;
  101282. function getBinaryImageMetadata(binaryData) {
  101283. const dataView = toDataView(binaryData);
  101284. return getPngMetadata(dataView) || getJpegMetadata(dataView) || getGifMetadata(dataView) || getBmpMetadata(dataView);
  101285. }
  101286. function getPngMetadata(binaryData) {
  101287. const dataView = toDataView(binaryData);
  101288. const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;
  101289. if (!isPng) {
  101290. return null;
  101291. }
  101292. return {
  101293. mimeType: 'image/png',
  101294. width: dataView.getUint32(16, BIG_ENDIAN),
  101295. height: dataView.getUint32(20, BIG_ENDIAN)
  101296. };
  101297. }
  101298. function getGifMetadata(binaryData) {
  101299. const dataView = toDataView(binaryData);
  101300. const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;
  101301. if (!isGif) {
  101302. return null;
  101303. }
  101304. return {
  101305. mimeType: 'image/gif',
  101306. width: dataView.getUint16(6, LITTLE_ENDIAN),
  101307. height: dataView.getUint16(8, LITTLE_ENDIAN)
  101308. };
  101309. }
  101310. function getBmpMetadata(binaryData) {
  101311. const dataView = toDataView(binaryData);
  101312. const isBmp = dataView.byteLength >= 14 && dataView.getUint16(0, BIG_ENDIAN) === 0x424d && dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;
  101313. if (!isBmp) {
  101314. return null;
  101315. }
  101316. return {
  101317. mimeType: 'image/bmp',
  101318. width: dataView.getUint32(18, LITTLE_ENDIAN),
  101319. height: dataView.getUint32(22, LITTLE_ENDIAN)
  101320. };
  101321. }
  101322. function getJpegMetadata(binaryData) {
  101323. const dataView = toDataView(binaryData);
  101324. const isJpeg = dataView.byteLength >= 3 && dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 && dataView.getUint8(2) === 0xff;
  101325. if (!isJpeg) {
  101326. return null;
  101327. }
  101328. const {
  101329. tableMarkers,
  101330. sofMarkers
  101331. } = getJpegMarkers();
  101332. let i = 2;
  101333. while (i + 9 < dataView.byteLength) {
  101334. const marker = dataView.getUint16(i, BIG_ENDIAN);
  101335. if (sofMarkers.has(marker)) {
  101336. return {
  101337. mimeType: 'image/jpeg',
  101338. height: dataView.getUint16(i + 5, BIG_ENDIAN),
  101339. width: dataView.getUint16(i + 7, BIG_ENDIAN)
  101340. };
  101341. }
  101342. if (!tableMarkers.has(marker)) {
  101343. return null;
  101344. }
  101345. i += 2;
  101346. i += dataView.getUint16(i, BIG_ENDIAN);
  101347. }
  101348. return null;
  101349. }
  101350. function getJpegMarkers() {
  101351. const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);
  101352. for (let i = 0xffe0; i < 0xfff0; ++i) {
  101353. tableMarkers.add(i);
  101354. }
  101355. const sofMarkers = new Set([0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce, 0xffcf, 0xffde]);
  101356. return {
  101357. tableMarkers,
  101358. sofMarkers
  101359. };
  101360. }
  101361. function toDataView(data) {
  101362. if (data instanceof DataView) {
  101363. return data;
  101364. }
  101365. if (ArrayBuffer.isView(data)) {
  101366. return new DataView(data.buffer);
  101367. }
  101368. if (data instanceof ArrayBuffer) {
  101369. return new DataView(data);
  101370. }
  101371. throw new Error('toDataView');
  101372. }
  101373. async function parseToNodeImage(arrayBuffer, options) {
  101374. const {
  101375. mimeType
  101376. } = getBinaryImageMetadata(arrayBuffer) || {};
  101377. const _parseImageNode = globalThis._parseImageNode;
  101378. assert$7(_parseImageNode);
  101379. return await _parseImageNode(arrayBuffer, mimeType);
  101380. }
  101381. async function parseImage(arrayBuffer, options, context) {
  101382. options = options || {};
  101383. const imageOptions = options.image || {};
  101384. const imageType = imageOptions.type || 'auto';
  101385. const {
  101386. url
  101387. } = context || {};
  101388. const loadType = getLoadableImageType(imageType);
  101389. let image;
  101390. switch (loadType) {
  101391. case 'imagebitmap':
  101392. image = await parseToImageBitmap(arrayBuffer, options, url);
  101393. break;
  101394. case 'image':
  101395. image = await parseToImage(arrayBuffer, options, url);
  101396. break;
  101397. case 'data':
  101398. image = await parseToNodeImage(arrayBuffer);
  101399. break;
  101400. default:
  101401. assert$7(false);
  101402. }
  101403. if (imageType === 'data') {
  101404. image = getImageData(image);
  101405. }
  101406. return image;
  101407. }
  101408. function getLoadableImageType(type) {
  101409. switch (type) {
  101410. case 'auto':
  101411. case 'data':
  101412. return getDefaultImageType();
  101413. default:
  101414. isImageTypeSupported(type);
  101415. return type;
  101416. }
  101417. }
  101418. const EXTENSIONS$1 = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg'];
  101419. const MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/vnd.microsoft.icon', 'image/svg+xml'];
  101420. const DEFAULT_IMAGE_LOADER_OPTIONS = {
  101421. image: {
  101422. type: 'auto',
  101423. decode: true
  101424. }
  101425. };
  101426. const ImageLoader$1 = {
  101427. id: 'image',
  101428. module: 'images',
  101429. name: 'Images',
  101430. version: VERSION,
  101431. mimeTypes: MIME_TYPES,
  101432. extensions: EXTENSIONS$1,
  101433. parse: parseImage,
  101434. tests: [arrayBuffer => Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],
  101435. options: DEFAULT_IMAGE_LOADER_OPTIONS
  101436. };
  101437. const NODE_FORMAT_SUPPORT = ['image/png', 'image/jpeg', 'image/gif'];
  101438. const mimeTypeSupported = {};
  101439. function _isImageFormatSupported(mimeType) {
  101440. if (mimeTypeSupported[mimeType] === undefined) {
  101441. mimeTypeSupported[mimeType] = checkFormatSupport(mimeType);
  101442. }
  101443. return mimeTypeSupported[mimeType];
  101444. }
  101445. function checkFormatSupport(mimeType) {
  101446. switch (mimeType) {
  101447. case 'image/webp':
  101448. return checkWebPSupport();
  101449. case 'image/svg':
  101450. return isBrowser$2;
  101451. default:
  101452. if (!isBrowser$2) {
  101453. const {
  101454. _parseImageNode
  101455. } = globalThis;
  101456. return Boolean(_parseImageNode) && NODE_FORMAT_SUPPORT.includes(mimeType);
  101457. }
  101458. return true;
  101459. }
  101460. }
  101461. function checkWebPSupport() {
  101462. if (!isBrowser$2) {
  101463. return false;
  101464. }
  101465. try {
  101466. const element = document.createElement('canvas');
  101467. return element.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  101468. } catch {
  101469. return false;
  101470. }
  101471. }
  101472. function assert$1(condition, message) {
  101473. if (!condition) {
  101474. throw new Error(message || 'assert failed: gltf');
  101475. }
  101476. }
  101477. function resolveUrl(url, options) {
  101478. const absolute = url.startsWith('data:') || url.startsWith('http:') || url.startsWith('https:');
  101479. if (absolute) {
  101480. return url;
  101481. }
  101482. const baseUrl = options.baseUri || options.uri;
  101483. if (!baseUrl) {
  101484. throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));
  101485. }
  101486. return baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1) + url;
  101487. }
  101488. function getTypedArrayForBufferView(json, buffers, bufferViewIndex) {
  101489. const bufferView = json.bufferViews[bufferViewIndex];
  101490. assert$1(bufferView);
  101491. const bufferIndex = bufferView.buffer;
  101492. const binChunk = buffers[bufferIndex];
  101493. assert$1(binChunk);
  101494. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  101495. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  101496. }
  101497. const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
  101498. const ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT = [[Int8Array, 5120], [Uint8Array, 5121], [Int16Array, 5122], [Uint16Array, 5123], [Uint32Array, 5125], [Float32Array, 5126], [Float64Array, 5130]];
  101499. const ARRAY_TO_COMPONENT_TYPE = new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);
  101500. const ATTRIBUTE_TYPE_TO_COMPONENTS = {
  101501. SCALAR: 1,
  101502. VEC2: 2,
  101503. VEC3: 3,
  101504. VEC4: 4,
  101505. MAT2: 4,
  101506. MAT3: 9,
  101507. MAT4: 16
  101508. };
  101509. const ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE = {
  101510. 5120: 1,
  101511. 5121: 1,
  101512. 5122: 2,
  101513. 5123: 2,
  101514. 5125: 4,
  101515. 5126: 4
  101516. };
  101517. const ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY = {
  101518. 5120: Int8Array,
  101519. 5121: Uint8Array,
  101520. 5122: Int16Array,
  101521. 5123: Uint16Array,
  101522. 5125: Uint32Array,
  101523. 5126: Float32Array
  101524. };
  101525. function getAccessorTypeFromSize(size) {
  101526. const type = TYPES[size - 1];
  101527. return type || TYPES[0];
  101528. }
  101529. function getComponentTypeFromArray(typedArray) {
  101530. const componentType = ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);
  101531. if (!componentType) {
  101532. throw new Error('Illegal typed array');
  101533. }
  101534. return componentType;
  101535. }
  101536. function getAccessorArrayTypeAndLength(accessor, bufferView) {
  101537. const ArrayType = ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];
  101538. const components = ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];
  101539. const bytesPerComponent = ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];
  101540. const length = accessor.count * components;
  101541. const byteLength = accessor.count * components * bytesPerComponent;
  101542. assert$1(byteLength >= 0 && byteLength <= bufferView.byteLength);
  101543. return {
  101544. ArrayType,
  101545. length,
  101546. byteLength
  101547. };
  101548. }
  101549. const DEFAULT_GLTF_JSON = {
  101550. asset: {
  101551. version: '2.0',
  101552. generator: 'loaders.gl'
  101553. },
  101554. buffers: []
  101555. };
  101556. class GLTFScenegraph {
  101557. constructor(gltf) {
  101558. _defineProperty(this, "gltf", void 0);
  101559. _defineProperty(this, "sourceBuffers", void 0);
  101560. _defineProperty(this, "byteLength", void 0);
  101561. this.gltf = gltf || {
  101562. json: { ...DEFAULT_GLTF_JSON
  101563. },
  101564. buffers: []
  101565. };
  101566. this.sourceBuffers = [];
  101567. this.byteLength = 0;
  101568. if (this.gltf.buffers && this.gltf.buffers[0]) {
  101569. this.byteLength = this.gltf.buffers[0].byteLength;
  101570. this.sourceBuffers = [this.gltf.buffers[0]];
  101571. }
  101572. }
  101573. get json() {
  101574. return this.gltf.json;
  101575. }
  101576. getApplicationData(key) {
  101577. const data = this.json[key];
  101578. return data;
  101579. }
  101580. getExtraData(key) {
  101581. const extras = this.json.extras || {};
  101582. return extras[key];
  101583. }
  101584. getExtension(extensionName) {
  101585. const isExtension = this.getUsedExtensions().find(name => name === extensionName);
  101586. const extensions = this.json.extensions || {};
  101587. return isExtension ? extensions[extensionName] || true : null;
  101588. }
  101589. getRequiredExtension(extensionName) {
  101590. const isRequired = this.getRequiredExtensions().find(name => name === extensionName);
  101591. return isRequired ? this.getExtension(extensionName) : null;
  101592. }
  101593. getRequiredExtensions() {
  101594. return this.json.extensionsRequired || [];
  101595. }
  101596. getUsedExtensions() {
  101597. return this.json.extensionsUsed || [];
  101598. }
  101599. getObjectExtension(object, extensionName) {
  101600. const extensions = object.extensions || {};
  101601. return extensions[extensionName];
  101602. }
  101603. getScene(index) {
  101604. return this.getObject('scenes', index);
  101605. }
  101606. getNode(index) {
  101607. return this.getObject('nodes', index);
  101608. }
  101609. getSkin(index) {
  101610. return this.getObject('skins', index);
  101611. }
  101612. getMesh(index) {
  101613. return this.getObject('meshes', index);
  101614. }
  101615. getMaterial(index) {
  101616. return this.getObject('materials', index);
  101617. }
  101618. getAccessor(index) {
  101619. return this.getObject('accessors', index);
  101620. }
  101621. getTexture(index) {
  101622. return this.getObject('textures', index);
  101623. }
  101624. getSampler(index) {
  101625. return this.getObject('samplers', index);
  101626. }
  101627. getImage(index) {
  101628. return this.getObject('images', index);
  101629. }
  101630. getBufferView(index) {
  101631. return this.getObject('bufferViews', index);
  101632. }
  101633. getBuffer(index) {
  101634. return this.getObject('buffers', index);
  101635. }
  101636. getObject(array, index) {
  101637. if (typeof index === 'object') {
  101638. return index;
  101639. }
  101640. const object = this.json[array] && this.json[array][index];
  101641. if (!object) {
  101642. throw new Error("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  101643. }
  101644. return object;
  101645. }
  101646. getTypedArrayForBufferView(bufferView) {
  101647. bufferView = this.getBufferView(bufferView);
  101648. const bufferIndex = bufferView.buffer;
  101649. const binChunk = this.gltf.buffers[bufferIndex];
  101650. assert$1(binChunk);
  101651. const byteOffset = (bufferView.byteOffset || 0) + binChunk.byteOffset;
  101652. return new Uint8Array(binChunk.arrayBuffer, byteOffset, bufferView.byteLength);
  101653. }
  101654. getTypedArrayForAccessor(accessor) {
  101655. accessor = this.getAccessor(accessor);
  101656. const bufferView = this.getBufferView(accessor.bufferView);
  101657. const buffer = this.getBuffer(bufferView.buffer);
  101658. const arrayBuffer = buffer.data;
  101659. const {
  101660. ArrayType,
  101661. length
  101662. } = getAccessorArrayTypeAndLength(accessor, bufferView);
  101663. const byteOffset = bufferView.byteOffset + accessor.byteOffset;
  101664. return new ArrayType(arrayBuffer, byteOffset, length);
  101665. }
  101666. getTypedArrayForImageData(image) {
  101667. image = this.getAccessor(image);
  101668. const bufferView = this.getBufferView(image.bufferView);
  101669. const buffer = this.getBuffer(bufferView.buffer);
  101670. const arrayBuffer = buffer.data;
  101671. const byteOffset = bufferView.byteOffset || 0;
  101672. return new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  101673. }
  101674. addApplicationData(key, data) {
  101675. this.json[key] = data;
  101676. return this;
  101677. }
  101678. addExtraData(key, data) {
  101679. this.json.extras = this.json.extras || {};
  101680. this.json.extras[key] = data;
  101681. return this;
  101682. }
  101683. addObjectExtension(object, extensionName, data) {
  101684. object.extensions = object.extensions || {};
  101685. object.extensions[extensionName] = data;
  101686. this.registerUsedExtension(extensionName);
  101687. return this;
  101688. }
  101689. setObjectExtension(object, extensionName, data) {
  101690. const extensions = object.extensions || {};
  101691. extensions[extensionName] = data;
  101692. }
  101693. removeObjectExtension(object, extensionName) {
  101694. const extensions = object.extensions || {};
  101695. const extension = extensions[extensionName];
  101696. delete extensions[extensionName];
  101697. return extension;
  101698. }
  101699. addExtension(extensionName, extensionData = {}) {
  101700. assert$1(extensionData);
  101701. this.json.extensions = this.json.extensions || {};
  101702. this.json.extensions[extensionName] = extensionData;
  101703. this.registerUsedExtension(extensionName);
  101704. return extensionData;
  101705. }
  101706. addRequiredExtension(extensionName, extensionData = {}) {
  101707. assert$1(extensionData);
  101708. this.addExtension(extensionName, extensionData);
  101709. this.registerRequiredExtension(extensionName);
  101710. return extensionData;
  101711. }
  101712. registerUsedExtension(extensionName) {
  101713. this.json.extensionsUsed = this.json.extensionsUsed || [];
  101714. if (!this.json.extensionsUsed.find(ext => ext === extensionName)) {
  101715. this.json.extensionsUsed.push(extensionName);
  101716. }
  101717. }
  101718. registerRequiredExtension(extensionName) {
  101719. this.registerUsedExtension(extensionName);
  101720. this.json.extensionsRequired = this.json.extensionsRequired || [];
  101721. if (!this.json.extensionsRequired.find(ext => ext === extensionName)) {
  101722. this.json.extensionsRequired.push(extensionName);
  101723. }
  101724. }
  101725. removeExtension(extensionName) {
  101726. if (this.json.extensionsRequired) {
  101727. this._removeStringFromArray(this.json.extensionsRequired, extensionName);
  101728. }
  101729. if (this.json.extensionsUsed) {
  101730. this._removeStringFromArray(this.json.extensionsUsed, extensionName);
  101731. }
  101732. if (this.json.extensions) {
  101733. delete this.json.extensions[extensionName];
  101734. }
  101735. }
  101736. setDefaultScene(sceneIndex) {
  101737. this.json.scene = sceneIndex;
  101738. }
  101739. addScene(scene) {
  101740. const {
  101741. nodeIndices
  101742. } = scene;
  101743. this.json.scenes = this.json.scenes || [];
  101744. this.json.scenes.push({
  101745. nodes: nodeIndices
  101746. });
  101747. return this.json.scenes.length - 1;
  101748. }
  101749. addNode(node) {
  101750. const {
  101751. meshIndex,
  101752. matrix
  101753. } = node;
  101754. this.json.nodes = this.json.nodes || [];
  101755. const nodeData = {
  101756. mesh: meshIndex
  101757. };
  101758. if (matrix) {
  101759. nodeData.matrix = matrix;
  101760. }
  101761. this.json.nodes.push(nodeData);
  101762. return this.json.nodes.length - 1;
  101763. }
  101764. addMesh(mesh) {
  101765. const {
  101766. attributes,
  101767. indices,
  101768. material,
  101769. mode = 4
  101770. } = mesh;
  101771. const accessors = this._addAttributes(attributes);
  101772. const glTFMesh = {
  101773. primitives: [{
  101774. attributes: accessors,
  101775. mode
  101776. }]
  101777. };
  101778. if (indices) {
  101779. const indicesAccessor = this._addIndices(indices);
  101780. glTFMesh.primitives[0].indices = indicesAccessor;
  101781. }
  101782. if (Number.isFinite(material)) {
  101783. glTFMesh.primitives[0].material = material;
  101784. }
  101785. this.json.meshes = this.json.meshes || [];
  101786. this.json.meshes.push(glTFMesh);
  101787. return this.json.meshes.length - 1;
  101788. }
  101789. addPointCloud(attributes) {
  101790. const accessorIndices = this._addAttributes(attributes);
  101791. const glTFMesh = {
  101792. primitives: [{
  101793. attributes: accessorIndices,
  101794. mode: 0
  101795. }]
  101796. };
  101797. this.json.meshes = this.json.meshes || [];
  101798. this.json.meshes.push(glTFMesh);
  101799. return this.json.meshes.length - 1;
  101800. }
  101801. addImage(imageData, mimeTypeOpt) {
  101802. const metadata = getBinaryImageMetadata(imageData);
  101803. const mimeType = mimeTypeOpt || (metadata === null || metadata === void 0 ? void 0 : metadata.mimeType);
  101804. const bufferViewIndex = this.addBufferView(imageData);
  101805. const glTFImage = {
  101806. bufferView: bufferViewIndex,
  101807. mimeType
  101808. };
  101809. this.json.images = this.json.images || [];
  101810. this.json.images.push(glTFImage);
  101811. return this.json.images.length - 1;
  101812. }
  101813. addBufferView(buffer) {
  101814. const byteLength = buffer.byteLength;
  101815. assert$1(Number.isFinite(byteLength));
  101816. this.sourceBuffers = this.sourceBuffers || [];
  101817. this.sourceBuffers.push(buffer);
  101818. const glTFBufferView = {
  101819. buffer: 0,
  101820. byteOffset: this.byteLength,
  101821. byteLength
  101822. };
  101823. this.byteLength += padToNBytes(byteLength, 4);
  101824. this.json.bufferViews = this.json.bufferViews || [];
  101825. this.json.bufferViews.push(glTFBufferView);
  101826. return this.json.bufferViews.length - 1;
  101827. }
  101828. addAccessor(bufferViewIndex, accessor) {
  101829. const glTFAccessor = {
  101830. bufferView: bufferViewIndex,
  101831. type: getAccessorTypeFromSize(accessor.size),
  101832. componentType: accessor.componentType,
  101833. count: accessor.count,
  101834. max: accessor.max,
  101835. min: accessor.min
  101836. };
  101837. this.json.accessors = this.json.accessors || [];
  101838. this.json.accessors.push(glTFAccessor);
  101839. return this.json.accessors.length - 1;
  101840. }
  101841. addBinaryBuffer(sourceBuffer, accessor = {
  101842. size: 3
  101843. }) {
  101844. const bufferViewIndex = this.addBufferView(sourceBuffer);
  101845. let minMax = {
  101846. min: accessor.min,
  101847. max: accessor.max
  101848. };
  101849. if (!minMax.min || !minMax.max) {
  101850. minMax = this._getAccessorMinMax(sourceBuffer, accessor.size);
  101851. }
  101852. const accessorDefaults = {
  101853. size: accessor.size,
  101854. componentType: getComponentTypeFromArray(sourceBuffer),
  101855. count: Math.round(sourceBuffer.length / accessor.size),
  101856. min: minMax.min,
  101857. max: minMax.max
  101858. };
  101859. return this.addAccessor(bufferViewIndex, Object.assign(accessorDefaults, accessor));
  101860. }
  101861. addTexture(texture) {
  101862. const {
  101863. imageIndex
  101864. } = texture;
  101865. const glTFTexture = {
  101866. source: imageIndex
  101867. };
  101868. this.json.textures = this.json.textures || [];
  101869. this.json.textures.push(glTFTexture);
  101870. return this.json.textures.length - 1;
  101871. }
  101872. addMaterial(pbrMaterialInfo) {
  101873. this.json.materials = this.json.materials || [];
  101874. this.json.materials.push(pbrMaterialInfo);
  101875. return this.json.materials.length - 1;
  101876. }
  101877. createBinaryChunk() {
  101878. var _this$json, _this$json$buffers;
  101879. this.gltf.buffers = [];
  101880. const totalByteLength = this.byteLength;
  101881. const arrayBuffer = new ArrayBuffer(totalByteLength);
  101882. const targetArray = new Uint8Array(arrayBuffer);
  101883. let dstByteOffset = 0;
  101884. for (const sourceBuffer of this.sourceBuffers || []) {
  101885. dstByteOffset = copyToArray(sourceBuffer, targetArray, dstByteOffset);
  101886. }
  101887. 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]) {
  101888. this.json.buffers[0].byteLength = totalByteLength;
  101889. } else {
  101890. this.json.buffers = [{
  101891. byteLength: totalByteLength
  101892. }];
  101893. }
  101894. this.gltf.binary = arrayBuffer;
  101895. this.sourceBuffers = [arrayBuffer];
  101896. }
  101897. _removeStringFromArray(array, string) {
  101898. let found = true;
  101899. while (found) {
  101900. const index = array.indexOf(string);
  101901. if (index > -1) {
  101902. array.splice(index, 1);
  101903. } else {
  101904. found = false;
  101905. }
  101906. }
  101907. }
  101908. _addAttributes(attributes = {}) {
  101909. const result = {};
  101910. for (const attributeKey in attributes) {
  101911. const attributeData = attributes[attributeKey];
  101912. const attrName = this._getGltfAttributeName(attributeKey);
  101913. const accessor = this.addBinaryBuffer(attributeData.value, attributeData);
  101914. result[attrName] = accessor;
  101915. }
  101916. return result;
  101917. }
  101918. _addIndices(indices) {
  101919. return this.addBinaryBuffer(indices, {
  101920. size: 1
  101921. });
  101922. }
  101923. _getGltfAttributeName(attributeName) {
  101924. switch (attributeName.toLowerCase()) {
  101925. case 'position':
  101926. case 'positions':
  101927. case 'vertices':
  101928. return 'POSITION';
  101929. case 'normal':
  101930. case 'normals':
  101931. return 'NORMAL';
  101932. case 'color':
  101933. case 'colors':
  101934. return 'COLOR_0';
  101935. case 'texcoord':
  101936. case 'texcoords':
  101937. return 'TEXCOORD_0';
  101938. default:
  101939. return attributeName;
  101940. }
  101941. }
  101942. _getAccessorMinMax(buffer, size) {
  101943. const result = {
  101944. min: null,
  101945. max: null
  101946. };
  101947. if (buffer.length < size) {
  101948. return result;
  101949. }
  101950. result.min = [];
  101951. result.max = [];
  101952. const initValues = buffer.subarray(0, size);
  101953. for (const value of initValues) {
  101954. result.min.push(value);
  101955. result.max.push(value);
  101956. }
  101957. for (let index = size; index < buffer.length; index += size) {
  101958. for (let componentIndex = 0; componentIndex < size; componentIndex++) {
  101959. result.min[0 + componentIndex] = Math.min(result.min[0 + componentIndex], buffer[index + componentIndex]);
  101960. result.max[0 + componentIndex] = Math.max(result.max[0 + componentIndex], buffer[index + componentIndex]);
  101961. }
  101962. }
  101963. return result;
  101964. }
  101965. }
  101966. const isWebAssemblySupported = typeof WebAssembly !== 'object';
  101967. const wasm_base = 'B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB';
  101968. const wasm_simd = 'B9h9z9tFBBBF8dL9gBB9gLaaaaaFa9gEaaaB9gGaaB9gFaFaEQSBBFBFFGEGEGIILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBNn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBcI9z9iqlBMc/j9JSIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMkRIbaG97FaK978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAnDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAnDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBRnCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBHiCFD9tAiAPD9OD9hD9RHiDQBTFtGmEYIPLdKeOnH8ZAIAQJDBIBHpCFD9tApAPD9OD9hD9RHpAIASJDBIBHyCFD9tAyAPD9OD9hD9RHyDQBTFtGmEYIPLdKeOnH8cDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAnD9uHnDyBjGBAEAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnA8ZA8cDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNiV8ZcpMyS8cQ8df8eb8fHdApAyDQNiV8ZcpMyS8cQ8df8eb8fHiDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/xLGEaK978jUUUUBCAlHE8kUUUUBGXGXAGCI9HQBGXAFC98ZHI9FQBABRGCBRLEXAGAGDBBBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMBBAGCTJRGALCIJHLAI9JQBMMAIAF9PQFAEAFCEZHLCGWHGqCBCTAGl/8MBAEABAICGWJHIAG/8cBBGXAL9FQBAEAEDBIBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMIBMAIAEAG/8cBBSFMABAFC98ZHGT+HUUUBAGAF9PQBAEAFCEZHICEWHLJCBCAALl/8MBAEABAGCEWJHGAL/8cBBAEAIT+HUUUBAGAEAL/8cBBMAECAJ8kUUUUBM+yEGGaO97GXAF9FQBCBRGEXABCTJHEAEDBBBHICBDtHLCUU98D8cFCUU98D8cEHKD9OABDBBBHOAIDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAOAIDQBFGENVcMTtmYi8ZpyHICTD+sFD/6FHND/gFAICTD+rFCTD+sFD/6FHVD/gFD/kFD/lFHI9DB/+g6DYAVAIALD+2FHLAVCUUUU94DtHcD9OD9RD/kFHVAVD/mFAIAID/mFANALANAcD9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHLD/kFCTD+rFAVAND/mFALD/kFCggEDtD9OD9QHVAIAND/mFALD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHIDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAOAKD9OAVAIDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM94FEa8jUUUUBCAlHE8kUUUUBABAFC98ZHIT+JUUUBGXAIAF9PQBAEAFCEZHLCEWHFJCBCAAFl/8MBAEABAICEWJHBAF/8cBBAEALT+JUUUBABAEAF/8cBBMAECAJ8kUUUUBM/hEIGaF97FaL978jUUUUBCTlRGGXAF9FQBCBREEXAGABDBBBHIABCTJHLDBBBHKDQILKOSQfbPden8c8d8e8fHOCTD+sFHNCID+rFDMIBAB9DBBU8/DY9D/zI818/DYANCEDtD9QD/6FD/nFHNAIAKDQBFGENVcMTtmYi8ZpyHICTD+rFCTD+sFD/6FD/mFHKAKD/mFANAICTD+sFD/6FD/mFHVAVD/mFANAOCTD+rFCTD+sFD/6FD/mFHOAOD/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHND/mF9DBBX9LDYHID/kFCggEDtHcD9OAVAND/mFAID/kFCTD+rFD9QHVAOAND/mFAID/kFCTD+rFAKAND/mFAID/kFAcD9OD9QHNDQBFTtGEmYILPdKOenHID8dBAGDBIBDyB+t+J83EBABCNJAID8dFAGDBIBDyF+t+J83EBALAVANDQNVi8ZcMpySQ8c8dfb8e8fHND8dBAGDBIBDyG+t+J83EBABCiJAND8dFAGDBIBDyE+t+J83EBABCAJRBAECIJHEAF9JQBMMM/3FGEaF978jUUUUBCoBlREGXAGCGrAF9sHIC98ZHL9FQBCBRGABRFEXAFAFDBBBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBAFCTJRFAGCIJHGAL9JQBMMGXALAI9PQBAEAICEZHGCGWHFqCBCoBAFl/8MBAEABALCGWJHLAF/8cBBGXAG9FQBAEAEDBIBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMIBMALAEAF/8cBBMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB';
  101969. const detector = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11]);
  101970. const wasmpack = new Uint8Array([32, 0, 65, 253, 3, 1, 2, 34, 4, 106, 6, 5, 11, 8, 7, 20, 13, 33, 12, 16, 128, 9, 116, 64, 19, 113, 127, 15, 10, 21, 22, 14, 255, 66, 24, 54, 136, 107, 18, 23, 192, 26, 114, 118, 132, 17, 77, 101, 130, 144, 27, 87, 131, 44, 45, 74, 156, 154, 70, 167]);
  101971. const FILTERS = {
  101972. 0: '',
  101973. 1: 'meshopt_decodeFilterOct',
  101974. 2: 'meshopt_decodeFilterQuat',
  101975. 3: 'meshopt_decodeFilterExp',
  101976. NONE: '',
  101977. OCTAHEDRAL: 'meshopt_decodeFilterOct',
  101978. QUATERNION: 'meshopt_decodeFilterQuat',
  101979. EXPONENTIAL: 'meshopt_decodeFilterExp'
  101980. };
  101981. const DECODERS = {
  101982. 0: 'meshopt_decodeVertexBuffer',
  101983. 1: 'meshopt_decodeIndexBuffer',
  101984. 2: 'meshopt_decodeIndexSequence',
  101985. ATTRIBUTES: 'meshopt_decodeVertexBuffer',
  101986. TRIANGLES: 'meshopt_decodeIndexBuffer',
  101987. INDICES: 'meshopt_decodeIndexSequence'
  101988. };
  101989. function isMeshoptSupported() {
  101990. return isWebAssemblySupported;
  101991. }
  101992. async function meshoptDecodeGltfBuffer(target, count, size, source, mode, filter = 'NONE') {
  101993. const instance = await loadWasmInstance();
  101994. decode$5(instance, instance.exports[DECODERS[mode]], target, count, size, source, instance.exports[FILTERS[filter || 'NONE']]);
  101995. }
  101996. let wasmPromise;
  101997. async function loadWasmInstance() {
  101998. if (!wasmPromise) {
  101999. wasmPromise = loadWasmModule();
  102000. }
  102001. return wasmPromise;
  102002. }
  102003. async function loadWasmModule() {
  102004. let wasm = wasm_base;
  102005. if (WebAssembly.validate(detector)) {
  102006. wasm = wasm_simd;
  102007. console.log('Warning: meshopt_decoder is using experimental SIMD support');
  102008. }
  102009. const result = await WebAssembly.instantiate(unpack(wasm), {});
  102010. await result.instance.exports.__wasm_call_ctors();
  102011. return result.instance;
  102012. }
  102013. function unpack(data) {
  102014. const result = new Uint8Array(data.length);
  102015. for (let i = 0; i < data.length; ++i) {
  102016. const ch = data.charCodeAt(i);
  102017. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  102018. }
  102019. let write = 0;
  102020. for (let i = 0; i < data.length; ++i) {
  102021. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  102022. }
  102023. return result.buffer.slice(0, write);
  102024. }
  102025. function decode$5(instance, fun, target, count, size, source, filter) {
  102026. const sbrk = instance.exports.sbrk;
  102027. const count4 = count + 3 & ~3;
  102028. const tp = sbrk(count4 * size);
  102029. const sp = sbrk(source.length);
  102030. const heap = new Uint8Array(instance.exports.memory.buffer);
  102031. heap.set(source, sp);
  102032. const res = fun(tp, count, size, sp, source.length);
  102033. if (res === 0 && filter) {
  102034. filter(tp, count4, size);
  102035. }
  102036. target.set(heap.subarray(tp, tp + count * size));
  102037. sbrk(tp - sbrk(0));
  102038. if (res !== 0) {
  102039. throw new Error("Malformed buffer data: ".concat(res));
  102040. }
  102041. }
  102042. const EXT_MESHOPT_COMPRESSION = 'EXT_meshopt_compression';
  102043. const name$6 = EXT_MESHOPT_COMPRESSION;
  102044. function preprocess$4(gltfData) {
  102045. const scenegraph = new GLTFScenegraph(gltfData);
  102046. if (scenegraph.getRequiredExtensions().includes(EXT_MESHOPT_COMPRESSION) && !isMeshoptSupported()) {
  102047. throw new Error("gltf: Required extension ".concat(EXT_MESHOPT_COMPRESSION, " not supported by browser"));
  102048. }
  102049. }
  102050. async function decode$4(gltfData, options) {
  102051. var _options$gltf;
  102052. const scenegraph = new GLTFScenegraph(gltfData);
  102053. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  102054. return;
  102055. }
  102056. const promises = [];
  102057. for (const bufferViewIndex of gltfData.json.bufferViews || []) {
  102058. promises.push(decodeMeshoptBufferView(scenegraph, bufferViewIndex));
  102059. }
  102060. await Promise.all(promises);
  102061. scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);
  102062. }
  102063. async function decodeMeshoptBufferView(scenegraph, bufferView) {
  102064. const meshoptExtension = scenegraph.getObjectExtension(bufferView, EXT_MESHOPT_COMPRESSION);
  102065. if (meshoptExtension) {
  102066. const buffer = bufferView.buffer;
  102067. const {
  102068. byteOffset = 0,
  102069. byteLength = 0,
  102070. byteStride,
  102071. count,
  102072. mode,
  102073. filter = 'NONE'
  102074. } = meshoptExtension;
  102075. const source = new Uint8Array(buffer, byteOffset, byteLength);
  102076. const result = new ArrayBuffer(count * byteStride);
  102077. await meshoptDecodeGltfBuffer(new Uint8Array(result), count, byteStride, source, mode, filter);
  102078. return result;
  102079. }
  102080. return null;
  102081. }
  102082. var EXT_meshopt_compression = /*#__PURE__*/Object.freeze({
  102083. __proto__: null,
  102084. name: name$6,
  102085. preprocess: preprocess$4,
  102086. decode: decode$4
  102087. });
  102088. const EXT_TEXTURE_WEBP = 'EXT_texture_webp';
  102089. const name$5 = EXT_TEXTURE_WEBP;
  102090. function preprocess$3(gltfData, options) {
  102091. const scenegraph = new GLTFScenegraph(gltfData);
  102092. if (!_isImageFormatSupported('image/webp')) {
  102093. if (scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)) {
  102094. throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP, " not supported by browser"));
  102095. }
  102096. return;
  102097. }
  102098. const {
  102099. json
  102100. } = scenegraph;
  102101. for (const texture of json.textures || []) {
  102102. const extension = scenegraph.getObjectExtension(texture, EXT_TEXTURE_WEBP);
  102103. if (extension) {
  102104. texture.source = extension.source;
  102105. }
  102106. scenegraph.removeObjectExtension(texture, EXT_TEXTURE_WEBP);
  102107. }
  102108. scenegraph.removeExtension(EXT_TEXTURE_WEBP);
  102109. }
  102110. var EXT_texture_webp = /*#__PURE__*/Object.freeze({
  102111. __proto__: null,
  102112. name: name$5,
  102113. preprocess: preprocess$3
  102114. });
  102115. const KHR_TEXTURE_BASISU = 'KHR_texture_basisu';
  102116. const name$4 = KHR_TEXTURE_BASISU;
  102117. function preprocess$2(gltfData, options) {
  102118. const scene = new GLTFScenegraph(gltfData);
  102119. const {
  102120. json
  102121. } = scene;
  102122. for (const texture of json.textures || []) {
  102123. const extension = scene.getObjectExtension(texture, KHR_TEXTURE_BASISU);
  102124. if (extension) {
  102125. texture.source = extension.source;
  102126. }
  102127. scene.removeObjectExtension(texture, KHR_TEXTURE_BASISU);
  102128. }
  102129. scene.removeExtension(KHR_TEXTURE_BASISU);
  102130. }
  102131. var KHR_texture_basisu = /*#__PURE__*/Object.freeze({
  102132. __proto__: null,
  102133. name: name$4,
  102134. preprocess: preprocess$2
  102135. });
  102136. function getGLTFAccessors(attributes) {
  102137. const accessors = {};
  102138. for (const name in attributes) {
  102139. const attribute = attributes[name];
  102140. if (name !== 'indices') {
  102141. const glTFAccessor = getGLTFAccessor(attribute);
  102142. accessors[name] = glTFAccessor;
  102143. }
  102144. }
  102145. return accessors;
  102146. }
  102147. function getGLTFAccessor(attribute) {
  102148. const {
  102149. buffer,
  102150. size,
  102151. count
  102152. } = getAccessorData(attribute);
  102153. const glTFAccessor = {
  102154. value: buffer,
  102155. size,
  102156. byteOffset: 0,
  102157. count,
  102158. type: getAccessorTypeFromSize(size),
  102159. componentType: getComponentTypeFromArray(buffer)
  102160. };
  102161. return glTFAccessor;
  102162. }
  102163. function getAccessorData(attribute) {
  102164. let buffer = attribute;
  102165. let size = 1;
  102166. let count = 0;
  102167. if (attribute && attribute.value) {
  102168. buffer = attribute.value;
  102169. size = attribute.size || 1;
  102170. }
  102171. if (buffer) {
  102172. if (!ArrayBuffer.isView(buffer)) {
  102173. buffer = toTypedArray(buffer, Float32Array);
  102174. }
  102175. count = buffer.length / size;
  102176. }
  102177. return {
  102178. buffer,
  102179. size,
  102180. count
  102181. };
  102182. }
  102183. function toTypedArray(array, ArrayType, convertTypedArrays = false) {
  102184. if (!array) {
  102185. return null;
  102186. }
  102187. if (Array.isArray(array)) {
  102188. return new ArrayType(array);
  102189. }
  102190. if (convertTypedArrays && !(array instanceof ArrayType)) {
  102191. return new ArrayType(array);
  102192. }
  102193. return array;
  102194. }
  102195. const KHR_DRACO_MESH_COMPRESSION = 'KHR_draco_mesh_compression';
  102196. const name$3 = KHR_DRACO_MESH_COMPRESSION;
  102197. function preprocess$1(gltfData, options, context) {
  102198. const scenegraph = new GLTFScenegraph(gltfData);
  102199. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  102200. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) ;
  102201. }
  102202. }
  102203. async function decode$3(gltfData, options, context) {
  102204. var _options$gltf;
  102205. if (!(options !== null && options !== void 0 && (_options$gltf = options.gltf) !== null && _options$gltf !== void 0 && _options$gltf.decompressMeshes)) {
  102206. return;
  102207. }
  102208. const scenegraph = new GLTFScenegraph(gltfData);
  102209. const promises = [];
  102210. for (const primitive of makeMeshPrimitiveIterator(scenegraph)) {
  102211. if (scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION)) {
  102212. promises.push(decompressPrimitive(scenegraph, primitive, options, context));
  102213. }
  102214. }
  102215. await Promise.all(promises);
  102216. scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);
  102217. }
  102218. function encode$3(gltfData, options = {}) {
  102219. const scenegraph = new GLTFScenegraph(gltfData);
  102220. for (const mesh of scenegraph.json.meshes || []) {
  102221. compressMesh(mesh);
  102222. scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);
  102223. }
  102224. }
  102225. async function decompressPrimitive(scenegraph, primitive, options, context) {
  102226. const dracoExtension = scenegraph.getObjectExtension(primitive, KHR_DRACO_MESH_COMPRESSION);
  102227. if (!dracoExtension) {
  102228. return;
  102229. }
  102230. const buffer = scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);
  102231. const bufferCopy = sliceArrayBuffer(buffer.buffer, buffer.byteOffset);
  102232. const {
  102233. parse
  102234. } = context;
  102235. const dracoOptions = { ...options
  102236. };
  102237. delete dracoOptions['3d-tiles'];
  102238. const decodedData = await parse(bufferCopy, DracoLoader, dracoOptions, context);
  102239. const decodedAttributes = getGLTFAccessors(decodedData.attributes);
  102240. for (const [attributeName, decodedAttribute] of Object.entries(decodedAttributes)) {
  102241. if (attributeName in primitive.attributes) {
  102242. const accessorIndex = primitive.attributes[attributeName];
  102243. const accessor = scenegraph.getAccessor(accessorIndex);
  102244. if (accessor !== null && accessor !== void 0 && accessor.min && accessor !== null && accessor !== void 0 && accessor.max) {
  102245. decodedAttribute.min = accessor.min;
  102246. decodedAttribute.max = accessor.max;
  102247. }
  102248. }
  102249. }
  102250. primitive.attributes = decodedAttributes;
  102251. if (decodedData.indices) {
  102252. primitive.indices = getGLTFAccessor(decodedData.indices);
  102253. }
  102254. checkPrimitive(primitive);
  102255. }
  102256. function compressMesh(attributes, indices, mode = 4, options, context) {
  102257. var _context$parseSync;
  102258. if (!options.DracoWriter) {
  102259. throw new Error('options.gltf.DracoWriter not provided');
  102260. }
  102261. const compressedData = options.DracoWriter.encodeSync({
  102262. attributes
  102263. });
  102264. const decodedData = context === null || context === void 0 ? void 0 : (_context$parseSync = context.parseSync) === null || _context$parseSync === void 0 ? void 0 : _context$parseSync.call(context, {
  102265. attributes
  102266. });
  102267. const fauxAccessors = options._addFauxAttributes(decodedData.attributes);
  102268. const bufferViewIndex = options.addBufferView(compressedData);
  102269. const glTFMesh = {
  102270. primitives: [{
  102271. attributes: fauxAccessors,
  102272. mode,
  102273. extensions: {
  102274. [KHR_DRACO_MESH_COMPRESSION]: {
  102275. bufferView: bufferViewIndex,
  102276. attributes: fauxAccessors
  102277. }
  102278. }
  102279. }]
  102280. };
  102281. return glTFMesh;
  102282. }
  102283. function checkPrimitive(primitive) {
  102284. if (!primitive.attributes && Object.keys(primitive.attributes).length > 0) {
  102285. throw new Error('glTF: Empty primitive detected: Draco decompression failure?');
  102286. }
  102287. }
  102288. function* makeMeshPrimitiveIterator(scenegraph) {
  102289. for (const mesh of scenegraph.json.meshes || []) {
  102290. for (const primitive of mesh.primitives) {
  102291. yield primitive;
  102292. }
  102293. }
  102294. }
  102295. var KHR_draco_mesh_compression = /*#__PURE__*/Object.freeze({
  102296. __proto__: null,
  102297. name: name$3,
  102298. preprocess: preprocess$1,
  102299. decode: decode$3,
  102300. encode: encode$3
  102301. });
  102302. const KHR_LIGHTS_PUNCTUAL = 'KHR_lights_punctual';
  102303. const name$2 = KHR_LIGHTS_PUNCTUAL;
  102304. async function decode$2(gltfData) {
  102305. const gltfScenegraph = new GLTFScenegraph(gltfData);
  102306. const {
  102307. json
  102308. } = gltfScenegraph;
  102309. const extension = gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);
  102310. if (extension) {
  102311. gltfScenegraph.json.lights = extension.lights;
  102312. gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);
  102313. }
  102314. for (const node of json.nodes || []) {
  102315. const nodeExtension = gltfScenegraph.getObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  102316. if (nodeExtension) {
  102317. node.light = nodeExtension.light;
  102318. }
  102319. gltfScenegraph.removeObjectExtension(node, KHR_LIGHTS_PUNCTUAL);
  102320. }
  102321. }
  102322. async function encode$2(gltfData) {
  102323. const gltfScenegraph = new GLTFScenegraph(gltfData);
  102324. const {
  102325. json
  102326. } = gltfScenegraph;
  102327. if (json.lights) {
  102328. const extension = gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);
  102329. assert$1(!extension.lights);
  102330. extension.lights = json.lights;
  102331. delete json.lights;
  102332. }
  102333. if (gltfScenegraph.json.lights) {
  102334. for (const light of gltfScenegraph.json.lights) {
  102335. const node = light.node;
  102336. gltfScenegraph.addObjectExtension(node, KHR_LIGHTS_PUNCTUAL, light);
  102337. }
  102338. delete gltfScenegraph.json.lights;
  102339. }
  102340. }
  102341. var KHR_lights_punctual = /*#__PURE__*/Object.freeze({
  102342. __proto__: null,
  102343. name: name$2,
  102344. decode: decode$2,
  102345. encode: encode$2
  102346. });
  102347. const KHR_MATERIALS_UNLIT = 'KHR_materials_unlit';
  102348. const name$1 = KHR_MATERIALS_UNLIT;
  102349. async function decode$1(gltfData) {
  102350. const gltfScenegraph = new GLTFScenegraph(gltfData);
  102351. const {
  102352. json
  102353. } = gltfScenegraph;
  102354. gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);
  102355. for (const material of json.materials || []) {
  102356. const extension = material.extensions && material.extensions.KHR_materials_unlit;
  102357. if (extension) {
  102358. material.unlit = true;
  102359. }
  102360. gltfScenegraph.removeObjectExtension(material, KHR_MATERIALS_UNLIT);
  102361. }
  102362. }
  102363. function encode$1(gltfData) {
  102364. const gltfScenegraph = new GLTFScenegraph(gltfData);
  102365. const {
  102366. json
  102367. } = gltfScenegraph;
  102368. if (gltfScenegraph.materials) {
  102369. for (const material of json.materials || []) {
  102370. if (material.unlit) {
  102371. delete material.unlit;
  102372. gltfScenegraph.addObjectExtension(material, KHR_MATERIALS_UNLIT, {});
  102373. gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);
  102374. }
  102375. }
  102376. }
  102377. }
  102378. var KHR_materials_unlit = /*#__PURE__*/Object.freeze({
  102379. __proto__: null,
  102380. name: name$1,
  102381. decode: decode$1,
  102382. encode: encode$1
  102383. });
  102384. const KHR_TECHNIQUES_WEBGL = 'KHR_techniques_webgl';
  102385. const name = KHR_TECHNIQUES_WEBGL;
  102386. async function decode(gltfData) {
  102387. const gltfScenegraph = new GLTFScenegraph(gltfData);
  102388. const {
  102389. json
  102390. } = gltfScenegraph;
  102391. const extension = gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);
  102392. if (extension) {
  102393. const techniques = resolveTechniques(extension, gltfScenegraph);
  102394. for (const material of json.materials || []) {
  102395. const materialExtension = gltfScenegraph.getObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  102396. if (materialExtension) {
  102397. material.technique = Object.assign({}, materialExtension, techniques[materialExtension.technique]);
  102398. material.technique.values = resolveValues(material.technique, gltfScenegraph);
  102399. }
  102400. gltfScenegraph.removeObjectExtension(material, KHR_TECHNIQUES_WEBGL);
  102401. }
  102402. gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);
  102403. }
  102404. }
  102405. async function encode(gltfData, options) {}
  102406. function resolveTechniques(techniquesExtension, gltfScenegraph) {
  102407. const {
  102408. programs = [],
  102409. shaders = [],
  102410. techniques = []
  102411. } = techniquesExtension;
  102412. const textDecoder = new TextDecoder();
  102413. shaders.forEach(shader => {
  102414. if (Number.isFinite(shader.bufferView)) {
  102415. shader.code = textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));
  102416. } else {
  102417. throw new Error('KHR_techniques_webgl: no shader code');
  102418. }
  102419. });
  102420. programs.forEach(program => {
  102421. program.fragmentShader = shaders[program.fragmentShader];
  102422. program.vertexShader = shaders[program.vertexShader];
  102423. });
  102424. techniques.forEach(technique => {
  102425. technique.program = programs[technique.program];
  102426. });
  102427. return techniques;
  102428. }
  102429. function resolveValues(technique, gltfScenegraph) {
  102430. const values = Object.assign({}, technique.values);
  102431. Object.keys(technique.uniforms || {}).forEach(uniform => {
  102432. if (technique.uniforms[uniform].value && !(uniform in values)) {
  102433. values[uniform] = technique.uniforms[uniform].value;
  102434. }
  102435. });
  102436. Object.keys(values).forEach(uniform => {
  102437. if (typeof values[uniform] === 'object' && values[uniform].index !== undefined) {
  102438. values[uniform].texture = gltfScenegraph.getTexture(values[uniform].index);
  102439. }
  102440. });
  102441. return values;
  102442. }
  102443. var KHR_techniques_webgl = /*#__PURE__*/Object.freeze({
  102444. __proto__: null,
  102445. name: name,
  102446. decode: decode,
  102447. encode: encode
  102448. });
  102449. const EXTENSIONS$2 = [EXT_meshopt_compression, EXT_texture_webp, KHR_texture_basisu, KHR_draco_mesh_compression, KHR_lights_punctual, KHR_materials_unlit, KHR_techniques_webgl];
  102450. function preprocessExtensions(gltf, options = {}, context) {
  102451. const extensions = EXTENSIONS$2.filter(extension => useExtension(extension.name, options));
  102452. for (const extension of extensions) {
  102453. var _extension$preprocess;
  102454. (_extension$preprocess = extension.preprocess) === null || _extension$preprocess === void 0 ? void 0 : _extension$preprocess.call(extension, gltf, options, context);
  102455. }
  102456. }
  102457. async function decodeExtensions(gltf, options = {}, context) {
  102458. const extensions = EXTENSIONS$2.filter(extension => useExtension(extension.name, options));
  102459. for (const extension of extensions) {
  102460. var _extension$decode;
  102461. await ((_extension$decode = extension.decode) === null || _extension$decode === void 0 ? void 0 : _extension$decode.call(extension, gltf, options, context));
  102462. }
  102463. }
  102464. function useExtension(extensionName, options) {
  102465. var _options$gltf;
  102466. const excludes = (options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.excludeExtensions) || {};
  102467. const exclude = extensionName in excludes && !excludes[extensionName];
  102468. return !exclude;
  102469. }
  102470. const KHR_BINARY_GLTF = 'KHR_binary_glTF';
  102471. function preprocess(gltfData) {
  102472. const gltfScenegraph = new GLTFScenegraph(gltfData);
  102473. const {
  102474. json
  102475. } = gltfScenegraph;
  102476. for (const image of json.images || []) {
  102477. const extension = gltfScenegraph.getObjectExtension(image, KHR_BINARY_GLTF);
  102478. if (extension) {
  102479. Object.assign(image, extension);
  102480. }
  102481. gltfScenegraph.removeObjectExtension(image, KHR_BINARY_GLTF);
  102482. }
  102483. if (json.buffers && json.buffers[0]) {
  102484. delete json.buffers[0].uri;
  102485. }
  102486. gltfScenegraph.removeExtension(KHR_BINARY_GLTF);
  102487. }
  102488. const GLTF_ARRAYS = {
  102489. accessors: 'accessor',
  102490. animations: 'animation',
  102491. buffers: 'buffer',
  102492. bufferViews: 'bufferView',
  102493. images: 'image',
  102494. materials: 'material',
  102495. meshes: 'mesh',
  102496. nodes: 'node',
  102497. samplers: 'sampler',
  102498. scenes: 'scene',
  102499. skins: 'skin',
  102500. textures: 'texture'
  102501. };
  102502. const GLTF_KEYS = {
  102503. accessor: 'accessors',
  102504. animations: 'animation',
  102505. buffer: 'buffers',
  102506. bufferView: 'bufferViews',
  102507. image: 'images',
  102508. material: 'materials',
  102509. mesh: 'meshes',
  102510. node: 'nodes',
  102511. sampler: 'samplers',
  102512. scene: 'scenes',
  102513. skin: 'skins',
  102514. texture: 'textures'
  102515. };
  102516. class GLTFV1Normalizer {
  102517. constructor() {
  102518. _defineProperty(this, "idToIndexMap", {
  102519. animations: {},
  102520. accessors: {},
  102521. buffers: {},
  102522. bufferViews: {},
  102523. images: {},
  102524. materials: {},
  102525. meshes: {},
  102526. nodes: {},
  102527. samplers: {},
  102528. scenes: {},
  102529. skins: {},
  102530. textures: {}
  102531. });
  102532. _defineProperty(this, "json", void 0);
  102533. }
  102534. normalize(gltf, options) {
  102535. this.json = gltf.json;
  102536. const json = gltf.json;
  102537. switch (json.asset && json.asset.version) {
  102538. case '2.0':
  102539. return;
  102540. case undefined:
  102541. case '1.0':
  102542. break;
  102543. default:
  102544. console.warn("glTF: Unknown version ".concat(json.asset.version));
  102545. return;
  102546. }
  102547. if (!options.normalize) {
  102548. throw new Error('glTF v1 is not supported.');
  102549. }
  102550. console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');
  102551. this._addAsset(json);
  102552. this._convertTopLevelObjectsToArrays(json);
  102553. preprocess(gltf);
  102554. this._convertObjectIdsToArrayIndices(json);
  102555. this._updateObjects(json);
  102556. this._updateMaterial(json);
  102557. }
  102558. _addAsset(json) {
  102559. json.asset = json.asset || {};
  102560. json.asset.version = '2.0';
  102561. json.asset.generator = json.asset.generator || 'Normalized to glTF 2.0 by loaders.gl';
  102562. }
  102563. _convertTopLevelObjectsToArrays(json) {
  102564. for (const arrayName in GLTF_ARRAYS) {
  102565. this._convertTopLevelObjectToArray(json, arrayName);
  102566. }
  102567. }
  102568. _convertTopLevelObjectToArray(json, mapName) {
  102569. const objectMap = json[mapName];
  102570. if (!objectMap || Array.isArray(objectMap)) {
  102571. return;
  102572. }
  102573. json[mapName] = [];
  102574. for (const id in objectMap) {
  102575. const object = objectMap[id];
  102576. object.id = object.id || id;
  102577. const index = json[mapName].length;
  102578. json[mapName].push(object);
  102579. this.idToIndexMap[mapName][id] = index;
  102580. }
  102581. }
  102582. _convertObjectIdsToArrayIndices(json) {
  102583. for (const arrayName in GLTF_ARRAYS) {
  102584. this._convertIdsToIndices(json, arrayName);
  102585. }
  102586. if ('scene' in json) {
  102587. json.scene = this._convertIdToIndex(json.scene, 'scene');
  102588. }
  102589. for (const texture of json.textures) {
  102590. this._convertTextureIds(texture);
  102591. }
  102592. for (const mesh of json.meshes) {
  102593. this._convertMeshIds(mesh);
  102594. }
  102595. for (const node of json.nodes) {
  102596. this._convertNodeIds(node);
  102597. }
  102598. for (const node of json.scenes) {
  102599. this._convertSceneIds(node);
  102600. }
  102601. }
  102602. _convertTextureIds(texture) {
  102603. if (texture.source) {
  102604. texture.source = this._convertIdToIndex(texture.source, 'image');
  102605. }
  102606. }
  102607. _convertMeshIds(mesh) {
  102608. for (const primitive of mesh.primitives) {
  102609. const {
  102610. attributes,
  102611. indices,
  102612. material
  102613. } = primitive;
  102614. for (const attributeName in attributes) {
  102615. attributes[attributeName] = this._convertIdToIndex(attributes[attributeName], 'accessor');
  102616. }
  102617. if (indices) {
  102618. primitive.indices = this._convertIdToIndex(indices, 'accessor');
  102619. }
  102620. if (material) {
  102621. primitive.material = this._convertIdToIndex(material, 'material');
  102622. }
  102623. }
  102624. }
  102625. _convertNodeIds(node) {
  102626. if (node.children) {
  102627. node.children = node.children.map(child => this._convertIdToIndex(child, 'node'));
  102628. }
  102629. if (node.meshes) {
  102630. node.meshes = node.meshes.map(mesh => this._convertIdToIndex(mesh, 'mesh'));
  102631. }
  102632. }
  102633. _convertSceneIds(scene) {
  102634. if (scene.nodes) {
  102635. scene.nodes = scene.nodes.map(node => this._convertIdToIndex(node, 'node'));
  102636. }
  102637. }
  102638. _convertIdsToIndices(json, topLevelArrayName) {
  102639. if (!json[topLevelArrayName]) {
  102640. console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));
  102641. json[topLevelArrayName] = [];
  102642. }
  102643. for (const object of json[topLevelArrayName]) {
  102644. for (const key in object) {
  102645. const id = object[key];
  102646. const index = this._convertIdToIndex(id, key);
  102647. object[key] = index;
  102648. }
  102649. }
  102650. }
  102651. _convertIdToIndex(id, key) {
  102652. const arrayName = GLTF_KEYS[key];
  102653. if (arrayName in this.idToIndexMap) {
  102654. const index = this.idToIndexMap[arrayName][id];
  102655. if (!Number.isFinite(index)) {
  102656. throw new Error("gltf v1: failed to resolve ".concat(key, " with id ").concat(id));
  102657. }
  102658. return index;
  102659. }
  102660. return id;
  102661. }
  102662. _updateObjects(json) {
  102663. for (const buffer of this.json.buffers) {
  102664. delete buffer.type;
  102665. }
  102666. }
  102667. _updateMaterial(json) {
  102668. for (const material of json.materials) {
  102669. material.pbrMetallicRoughness = {
  102670. baseColorFactor: [1, 1, 1, 1],
  102671. metallicFactor: 1,
  102672. roughnessFactor: 1
  102673. };
  102674. const textureId = material.values && material.values.tex;
  102675. const textureIndex = json.textures.findIndex(texture => texture.id === textureId);
  102676. if (textureIndex !== -1) {
  102677. material.pbrMetallicRoughness.baseColorTexture = {
  102678. index: textureIndex
  102679. };
  102680. }
  102681. }
  102682. }
  102683. }
  102684. function normalizeGLTFV1(gltf, options = {}) {
  102685. return new GLTFV1Normalizer().normalize(gltf, options);
  102686. }
  102687. const COMPONENTS = {
  102688. SCALAR: 1,
  102689. VEC2: 2,
  102690. VEC3: 3,
  102691. VEC4: 4,
  102692. MAT2: 4,
  102693. MAT3: 9,
  102694. MAT4: 16
  102695. };
  102696. const BYTES = {
  102697. 5120: 1,
  102698. 5121: 1,
  102699. 5122: 2,
  102700. 5123: 2,
  102701. 5125: 4,
  102702. 5126: 4
  102703. };
  102704. const GL_SAMPLER = {
  102705. TEXTURE_MAG_FILTER: 0x2800,
  102706. TEXTURE_MIN_FILTER: 0x2801,
  102707. TEXTURE_WRAP_S: 0x2802,
  102708. TEXTURE_WRAP_T: 0x2803,
  102709. REPEAT: 0x2901,
  102710. LINEAR: 0x2601,
  102711. NEAREST_MIPMAP_LINEAR: 0x2702
  102712. };
  102713. const SAMPLER_PARAMETER_GLTF_TO_GL = {
  102714. magFilter: GL_SAMPLER.TEXTURE_MAG_FILTER,
  102715. minFilter: GL_SAMPLER.TEXTURE_MIN_FILTER,
  102716. wrapS: GL_SAMPLER.TEXTURE_WRAP_S,
  102717. wrapT: GL_SAMPLER.TEXTURE_WRAP_T
  102718. };
  102719. const DEFAULT_SAMPLER = {
  102720. [GL_SAMPLER.TEXTURE_MAG_FILTER]: GL_SAMPLER.LINEAR,
  102721. [GL_SAMPLER.TEXTURE_MIN_FILTER]: GL_SAMPLER.NEAREST_MIPMAP_LINEAR,
  102722. [GL_SAMPLER.TEXTURE_WRAP_S]: GL_SAMPLER.REPEAT,
  102723. [GL_SAMPLER.TEXTURE_WRAP_T]: GL_SAMPLER.REPEAT
  102724. };
  102725. function getBytesFromComponentType(componentType) {
  102726. return BYTES[componentType];
  102727. }
  102728. function getSizeFromAccessorType(type) {
  102729. return COMPONENTS[type];
  102730. }
  102731. class GLTFPostProcessor {
  102732. constructor() {
  102733. _defineProperty(this, "baseUri", '');
  102734. _defineProperty(this, "json", {});
  102735. _defineProperty(this, "buffers", []);
  102736. _defineProperty(this, "images", []);
  102737. }
  102738. postProcess(gltf, options = {}) {
  102739. const {
  102740. json,
  102741. buffers = [],
  102742. images = [],
  102743. baseUri = ''
  102744. } = gltf;
  102745. assert$1(json);
  102746. this.baseUri = baseUri;
  102747. this.json = json;
  102748. this.buffers = buffers;
  102749. this.images = images;
  102750. this._resolveTree(this.json, options);
  102751. return this.json;
  102752. }
  102753. _resolveTree(json, options = {}) {
  102754. if (json.bufferViews) {
  102755. json.bufferViews = json.bufferViews.map((bufView, i) => this._resolveBufferView(bufView, i));
  102756. }
  102757. if (json.images) {
  102758. json.images = json.images.map((image, i) => this._resolveImage(image, i));
  102759. }
  102760. if (json.samplers) {
  102761. json.samplers = json.samplers.map((sampler, i) => this._resolveSampler(sampler, i));
  102762. }
  102763. if (json.textures) {
  102764. json.textures = json.textures.map((texture, i) => this._resolveTexture(texture, i));
  102765. }
  102766. if (json.accessors) {
  102767. json.accessors = json.accessors.map((accessor, i) => this._resolveAccessor(accessor, i));
  102768. }
  102769. if (json.materials) {
  102770. json.materials = json.materials.map((material, i) => this._resolveMaterial(material, i));
  102771. }
  102772. if (json.meshes) {
  102773. json.meshes = json.meshes.map((mesh, i) => this._resolveMesh(mesh, i));
  102774. }
  102775. if (json.nodes) {
  102776. json.nodes = json.nodes.map((node, i) => this._resolveNode(node, i));
  102777. }
  102778. if (json.skins) {
  102779. json.skins = json.skins.map((skin, i) => this._resolveSkin(skin, i));
  102780. }
  102781. if (json.scenes) {
  102782. json.scenes = json.scenes.map((scene, i) => this._resolveScene(scene, i));
  102783. }
  102784. if (json.scene !== undefined) {
  102785. json.scene = json.scenes[this.json.scene];
  102786. }
  102787. }
  102788. getScene(index) {
  102789. return this._get('scenes', index);
  102790. }
  102791. getNode(index) {
  102792. return this._get('nodes', index);
  102793. }
  102794. getSkin(index) {
  102795. return this._get('skins', index);
  102796. }
  102797. getMesh(index) {
  102798. return this._get('meshes', index);
  102799. }
  102800. getMaterial(index) {
  102801. return this._get('materials', index);
  102802. }
  102803. getAccessor(index) {
  102804. return this._get('accessors', index);
  102805. }
  102806. getCamera(index) {
  102807. return null;
  102808. }
  102809. getTexture(index) {
  102810. return this._get('textures', index);
  102811. }
  102812. getSampler(index) {
  102813. return this._get('samplers', index);
  102814. }
  102815. getImage(index) {
  102816. return this._get('images', index);
  102817. }
  102818. getBufferView(index) {
  102819. return this._get('bufferViews', index);
  102820. }
  102821. getBuffer(index) {
  102822. return this._get('buffers', index);
  102823. }
  102824. _get(array, index) {
  102825. if (typeof index === 'object') {
  102826. return index;
  102827. }
  102828. const object = this.json[array] && this.json[array][index];
  102829. if (!object) {
  102830. console.warn("glTF file error: Could not find ".concat(array, "[").concat(index, "]"));
  102831. }
  102832. return object;
  102833. }
  102834. _resolveScene(scene, index) {
  102835. scene.id = scene.id || "scene-".concat(index);
  102836. scene.nodes = (scene.nodes || []).map(node => this.getNode(node));
  102837. return scene;
  102838. }
  102839. _resolveNode(node, index) {
  102840. node.id = node.id || "node-".concat(index);
  102841. if (node.children) {
  102842. node.children = node.children.map(child => this.getNode(child));
  102843. }
  102844. if (node.mesh !== undefined) {
  102845. node.mesh = this.getMesh(node.mesh);
  102846. } else if (node.meshes !== undefined && node.meshes.length) {
  102847. node.mesh = node.meshes.reduce((accum, meshIndex) => {
  102848. const mesh = this.getMesh(meshIndex);
  102849. accum.id = mesh.id;
  102850. accum.primitives = accum.primitives.concat(mesh.primitives);
  102851. return accum;
  102852. }, {
  102853. primitives: []
  102854. });
  102855. }
  102856. if (node.camera !== undefined) {
  102857. node.camera = this.getCamera(node.camera);
  102858. }
  102859. if (node.skin !== undefined) {
  102860. node.skin = this.getSkin(node.skin);
  102861. }
  102862. return node;
  102863. }
  102864. _resolveSkin(skin, index) {
  102865. skin.id = skin.id || "skin-".concat(index);
  102866. skin.inverseBindMatrices = this.getAccessor(skin.inverseBindMatrices);
  102867. return skin;
  102868. }
  102869. _resolveMesh(mesh, index) {
  102870. mesh.id = mesh.id || "mesh-".concat(index);
  102871. if (mesh.primitives) {
  102872. mesh.primitives = mesh.primitives.map(primitive => {
  102873. primitive = { ...primitive
  102874. };
  102875. const attributes = primitive.attributes;
  102876. primitive.attributes = {};
  102877. for (const attribute in attributes) {
  102878. primitive.attributes[attribute] = this.getAccessor(attributes[attribute]);
  102879. }
  102880. if (primitive.indices !== undefined) {
  102881. primitive.indices = this.getAccessor(primitive.indices);
  102882. }
  102883. if (primitive.material !== undefined) {
  102884. primitive.material = this.getMaterial(primitive.material);
  102885. }
  102886. return primitive;
  102887. });
  102888. }
  102889. return mesh;
  102890. }
  102891. _resolveMaterial(material, index) {
  102892. material.id = material.id || "material-".concat(index);
  102893. if (material.normalTexture) {
  102894. material.normalTexture = { ...material.normalTexture
  102895. };
  102896. material.normalTexture.texture = this.getTexture(material.normalTexture.index);
  102897. }
  102898. if (material.occlusionTexture) {
  102899. material.occlustionTexture = { ...material.occlustionTexture
  102900. };
  102901. material.occlusionTexture.texture = this.getTexture(material.occlusionTexture.index);
  102902. }
  102903. if (material.emissiveTexture) {
  102904. material.emmisiveTexture = { ...material.emmisiveTexture
  102905. };
  102906. material.emissiveTexture.texture = this.getTexture(material.emissiveTexture.index);
  102907. }
  102908. if (!material.emissiveFactor) {
  102909. material.emissiveFactor = material.emmisiveTexture ? [1, 1, 1] : [0, 0, 0];
  102910. }
  102911. if (material.pbrMetallicRoughness) {
  102912. material.pbrMetallicRoughness = { ...material.pbrMetallicRoughness
  102913. };
  102914. const mr = material.pbrMetallicRoughness;
  102915. if (mr.baseColorTexture) {
  102916. mr.baseColorTexture = { ...mr.baseColorTexture
  102917. };
  102918. mr.baseColorTexture.texture = this.getTexture(mr.baseColorTexture.index);
  102919. }
  102920. if (mr.metallicRoughnessTexture) {
  102921. mr.metallicRoughnessTexture = { ...mr.metallicRoughnessTexture
  102922. };
  102923. mr.metallicRoughnessTexture.texture = this.getTexture(mr.metallicRoughnessTexture.index);
  102924. }
  102925. }
  102926. return material;
  102927. }
  102928. _resolveAccessor(accessor, index) {
  102929. accessor.id = accessor.id || "accessor-".concat(index);
  102930. if (accessor.bufferView !== undefined) {
  102931. accessor.bufferView = this.getBufferView(accessor.bufferView);
  102932. }
  102933. accessor.bytesPerComponent = getBytesFromComponentType(accessor.componentType);
  102934. accessor.components = getSizeFromAccessorType(accessor.type);
  102935. accessor.bytesPerElement = accessor.bytesPerComponent * accessor.components;
  102936. if (accessor.bufferView) {
  102937. const buffer = accessor.bufferView.buffer;
  102938. const {
  102939. ArrayType,
  102940. byteLength
  102941. } = getAccessorArrayTypeAndLength(accessor, accessor.bufferView);
  102942. const byteOffset = (accessor.bufferView.byteOffset || 0) + (accessor.byteOffset || 0) + buffer.byteOffset;
  102943. let cutBuffer = buffer.arrayBuffer.slice(byteOffset, byteOffset + byteLength);
  102944. if (accessor.bufferView.byteStride) {
  102945. cutBuffer = this._getValueFromInterleavedBuffer(buffer, byteOffset, accessor.bufferView.byteStride, accessor.bytesPerElement, accessor.count);
  102946. }
  102947. accessor.value = new ArrayType(cutBuffer);
  102948. }
  102949. return accessor;
  102950. }
  102951. _getValueFromInterleavedBuffer(buffer, byteOffset, byteStride, bytesPerElement, count) {
  102952. const result = new Uint8Array(count * bytesPerElement);
  102953. for (let i = 0; i < count; i++) {
  102954. const elementOffset = byteOffset + i * byteStride;
  102955. result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset, elementOffset + bytesPerElement)), i * bytesPerElement);
  102956. }
  102957. return result.buffer;
  102958. }
  102959. _resolveTexture(texture, index) {
  102960. texture.id = texture.id || "texture-".concat(index);
  102961. texture.sampler = 'sampler' in texture ? this.getSampler(texture.sampler) : DEFAULT_SAMPLER;
  102962. texture.source = this.getImage(texture.source);
  102963. return texture;
  102964. }
  102965. _resolveSampler(sampler, index) {
  102966. sampler.id = sampler.id || "sampler-".concat(index);
  102967. sampler.parameters = {};
  102968. for (const key in sampler) {
  102969. const glEnum = this._enumSamplerParameter(key);
  102970. if (glEnum !== undefined) {
  102971. sampler.parameters[glEnum] = sampler[key];
  102972. }
  102973. }
  102974. return sampler;
  102975. }
  102976. _enumSamplerParameter(key) {
  102977. return SAMPLER_PARAMETER_GLTF_TO_GL[key];
  102978. }
  102979. _resolveImage(image, index) {
  102980. image.id = image.id || "image-".concat(index);
  102981. if (image.bufferView !== undefined) {
  102982. image.bufferView = this.getBufferView(image.bufferView);
  102983. }
  102984. const preloadedImage = this.images[index];
  102985. if (preloadedImage) {
  102986. image.image = preloadedImage;
  102987. }
  102988. return image;
  102989. }
  102990. _resolveBufferView(bufferView, index) {
  102991. const bufferIndex = bufferView.buffer;
  102992. const result = {
  102993. id: "bufferView-".concat(index),
  102994. ...bufferView,
  102995. buffer: this.buffers[bufferIndex]
  102996. };
  102997. const arrayBuffer = this.buffers[bufferIndex].arrayBuffer;
  102998. let byteOffset = this.buffers[bufferIndex].byteOffset || 0;
  102999. if ('byteOffset' in bufferView) {
  103000. byteOffset += bufferView.byteOffset;
  103001. }
  103002. result.data = new Uint8Array(arrayBuffer, byteOffset, bufferView.byteLength);
  103003. return result;
  103004. }
  103005. _resolveCamera(camera, index) {
  103006. camera.id = camera.id || "camera-".concat(index);
  103007. if (camera.perspective) ;
  103008. if (camera.orthographic) ;
  103009. return camera;
  103010. }
  103011. }
  103012. function postProcessGLTF(gltf, options) {
  103013. return new GLTFPostProcessor().postProcess(gltf, options);
  103014. }
  103015. const MAGIC_glTF = 0x676c5446;
  103016. const GLB_FILE_HEADER_SIZE = 12;
  103017. const GLB_CHUNK_HEADER_SIZE = 8;
  103018. const GLB_CHUNK_TYPE_JSON = 0x4e4f534a;
  103019. const GLB_CHUNK_TYPE_BIN = 0x004e4942;
  103020. const GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED = 0;
  103021. const GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED = 1;
  103022. const GLB_V1_CONTENT_FORMAT_JSON = 0x0;
  103023. const LE = true;
  103024. function getMagicString(dataView, byteOffset = 0) {
  103025. 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)));
  103026. }
  103027. function isGLB(arrayBuffer, byteOffset = 0, options = {}) {
  103028. const dataView = new DataView(arrayBuffer);
  103029. const {
  103030. magic = MAGIC_glTF
  103031. } = options;
  103032. const magic1 = dataView.getUint32(byteOffset, false);
  103033. return magic1 === magic || magic1 === MAGIC_glTF;
  103034. }
  103035. function parseGLBSync(glb, arrayBuffer, byteOffset = 0, options = {}) {
  103036. const dataView = new DataView(arrayBuffer);
  103037. const type = getMagicString(dataView, byteOffset + 0);
  103038. const version = dataView.getUint32(byteOffset + 4, LE);
  103039. const byteLength = dataView.getUint32(byteOffset + 8, LE);
  103040. Object.assign(glb, {
  103041. header: {
  103042. byteOffset,
  103043. byteLength,
  103044. hasBinChunk: false
  103045. },
  103046. type,
  103047. version,
  103048. json: {},
  103049. binChunks: []
  103050. });
  103051. byteOffset += GLB_FILE_HEADER_SIZE;
  103052. switch (glb.version) {
  103053. case 1:
  103054. return parseGLBV1(glb, dataView, byteOffset);
  103055. case 2:
  103056. return parseGLBV2(glb, dataView, byteOffset, options = {});
  103057. default:
  103058. throw new Error("Invalid GLB version ".concat(glb.version, ". Only supports v1 and v2."));
  103059. }
  103060. }
  103061. function parseGLBV1(glb, dataView, byteOffset) {
  103062. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  103063. const contentLength = dataView.getUint32(byteOffset + 0, LE);
  103064. const contentFormat = dataView.getUint32(byteOffset + 4, LE);
  103065. byteOffset += GLB_CHUNK_HEADER_SIZE;
  103066. assert$7(contentFormat === GLB_V1_CONTENT_FORMAT_JSON);
  103067. parseJSONChunk(glb, dataView, byteOffset, contentLength);
  103068. byteOffset += contentLength;
  103069. byteOffset += parseBINChunk(glb, dataView, byteOffset, glb.header.byteLength);
  103070. return byteOffset;
  103071. }
  103072. function parseGLBV2(glb, dataView, byteOffset, options) {
  103073. assert$7(glb.header.byteLength > GLB_FILE_HEADER_SIZE + GLB_CHUNK_HEADER_SIZE);
  103074. parseGLBChunksSync(glb, dataView, byteOffset, options);
  103075. return byteOffset + glb.header.byteLength;
  103076. }
  103077. function parseGLBChunksSync(glb, dataView, byteOffset, options) {
  103078. while (byteOffset + 8 <= glb.header.byteLength) {
  103079. const chunkLength = dataView.getUint32(byteOffset + 0, LE);
  103080. const chunkFormat = dataView.getUint32(byteOffset + 4, LE);
  103081. byteOffset += GLB_CHUNK_HEADER_SIZE;
  103082. switch (chunkFormat) {
  103083. case GLB_CHUNK_TYPE_JSON:
  103084. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  103085. break;
  103086. case GLB_CHUNK_TYPE_BIN:
  103087. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  103088. break;
  103089. case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:
  103090. if (!options.strict) {
  103091. parseJSONChunk(glb, dataView, byteOffset, chunkLength);
  103092. }
  103093. break;
  103094. case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:
  103095. if (!options.strict) {
  103096. parseBINChunk(glb, dataView, byteOffset, chunkLength);
  103097. }
  103098. break;
  103099. }
  103100. byteOffset += padToNBytes(chunkLength, 4);
  103101. }
  103102. return byteOffset;
  103103. }
  103104. function parseJSONChunk(glb, dataView, byteOffset, chunkLength) {
  103105. const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength);
  103106. const textDecoder = new TextDecoder('utf8');
  103107. const jsonText = textDecoder.decode(jsonChunk);
  103108. glb.json = JSON.parse(jsonText);
  103109. return padToNBytes(chunkLength, 4);
  103110. }
  103111. function parseBINChunk(glb, dataView, byteOffset, chunkLength) {
  103112. glb.header.hasBinChunk = true;
  103113. glb.binChunks.push({
  103114. byteOffset,
  103115. byteLength: chunkLength,
  103116. arrayBuffer: dataView.buffer
  103117. });
  103118. return padToNBytes(chunkLength, 4);
  103119. }
  103120. async function parseGLTF(gltf, arrayBufferOrString, byteOffset = 0, options, context) {
  103121. var _options$gltf, _options$gltf2, _options$gltf3, _options$gltf4;
  103122. parseGLTFContainerSync(gltf, arrayBufferOrString, byteOffset, options);
  103123. normalizeGLTFV1(gltf, {
  103124. normalize: options === null || options === void 0 ? void 0 : (_options$gltf = options.gltf) === null || _options$gltf === void 0 ? void 0 : _options$gltf.normalize
  103125. });
  103126. preprocessExtensions(gltf, options, context);
  103127. const promises = [];
  103128. if (options !== null && options !== void 0 && (_options$gltf2 = options.gltf) !== null && _options$gltf2 !== void 0 && _options$gltf2.loadBuffers && gltf.json.buffers) {
  103129. await loadBuffers(gltf, options, context);
  103130. }
  103131. if (options !== null && options !== void 0 && (_options$gltf3 = options.gltf) !== null && _options$gltf3 !== void 0 && _options$gltf3.loadImages) {
  103132. const promise = loadImages(gltf, options, context);
  103133. promises.push(promise);
  103134. }
  103135. const promise = decodeExtensions(gltf, options, context);
  103136. promises.push(promise);
  103137. await Promise.all(promises);
  103138. return options !== null && options !== void 0 && (_options$gltf4 = options.gltf) !== null && _options$gltf4 !== void 0 && _options$gltf4.postProcess ? postProcessGLTF(gltf, options) : gltf;
  103139. }
  103140. function parseGLTFContainerSync(gltf, data, byteOffset, options) {
  103141. if (options.uri) {
  103142. gltf.baseUri = options.uri;
  103143. }
  103144. if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options)) {
  103145. const textDecoder = new TextDecoder();
  103146. data = textDecoder.decode(data);
  103147. }
  103148. if (typeof data === 'string') {
  103149. gltf.json = parseJSON(data);
  103150. } else if (data instanceof ArrayBuffer) {
  103151. const glb = {};
  103152. byteOffset = parseGLBSync(glb, data, byteOffset, options.glb);
  103153. assert$1(glb.type === 'glTF', "Invalid GLB magic string ".concat(glb.type));
  103154. gltf._glb = glb;
  103155. gltf.json = glb.json;
  103156. } else {
  103157. assert$1(false, 'GLTF: must be ArrayBuffer or string');
  103158. }
  103159. const buffers = gltf.json.buffers || [];
  103160. gltf.buffers = new Array(buffers.length).fill(null);
  103161. if (gltf._glb && gltf._glb.header.hasBinChunk) {
  103162. const {
  103163. binChunks
  103164. } = gltf._glb;
  103165. gltf.buffers[0] = {
  103166. arrayBuffer: binChunks[0].arrayBuffer,
  103167. byteOffset: binChunks[0].byteOffset,
  103168. byteLength: binChunks[0].byteLength
  103169. };
  103170. }
  103171. const images = gltf.json.images || [];
  103172. gltf.images = new Array(images.length).fill({});
  103173. }
  103174. async function loadBuffers(gltf, options, context) {
  103175. const buffers = gltf.json.buffers || [];
  103176. for (let i = 0; i < buffers.length; ++i) {
  103177. const buffer = buffers[i];
  103178. if (buffer.uri) {
  103179. var _context$fetch, _response$arrayBuffer;
  103180. const {
  103181. fetch
  103182. } = context;
  103183. assert$1(fetch);
  103184. const uri = resolveUrl(buffer.uri, options);
  103185. const response = await (context === null || context === void 0 ? void 0 : (_context$fetch = context.fetch) === null || _context$fetch === void 0 ? void 0 : _context$fetch.call(context, uri));
  103186. const arrayBuffer = await (response === null || response === void 0 ? void 0 : (_response$arrayBuffer = response.arrayBuffer) === null || _response$arrayBuffer === void 0 ? void 0 : _response$arrayBuffer.call(response));
  103187. gltf.buffers[i] = {
  103188. arrayBuffer,
  103189. byteOffset: 0,
  103190. byteLength: arrayBuffer.byteLength
  103191. };
  103192. delete buffer.uri;
  103193. }
  103194. }
  103195. }
  103196. async function loadImages(gltf, options, context) {
  103197. const imageIndices = getReferencesImageIndices(gltf);
  103198. const images = gltf.json.images || [];
  103199. const promises = [];
  103200. for (const imageIndex of imageIndices) {
  103201. promises.push(loadImage(gltf, images[imageIndex], imageIndex, options, context));
  103202. }
  103203. return await Promise.all(promises);
  103204. }
  103205. function getReferencesImageIndices(gltf) {
  103206. const imageIndices = new Set();
  103207. const textures = gltf.json.textures || [];
  103208. for (const texture of textures) {
  103209. if (texture.source !== undefined) {
  103210. imageIndices.add(texture.source);
  103211. }
  103212. }
  103213. return Array.from(imageIndices).sort();
  103214. }
  103215. async function loadImage(gltf, image, index, options, context) {
  103216. const {
  103217. fetch,
  103218. parse
  103219. } = context;
  103220. let arrayBuffer;
  103221. if (image.uri) {
  103222. const uri = resolveUrl(image.uri, options);
  103223. const response = await fetch(uri);
  103224. arrayBuffer = await response.arrayBuffer();
  103225. }
  103226. if (Number.isFinite(image.bufferView)) {
  103227. const array = getTypedArrayForBufferView(gltf.json, gltf.buffers, image.bufferView);
  103228. arrayBuffer = sliceArrayBuffer(array.buffer, array.byteOffset, array.byteLength);
  103229. }
  103230. assert$1(arrayBuffer, 'glTF image has no data');
  103231. let parsedImage = await parse(arrayBuffer, [ImageLoader$1, BasisLoader], {
  103232. mimeType: image.mimeType,
  103233. basis: options.basis || {
  103234. format: selectSupportedBasisFormat()
  103235. }
  103236. }, context);
  103237. if (parsedImage && parsedImage[0]) {
  103238. parsedImage = {
  103239. compressed: true,
  103240. mipmaps: false,
  103241. width: parsedImage[0].width,
  103242. height: parsedImage[0].height,
  103243. data: parsedImage
  103244. };
  103245. }
  103246. gltf.images = gltf.images || [];
  103247. gltf.images[index] = parsedImage;
  103248. }
  103249. const GLTFLoader$1 = {
  103250. name: 'glTF',
  103251. id: 'gltf',
  103252. module: 'gltf',
  103253. version: VERSION$3,
  103254. extensions: ['gltf', 'glb'],
  103255. mimeTypes: ['model/gltf+json', 'model/gltf-binary'],
  103256. text: true,
  103257. binary: true,
  103258. tests: ['glTF'],
  103259. parse: parse$1,
  103260. options: {
  103261. gltf: {
  103262. normalize: true,
  103263. loadBuffers: true,
  103264. loadImages: true,
  103265. decompressMeshes: true,
  103266. postProcess: true
  103267. },
  103268. log: console
  103269. },
  103270. deprecatedOptions: {
  103271. fetchImages: 'gltf.loadImages',
  103272. createImages: 'gltf.loadImages',
  103273. decompress: 'gltf.decompressMeshes',
  103274. postProcess: 'gltf.postProcess',
  103275. gltf: {
  103276. decompress: 'gltf.decompressMeshes'
  103277. }
  103278. }
  103279. };
  103280. async function parse$1(arrayBuffer, options = {}, context) {
  103281. options = { ...GLTFLoader$1.options,
  103282. ...options
  103283. };
  103284. options.gltf = { ...GLTFLoader$1.options.gltf,
  103285. ...options.gltf
  103286. };
  103287. const {
  103288. byteOffset = 0
  103289. } = options;
  103290. const gltf = {};
  103291. return await parseGLTF(gltf, arrayBuffer, byteOffset, options, context);
  103292. }
  103293. const GLTF_FORMAT = {
  103294. URI: 0,
  103295. EMBEDDED: 1
  103296. };
  103297. function parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options) {
  103298. tile.rotateYtoZ = true;
  103299. const gltfByteLength = tile.byteOffset + tile.byteLength - byteOffset;
  103300. if (gltfByteLength === 0) {
  103301. throw new Error('glTF byte length must be greater than 0.');
  103302. }
  103303. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  103304. tile.gltfArrayBuffer = sliceArrayBuffer(arrayBuffer, byteOffset, gltfByteLength);
  103305. tile.gltfByteOffset = 0;
  103306. tile.gltfByteLength = gltfByteLength;
  103307. if (byteOffset % 4 === 0) ; else {
  103308. console.warn("".concat(tile.type, ": embedded glb is not aligned to a 4-byte boundary."));
  103309. }
  103310. return tile.byteOffset + tile.byteLength;
  103311. }
  103312. async function extractGLTF(tile, gltfFormat, options, context) {
  103313. const tile3DOptions = options['3d-tiles'] || {};
  103314. extractGLTFBufferOrURL(tile, gltfFormat);
  103315. if (tile3DOptions.loadGLTF) {
  103316. const {
  103317. parse,
  103318. fetch
  103319. } = context;
  103320. if (tile.gltfUrl) {
  103321. tile.gltfArrayBuffer = await fetch(tile.gltfUrl, options);
  103322. tile.gltfByteOffset = 0;
  103323. }
  103324. if (tile.gltfArrayBuffer) {
  103325. tile.gltf = await parse(tile.gltfArrayBuffer, GLTFLoader$1, options, context);
  103326. delete tile.gltfArrayBuffer;
  103327. delete tile.gltfByteOffset;
  103328. delete tile.gltfByteLength;
  103329. }
  103330. }
  103331. }
  103332. function extractGLTFBufferOrURL(tile, gltfFormat, options) {
  103333. switch (gltfFormat) {
  103334. case GLTF_FORMAT.URI:
  103335. const gltfUrlBytes = new Uint8Array(tile.gltfArrayBuffer, tile.gltfByteOffset);
  103336. const textDecoder = new TextDecoder();
  103337. const gltfUrl = textDecoder.decode(gltfUrlBytes);
  103338. tile.gltfUrl = gltfUrl.replace(/[\s\0]+$/, '');
  103339. delete tile.gltfArrayBuffer;
  103340. delete tile.gltfByteOffset;
  103341. delete tile.gltfByteLength;
  103342. break;
  103343. case GLTF_FORMAT.EMBEDDED:
  103344. break;
  103345. default:
  103346. throw new Error('b3dm: Illegal glTF format field');
  103347. }
  103348. }
  103349. async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  103350. var _tile$gltf;
  103351. byteOffset = parseBatchedModel(tile, arrayBuffer, byteOffset, options);
  103352. await extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options, context);
  103353. const extensions = tile === null || tile === void 0 ? void 0 : (_tile$gltf = tile.gltf) === null || _tile$gltf === void 0 ? void 0 : _tile$gltf.extensions;
  103354. if (extensions && extensions.CESIUM_RTC) {
  103355. tile.rtcCenter = extensions.CESIUM_RTC.center;
  103356. }
  103357. return byteOffset;
  103358. }
  103359. function parseBatchedModel(tile, arrayBuffer, byteOffset, options, context) {
  103360. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  103361. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  103362. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  103363. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  103364. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  103365. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  103366. return byteOffset;
  103367. }
  103368. async function parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context) {
  103369. byteOffset = parseInstancedModel(tile, arrayBuffer, byteOffset, options);
  103370. await extractGLTF(tile, tile.gltfFormat, options, context);
  103371. return byteOffset;
  103372. }
  103373. function parseInstancedModel(tile, arrayBuffer, byteOffset, options, context) {
  103374. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  103375. if (tile.version !== 1) {
  103376. throw new Error("Instanced 3D Model version ".concat(tile.version, " is not supported"));
  103377. }
  103378. byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset);
  103379. const view = new DataView(arrayBuffer);
  103380. tile.gltfFormat = view.getUint32(byteOffset, true);
  103381. byteOffset += 4;
  103382. byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset);
  103383. byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options);
  103384. if (tile.featureTableJsonByteLength === 0) {
  103385. throw new Error('i3dm parser: featureTableJsonByteLength is zero.');
  103386. }
  103387. const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary);
  103388. const instancesLength = featureTable.getGlobalProperty('INSTANCES_LENGTH');
  103389. featureTable.featuresLength = instancesLength;
  103390. if (!Number.isFinite(instancesLength)) {
  103391. throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');
  103392. }
  103393. tile.eastNorthUp = featureTable.getGlobalProperty('EAST_NORTH_UP');
  103394. tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL$1.FLOAT, 3);
  103395. const batchTable = new Tile3DBatchTableParser(tile.batchTableJson, tile.batchTableBinary, instancesLength);
  103396. extractInstancedAttributes(tile, featureTable, batchTable, instancesLength);
  103397. return byteOffset;
  103398. }
  103399. function extractInstancedAttributes(tile, featureTable, batchTable, instancesLength) {
  103400. const collectionOptions = {
  103401. instances: new Array(instancesLength),
  103402. batchTable: tile._batchTable,
  103403. cull: false,
  103404. url: undefined,
  103405. gltf: undefined,
  103406. basePath: undefined,
  103407. incrementallyLoadTextures: false,
  103408. forwardAxis: [1, 0, 0]
  103409. };
  103410. const instances = collectionOptions.instances;
  103411. const instancePosition = new Vector3$1();
  103412. new Vector3$1();
  103413. new Vector3$1();
  103414. new Vector3$1();
  103415. const instanceRotation = new Matrix3$1();
  103416. const instanceQuaternion = new Quaternion$1();
  103417. const instanceScale = new Vector3$1();
  103418. const instanceTranslationRotationScale = {};
  103419. const instanceTransform = new Matrix4$1();
  103420. const scratch1 = [];
  103421. const scratch2 = [];
  103422. const scratchVector1 = new Vector3$1();
  103423. const scratchVector2 = new Vector3$1();
  103424. for (let i = 0; i < instancesLength; i++) {
  103425. let position;
  103426. if (featureTable.hasProperty('POSITION')) {
  103427. position = featureTable.getProperty('POSITION', GL$1.FLOAT, 3, i, instancePosition);
  103428. } else if (featureTable.hasProperty('POSITION_QUANTIZED')) {
  103429. position = featureTable.getProperty('POSITION_QUANTIZED', GL$1.UNSIGNED_SHORT, 3, i, instancePosition);
  103430. const quantizedVolumeOffset = featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET', GL$1.FLOAT, 3, scratchVector1);
  103431. if (!quantizedVolumeOffset) {
  103432. throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');
  103433. }
  103434. const quantizedVolumeScale = featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE', GL$1.FLOAT, 3, scratchVector2);
  103435. if (!quantizedVolumeScale) {
  103436. throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');
  103437. }
  103438. const MAX_UNSIGNED_SHORT = 65535.0;
  103439. for (let j = 0; j < 3; j++) {
  103440. position[j] = position[j] / MAX_UNSIGNED_SHORT * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
  103441. }
  103442. }
  103443. if (!position) {
  103444. throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');
  103445. }
  103446. instancePosition.copy(position);
  103447. instanceTranslationRotationScale.translation = instancePosition;
  103448. tile.normalUp = featureTable.getProperty('NORMAL_UP', GL$1.FLOAT, 3, i, scratch1);
  103449. tile.normalRight = featureTable.getProperty('NORMAL_RIGHT', GL$1.FLOAT, 3, i, scratch2);
  103450. if (tile.normalUp) {
  103451. if (!tile.normalRight) {
  103452. throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');
  103453. }
  103454. tile.hasCustomOrientation = true;
  103455. } else {
  103456. tile.octNormalUp = featureTable.getProperty('NORMAL_UP_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch1);
  103457. tile.octNormalRight = featureTable.getProperty('NORMAL_RIGHT_OCT32P', GL$1.UNSIGNED_SHORT, 2, scratch2);
  103458. if (tile.octNormalUp) {
  103459. if (!tile.octNormalRight) {
  103460. throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');
  103461. }
  103462. throw new Error('i3dm: oct-encoded orientation not implemented');
  103463. } else if (tile.eastNorthUp) {
  103464. Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition, instanceTransform);
  103465. instanceTransform.getRotationMatrix3(instanceRotation);
  103466. } else {
  103467. instanceRotation.identity();
  103468. }
  103469. }
  103470. instanceQuaternion.fromMatrix3(instanceRotation);
  103471. instanceTranslationRotationScale.rotation = instanceQuaternion;
  103472. instanceScale.set(1.0, 1.0, 1.0);
  103473. const scale = featureTable.getProperty('SCALE', GL$1.FLOAT, 1, i);
  103474. if (Number.isFinite(scale)) {
  103475. instanceScale.multiplyByScalar(scale);
  103476. }
  103477. const nonUniformScale = featureTable.getProperty('SCALE_NON_UNIFORM', GL$1.FLOAT, 3, i, scratch1);
  103478. if (nonUniformScale) {
  103479. instanceScale.scale(nonUniformScale);
  103480. }
  103481. instanceTranslationRotationScale.scale = instanceScale;
  103482. let batchId = featureTable.getProperty('BATCH_ID', GL$1.UNSIGNED_SHORT, 1, i);
  103483. if (batchId === undefined) {
  103484. batchId = i;
  103485. }
  103486. const rotationMatrix = new Matrix4$1().fromQuaternion(instanceTranslationRotationScale.rotation);
  103487. instanceTransform.identity();
  103488. instanceTransform.translate(instanceTranslationRotationScale.translation);
  103489. instanceTransform.multiplyRight(rotationMatrix);
  103490. instanceTransform.scale(instanceTranslationRotationScale.scale);
  103491. const modelMatrix = instanceTransform.clone();
  103492. instances[i] = {
  103493. modelMatrix,
  103494. batchId
  103495. };
  103496. }
  103497. tile.instances = instances;
  103498. }
  103499. async function parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile) {
  103500. byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset);
  103501. const view = new DataView(arrayBuffer);
  103502. tile.tilesLength = view.getUint32(byteOffset, true);
  103503. byteOffset += 4;
  103504. tile.tiles = [];
  103505. while (tile.tiles.length < tile.tilesLength && tile.byteLength - byteOffset > 12) {
  103506. const subtile = {};
  103507. tile.tiles.push(subtile);
  103508. byteOffset = await parse3DTile(arrayBuffer, byteOffset, options, context, subtile);
  103509. }
  103510. return byteOffset;
  103511. }
  103512. async function parseGltf3DTile(tile, arrayBuffer, options, context) {
  103513. tile.rotateYtoZ = true;
  103514. tile.gltfUpAxis = options['3d-tiles'] && options['3d-tiles'].assetGltfUpAxis ? options['3d-tiles'].assetGltfUpAxis : 'Y';
  103515. const {
  103516. parse
  103517. } = context;
  103518. tile.gltf = await parse(arrayBuffer, GLTFLoader$1, options, context);
  103519. }
  103520. async function parse3DTile(arrayBuffer, byteOffset = 0, options, context, tile = {}) {
  103521. tile.byteOffset = byteOffset;
  103522. tile.type = getMagicString$1(arrayBuffer, byteOffset);
  103523. switch (tile.type) {
  103524. case TILE3D_TYPE.COMPOSITE:
  103525. return await parseComposite3DTile(tile, arrayBuffer, byteOffset, options, context, parse3DTile);
  103526. case TILE3D_TYPE.BATCHED_3D_MODEL:
  103527. return await parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  103528. case TILE3D_TYPE.GLTF:
  103529. return await parseGltf3DTile(tile, arrayBuffer, options, context);
  103530. case TILE3D_TYPE.INSTANCED_3D_MODEL:
  103531. return await parseInstancedModel3DTile(tile, arrayBuffer, byteOffset, options, context);
  103532. case TILE3D_TYPE.POINT_CLOUD:
  103533. return await parsePointCloud3DTile(tile, arrayBuffer, byteOffset, options, context);
  103534. default:
  103535. throw new Error("3DTileLoader: unknown type ".concat(tile.type));
  103536. }
  103537. }
  103538. const SUBTREE_FILE_MAGIC = 0x74627573;
  103539. const SUBTREE_FILE_VERSION = 1;
  103540. async function parse3DTilesSubtree(data) {
  103541. const magic = new Uint32Array(data.slice(0, 4));
  103542. if (magic[0] !== SUBTREE_FILE_MAGIC) {
  103543. throw new Error('Wrong subtree file magic number');
  103544. }
  103545. const version = new Uint32Array(data.slice(4, 8));
  103546. if (version[0] !== SUBTREE_FILE_VERSION) {
  103547. throw new Error('Wrong subtree file verson, must be 1');
  103548. }
  103549. const jsonByteLength = parseUint64Value(data.slice(8, 16));
  103550. const stringAttribute = new Uint8Array(data, 24, jsonByteLength);
  103551. const textDecoder = new TextDecoder('utf8');
  103552. const string = textDecoder.decode(stringAttribute);
  103553. const subtree = JSON.parse(string);
  103554. const binaryByteLength = parseUint64Value(data.slice(16, 24));
  103555. let internalBinaryBuffer = new ArrayBuffer(0);
  103556. if (binaryByteLength) {
  103557. internalBinaryBuffer = data.slice(24 + jsonByteLength);
  103558. }
  103559. if ('bufferView' in subtree.tileAvailability) {
  103560. subtree.tileAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'tileAvailability', internalBinaryBuffer);
  103561. }
  103562. if ('bufferView' in subtree.contentAvailability) {
  103563. subtree.contentAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'contentAvailability', internalBinaryBuffer);
  103564. }
  103565. if ('bufferView' in subtree.childSubtreeAvailability) {
  103566. subtree.childSubtreeAvailability.explicitBitstream = await getExplicitBitstream(subtree, 'childSubtreeAvailability', internalBinaryBuffer);
  103567. }
  103568. return subtree;
  103569. }
  103570. async function getExplicitBitstream(subtree, name, internalBinaryBuffer) {
  103571. const bufferViewIndex = subtree[name].bufferView;
  103572. const bufferView = subtree.bufferViews[bufferViewIndex];
  103573. const buffer = subtree.buffers[bufferView.buffer];
  103574. if (buffer.uri) {
  103575. const response = await fetchFile(buffer.uri);
  103576. const data = await response.arrayBuffer();
  103577. return new Uint8Array(data, bufferView.byteOffset, bufferView.byteLength);
  103578. }
  103579. return new Uint8Array(internalBinaryBuffer, bufferView.byteOffset, bufferView.byteLength);
  103580. }
  103581. function parseUint64Value(buffer) {
  103582. const dataView = new DataView(buffer);
  103583. const left = dataView.getUint32(0, true);
  103584. const right = dataView.getUint32(4, true);
  103585. return left + 2 ** 32 * right;
  103586. }
  103587. const Tile3DSubtreeLoader = {
  103588. id: '3d-tiles-subtree',
  103589. name: '3D Tiles Subtree',
  103590. module: '3d-tiles',
  103591. version: VERSION$5,
  103592. extensions: ['subtree'],
  103593. mimeTypes: ['application/octet-stream'],
  103594. tests: ['subtree'],
  103595. parse: parse3DTilesSubtree,
  103596. options: {}
  103597. };
  103598. const QUADTREE_DEVISION_COUNT = 4;
  103599. const OCTREE_DEVISION_COUNT = 8;
  103600. const SUBDIVISION_COUNT_MAP = {
  103601. QUADTREE: QUADTREE_DEVISION_COUNT,
  103602. OCTREE: OCTREE_DEVISION_COUNT
  103603. };
  103604. async function parseImplicitTiles(subtree, options, parentData = {
  103605. mortonIndex: 0,
  103606. x: 0,
  103607. y: 0,
  103608. z: 0
  103609. }, childIndex = 0, level = 0, globalData = {
  103610. level: 0,
  103611. mortonIndex: 0,
  103612. x: 0,
  103613. y: 0,
  103614. z: 0
  103615. }) {
  103616. const {
  103617. subdivisionScheme,
  103618. subtreeLevels,
  103619. maximumLevel,
  103620. contentUrlTemplate,
  103621. subtreesUriTemplate,
  103622. basePath
  103623. } = options;
  103624. const tile = {
  103625. children: [],
  103626. lodMetricValue: 0,
  103627. contentUrl: ''
  103628. };
  103629. const childrenPerTile = SUBDIVISION_COUNT_MAP[subdivisionScheme];
  103630. const childX = childIndex & 0b01;
  103631. const childY = childIndex >> 1 & 0b01;
  103632. const childZ = childIndex >> 2 & 0b01;
  103633. const levelOffset = (childrenPerTile ** level - 1) / (childrenPerTile - 1);
  103634. let childTileMortonIndex = concatBits(parentData.mortonIndex, childIndex);
  103635. let tileAvailabilityIndex = levelOffset + childTileMortonIndex;
  103636. let childTileX = concatBits(parentData.x, childX);
  103637. let childTileY = concatBits(parentData.y, childY);
  103638. let childTileZ = concatBits(parentData.z, childZ);
  103639. let isChildSubtreeAvailable = false;
  103640. if (level + 1 > subtreeLevels) {
  103641. isChildSubtreeAvailable = getAvailabilityResult(subtree.childSubtreeAvailability, childTileMortonIndex);
  103642. }
  103643. const x = concatBits(globalData.x, childTileX);
  103644. const y = concatBits(globalData.y, childTileY);
  103645. const z = concatBits(globalData.z, childTileZ);
  103646. const lev = level + globalData.level;
  103647. if (isChildSubtreeAvailable) {
  103648. const subtreePath = "".concat(basePath, "/").concat(subtreesUriTemplate);
  103649. const childSubtreeUrl = replaceContentUrlTemplate(subtreePath, lev, x, y, z);
  103650. const childSubtree = await load(childSubtreeUrl, Tile3DSubtreeLoader);
  103651. subtree = childSubtree;
  103652. globalData.mortonIndex = childTileMortonIndex;
  103653. globalData.x = childTileX;
  103654. globalData.y = childTileY;
  103655. globalData.z = childTileZ;
  103656. globalData.level = level;
  103657. childTileMortonIndex = 0;
  103658. tileAvailabilityIndex = 0;
  103659. childTileX = 0;
  103660. childTileY = 0;
  103661. childTileZ = 0;
  103662. level = 0;
  103663. }
  103664. const isTileAvailable = getAvailabilityResult(subtree.tileAvailability, tileAvailabilityIndex);
  103665. if (!isTileAvailable || level > maximumLevel) {
  103666. return tile;
  103667. }
  103668. const isContentAvailable = getAvailabilityResult(subtree.contentAvailability, tileAvailabilityIndex);
  103669. if (isContentAvailable) {
  103670. tile.contentUrl = replaceContentUrlTemplate(contentUrlTemplate, lev, x, y, z);
  103671. }
  103672. const childTileLevel = level + 1;
  103673. const pData = {
  103674. mortonIndex: childTileMortonIndex,
  103675. x: childTileX,
  103676. y: childTileY,
  103677. z: childTileZ
  103678. };
  103679. for (let index = 0; index < childrenPerTile; index++) {
  103680. const currentTile = await parseImplicitTiles(subtree, options, pData, index, childTileLevel, globalData);
  103681. if (currentTile.contentUrl || currentTile.children.length) {
  103682. const globalLevel = lev + 1;
  103683. const childCoordinates = {
  103684. childTileX,
  103685. childTileY,
  103686. childTileZ
  103687. };
  103688. const formattedTile = formatTileData(currentTile, globalLevel, childCoordinates, options);
  103689. tile.children.push(formattedTile);
  103690. }
  103691. }
  103692. return tile;
  103693. }
  103694. function getAvailabilityResult(availabilityData, index) {
  103695. if ('constant' in availabilityData) {
  103696. return Boolean(availabilityData.constant);
  103697. }
  103698. if (availabilityData.explicitBitstream) {
  103699. return getBooleanValueFromBitstream(index, availabilityData.explicitBitstream);
  103700. }
  103701. return false;
  103702. }
  103703. function formatTileData(tile, level, childCoordinates, options) {
  103704. const {
  103705. basePath,
  103706. refine,
  103707. getRefine,
  103708. lodMetricType,
  103709. getTileType,
  103710. rootLodMetricValue,
  103711. rootBoundingVolume
  103712. } = options;
  103713. const uri = tile.contentUrl && tile.contentUrl.replace("".concat(basePath, "/"), '');
  103714. const lodMetricValue = rootLodMetricValue / 2 ** level;
  103715. const boundingVolume = calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates);
  103716. return {
  103717. children: tile.children,
  103718. contentUrl: tile.contentUrl,
  103719. content: {
  103720. uri
  103721. },
  103722. id: tile.contentUrl,
  103723. refine: getRefine(refine),
  103724. type: getTileType(tile),
  103725. lodMetricType,
  103726. lodMetricValue,
  103727. boundingVolume
  103728. };
  103729. }
  103730. function calculateBoundingVolumeForChildTile(level, rootBoundingVolume, childCoordinates) {
  103731. if (rootBoundingVolume.region) {
  103732. const {
  103733. childTileX,
  103734. childTileY,
  103735. childTileZ
  103736. } = childCoordinates;
  103737. const [west, south, east, north, minimumHeight, maximumHeight] = rootBoundingVolume.region;
  103738. const boundingVolumesCount = 2 ** level;
  103739. const sizeX = (east - west) / boundingVolumesCount;
  103740. const sizeY = (north - south) / boundingVolumesCount;
  103741. const sizeZ = (maximumHeight - minimumHeight) / boundingVolumesCount;
  103742. const [childWest, childEast] = [west + sizeX * childTileX, west + sizeX * (childTileX + 1)];
  103743. const [childSouth, childNorth] = [south + sizeY * childTileY, south + sizeY * (childTileY + 1)];
  103744. const [childMinimumHeight, childMaximumHeight] = [minimumHeight + sizeZ * childTileZ, minimumHeight + sizeZ * (childTileZ + 1)];
  103745. return {
  103746. region: [childWest, childSouth, childEast, childNorth, childMinimumHeight, childMaximumHeight]
  103747. };
  103748. }
  103749. console.warn('Unsupported bounding volume type: ', rootBoundingVolume);
  103750. return null;
  103751. }
  103752. function concatBits(first, second) {
  103753. return parseInt(first.toString(2) + second.toString(2), 2);
  103754. }
  103755. function replaceContentUrlTemplate(templateUrl, level, x, y, z) {
  103756. const mapUrl = generateMapUrl({
  103757. level,
  103758. x,
  103759. y,
  103760. z
  103761. });
  103762. return templateUrl.replace(/{level}|{x}|{y}|{z}/gi, matched => mapUrl[matched]);
  103763. }
  103764. function generateMapUrl(items) {
  103765. const mapUrl = {};
  103766. for (const key in items) {
  103767. mapUrl["{".concat(key, "}")] = items[key];
  103768. }
  103769. return mapUrl;
  103770. }
  103771. function getBooleanValueFromBitstream(availabilityIndex, availabilityBuffer) {
  103772. const byteIndex = Math.floor(availabilityIndex / 8);
  103773. const bitIndex = availabilityIndex % 8;
  103774. const bitValue = availabilityBuffer[byteIndex] >> bitIndex & 1;
  103775. return bitValue === 1;
  103776. }
  103777. function getTileType(tile) {
  103778. if (!tile.contentUrl) {
  103779. return TILE_TYPE.EMPTY;
  103780. }
  103781. const contentUrl = tile.contentUrl;
  103782. const fileExtension = contentUrl.split('.').pop();
  103783. switch (fileExtension) {
  103784. case 'pnts':
  103785. return TILE_TYPE.POINTCLOUD;
  103786. case 'i3dm':
  103787. case 'b3dm':
  103788. case 'glb':
  103789. case 'gltf':
  103790. return TILE_TYPE.SCENEGRAPH;
  103791. default:
  103792. return fileExtension;
  103793. }
  103794. }
  103795. function getRefine(refine) {
  103796. switch (refine) {
  103797. case 'REPLACE':
  103798. case 'replace':
  103799. return TILE_REFINEMENT.REPLACE;
  103800. case 'ADD':
  103801. case 'add':
  103802. return TILE_REFINEMENT.ADD;
  103803. default:
  103804. return refine;
  103805. }
  103806. }
  103807. function normalizeTileData(tile, options) {
  103808. if (!tile) {
  103809. return null;
  103810. }
  103811. if (tile.content) {
  103812. const contentUri = tile.content.uri || tile.content.url;
  103813. tile.contentUrl = "".concat(options.basePath, "/").concat(contentUri);
  103814. }
  103815. tile.id = tile.contentUrl;
  103816. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  103817. tile.lodMetricValue = tile.geometricError;
  103818. tile.transformMatrix = tile.transform;
  103819. tile.type = getTileType(tile);
  103820. tile.refine = getRefine(tile.refine);
  103821. return tile;
  103822. }
  103823. function normalizeTileHeaders(tileset) {
  103824. const basePath = tileset.basePath;
  103825. const root = normalizeTileData(tileset.root, tileset);
  103826. const stack = [];
  103827. stack.push(root);
  103828. while (stack.length > 0) {
  103829. const tile = stack.pop() || {};
  103830. const children = tile.children || [];
  103831. for (const childHeader of children) {
  103832. normalizeTileData(childHeader, {
  103833. basePath
  103834. });
  103835. stack.push(childHeader);
  103836. }
  103837. }
  103838. return root;
  103839. }
  103840. async function normalizeImplicitTileHeaders(tileset) {
  103841. if (!tileset.root) {
  103842. return null;
  103843. }
  103844. const basePath = tileset.basePath;
  103845. const implicitTilingExtension = tileset.root.extensions['3DTILES_implicit_tiling'];
  103846. const {
  103847. subdivisionScheme,
  103848. maximumLevel,
  103849. subtreeLevels,
  103850. subtrees: {
  103851. uri: subtreesUriTemplate
  103852. }
  103853. } = implicitTilingExtension;
  103854. const subtreeUrl = replaceContentUrlTemplate(subtreesUriTemplate, 0, 0, 0, 0);
  103855. const rootSubtreeUrl = "".concat(basePath, "/").concat(subtreeUrl);
  103856. const rootSubtree = await load(rootSubtreeUrl, Tile3DSubtreeLoader);
  103857. const contentUrlTemplate = "".concat(basePath, "/").concat(tileset.root.content.uri);
  103858. const refine = tileset.root.refine;
  103859. const rootLodMetricValue = tileset.root.geometricError;
  103860. const rootBoundingVolume = tileset.root.boundingVolume;
  103861. const options = {
  103862. contentUrlTemplate,
  103863. subtreesUriTemplate,
  103864. subdivisionScheme,
  103865. subtreeLevels,
  103866. maximumLevel,
  103867. refine,
  103868. basePath,
  103869. lodMetricType: LOD_METRIC_TYPE.GEOMETRIC_ERROR,
  103870. rootLodMetricValue,
  103871. rootBoundingVolume,
  103872. getTileType,
  103873. getRefine
  103874. };
  103875. return await normalizeImplicitTileData(tileset.root, rootSubtree, options);
  103876. }
  103877. async function normalizeImplicitTileData(tile, rootSubtree, options) {
  103878. if (!tile) {
  103879. return null;
  103880. }
  103881. tile.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  103882. tile.lodMetricValue = tile.geometricError;
  103883. tile.transformMatrix = tile.transform;
  103884. const {
  103885. children,
  103886. contentUrl
  103887. } = await parseImplicitTiles(rootSubtree, options);
  103888. if (contentUrl) {
  103889. tile.contentUrl = contentUrl;
  103890. tile.content = {
  103891. uri: contentUrl.replace("".concat(options.basePath, "/"), '')
  103892. };
  103893. }
  103894. tile.refine = getRefine(tile.refine);
  103895. tile.type = getTileType(tile);
  103896. tile.children = children;
  103897. tile.id = tile.contentUrl;
  103898. return tile;
  103899. }
  103900. const IMPLICIT_TILING_EXTENSION_NAME = '3DTILES_implicit_tiling';
  103901. const Tiles3DLoader = {
  103902. id: '3d-tiles',
  103903. name: '3D Tiles',
  103904. module: '3d-tiles',
  103905. version: VERSION$5,
  103906. extensions: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  103907. mimeTypes: ['application/octet-stream'],
  103908. tests: ['cmpt', 'pnts', 'b3dm', 'i3dm'],
  103909. parse: parse$4,
  103910. options: {
  103911. '3d-tiles': {
  103912. loadGLTF: true,
  103913. decodeQuantizedPositions: false,
  103914. isTileset: 'auto',
  103915. assetGltfUpAxis: null
  103916. }
  103917. }
  103918. };
  103919. function getBaseUri(tileset) {
  103920. return dirname(tileset.url);
  103921. }
  103922. async function parseTile(arrayBuffer, options, context) {
  103923. const tile = {
  103924. content: {
  103925. featureIds: null
  103926. }
  103927. };
  103928. const byteOffset = 0;
  103929. await parse3DTile(arrayBuffer, byteOffset, options, context, tile.content);
  103930. return tile.content;
  103931. }
  103932. async function parseTileset(data, options, context) {
  103933. var _tilesetJson$root;
  103934. const tilesetJson = JSON.parse(new TextDecoder().decode(data));
  103935. tilesetJson.loader = options.loader || Tiles3DLoader;
  103936. tilesetJson.url = context.url;
  103937. tilesetJson.basePath = getBaseUri(tilesetJson);
  103938. tilesetJson.root = hasImplicitTilingExtension(tilesetJson) ? await normalizeImplicitTileHeaders(tilesetJson) : normalizeTileHeaders(tilesetJson);
  103939. tilesetJson.type = TILESET_TYPE.TILES3D;
  103940. tilesetJson.lodMetricType = LOD_METRIC_TYPE.GEOMETRIC_ERROR;
  103941. tilesetJson.lodMetricValue = ((_tilesetJson$root = tilesetJson.root) === null || _tilesetJson$root === void 0 ? void 0 : _tilesetJson$root.lodMetricValue) || 0;
  103942. return tilesetJson;
  103943. }
  103944. async function parse$4(data, options, context) {
  103945. const loaderOptions = options['3d-tiles'] || {};
  103946. let isTileset;
  103947. if (loaderOptions.isTileset === 'auto') {
  103948. isTileset = context.url && context.url.indexOf('.json') !== -1;
  103949. } else {
  103950. isTileset = loaderOptions.isTileset;
  103951. }
  103952. if (isTileset) {
  103953. data = await parseTileset(data, options, context);
  103954. } else {
  103955. data = await parseTile(data, options, context);
  103956. }
  103957. return data;
  103958. }
  103959. function hasImplicitTilingExtension(tilesetJson) {
  103960. var _tilesetJson$extensio, _tilesetJson$extensio2;
  103961. 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));
  103962. }
  103963. const CESIUM_ION_URL = 'https://api.cesium.com/v1/assets';
  103964. async function getIonTilesetMetadata(accessToken, assetId) {
  103965. if (!assetId) {
  103966. const assets = await getIonAssets(accessToken);
  103967. for (const item of assets.items) {
  103968. if (item.type === '3DTILES') {
  103969. assetId = item.id;
  103970. }
  103971. }
  103972. }
  103973. const ionAssetMetadata = await getIonAssetMetadata(accessToken, assetId);
  103974. const {
  103975. type,
  103976. url
  103977. } = ionAssetMetadata;
  103978. assert$7(type === '3DTILES' && url);
  103979. ionAssetMetadata.headers = {
  103980. Authorization: "Bearer ".concat(ionAssetMetadata.accessToken)
  103981. };
  103982. return ionAssetMetadata;
  103983. }
  103984. async function getIonAssets(accessToken) {
  103985. assert$7(accessToken);
  103986. const url = CESIUM_ION_URL;
  103987. const headers = {
  103988. Authorization: "Bearer ".concat(accessToken)
  103989. };
  103990. const response = await fetchFile(url, {
  103991. fetch: {
  103992. headers
  103993. }
  103994. });
  103995. if (!response.ok) {
  103996. throw new Error(response.statusText);
  103997. }
  103998. return await response.json();
  103999. }
  104000. async function getIonAssetMetadata(accessToken, assetId) {
  104001. assert$7(accessToken, assetId);
  104002. const headers = {
  104003. Authorization: "Bearer ".concat(accessToken)
  104004. };
  104005. const url = "".concat(CESIUM_ION_URL, "/").concat(assetId);
  104006. let response = await fetchFile("".concat(url), {
  104007. fetch: {
  104008. headers
  104009. }
  104010. });
  104011. if (!response.ok) {
  104012. throw new Error(response.statusText);
  104013. }
  104014. let metadata = await response.json();
  104015. response = await fetchFile("".concat(url, "/endpoint"), {
  104016. fetch: {
  104017. headers
  104018. }
  104019. });
  104020. if (!response.ok) {
  104021. throw new Error(response.statusText);
  104022. }
  104023. const tilesetInfo = await response.json();
  104024. metadata = { ...metadata,
  104025. ...tilesetInfo
  104026. };
  104027. return metadata;
  104028. }
  104029. async function preload(url, options = {}) {
  104030. options = options['cesium-ion'] || {};
  104031. const {
  104032. accessToken
  104033. } = options;
  104034. let assetId = options.assetId;
  104035. if (!Number.isFinite(assetId)) {
  104036. const matched = url.match(/\/([0-9]+)\/tileset.json/);
  104037. assetId = matched && matched[1];
  104038. }
  104039. return getIonTilesetMetadata(accessToken, assetId);
  104040. }
  104041. const CesiumIonLoader = { ...Tiles3DLoader,
  104042. id: 'cesium-ion',
  104043. name: 'Cesium Ion',
  104044. preload,
  104045. parse: async (data, options, context) => {
  104046. options = { ...options
  104047. };
  104048. options['3d-tiles'] = options['cesium-ion'];
  104049. options.loader = CesiumIonLoader;
  104050. return Tiles3DLoader.parse(data, options, context);
  104051. },
  104052. options: {
  104053. 'cesium-ion': { ...Tiles3DLoader.options['3d-tiles'],
  104054. accessToken: null
  104055. }
  104056. }
  104057. };
  104058. // From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  104059. function generateGradientTexture(gradient) {
  104060. const size = 64;
  104061. // create canvas
  104062. const canvas = document.createElement('canvas');
  104063. canvas.width = size;
  104064. canvas.height = size;
  104065. // get context
  104066. const context = canvas.getContext('2d');
  104067. // draw gradient
  104068. context.rect(0, 0, size, size);
  104069. const ctxGradient = context.createLinearGradient(0, 0, size, size);
  104070. for (let i = 0; i < gradient.length; i++) {
  104071. const step = gradient[i];
  104072. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  104073. }
  104074. context.fillStyle = ctxGradient;
  104075. context.fill();
  104076. //let texture = new THREE.Texture(canvas);
  104077. const texture = new CanvasTexture(canvas);
  104078. texture.needsUpdate = true;
  104079. texture.minFilter = LinearFilter;
  104080. texture.wrapS = RepeatWrapping;
  104081. texture.wrapT = RepeatWrapping;
  104082. texture.repeat.set(2, 2);
  104083. // textureImage = texture.image;
  104084. return texture;
  104085. }
  104086. function getCameraFrustum(camera) {
  104087. camera.updateMatrix(); // make sure camera's local matrix is updated
  104088. camera.updateMatrixWorld(); // make sure camera's world matrix is updated
  104089. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  104090. const frustum = new Frustum();
  104091. frustum.setFromProjectionMatrix(new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
  104092. return frustum;
  104093. }
  104094. function loadersPlaneToMesh(plane) {
  104095. const group = new Group();
  104096. // Create a basic rectangle geometry from math.gl plane
  104097. const planeGeometry = new PlaneGeometry(10, 5);
  104098. // Align the geometry to the plane
  104099. const coplanarPoint = new Vector3(...plane.projectPointOntoPlane([0, 0, 0]));
  104100. const normal = new Vector3(plane.normal.x, plane.normal.y, plane.normal.z);
  104101. const focalPoint = new Vector3().copy(coplanarPoint).add(normal);
  104102. planeGeometry.lookAt(focalPoint);
  104103. planeGeometry.translate(coplanarPoint.x, coplanarPoint.y, coplanarPoint.z);
  104104. // Edges
  104105. /*
  104106. const edges = new EdgesGeometry(planeGeometry)
  104107. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/
  104108. //plane
  104109. const material = new BasicMaterial({ color: 0x00ffff, side: DoubleSide });
  104110. const mesh = new Mesh(planeGeometry, material);
  104111. const arrowHelper = new ArrowHelper(normal, coplanarPoint, 5, 0xffff00);
  104112. group.add(arrowHelper);
  104113. group.add(mesh);
  104114. return group;
  104115. }
  104116. function loadersBoundingBoxToMesh(tile) {
  104117. // Create a basic rectangle geometry from math.gl half-axes
  104118. const { boundingVolume } = tile;
  104119. let redColor = 0;
  104120. if (tile.content) {
  104121. //redColor = Math.min((tile.content.byteLength != void 0 ? tile.content.byteLength : 0) / 500000, 1.0);
  104122. redColor = Math.min( tile.depth / 10 , 1.0); //改
  104123. }
  104124. const boxColor = new Color(redColor, 1.0, 0.0);
  104125. const boxGeometry = new BoxGeometry(1, 1, 1);
  104126. const boxTransform = new Matrix4();
  104127. if (boundingVolume.halfAxes) {
  104128. boxTransform.copy(getMatrix4FromHalfAxes(boundingVolume.halfAxes));
  104129. }
  104130. else if (boundingVolume.radius) {
  104131. boxGeometry.scale(boundingVolume.radius * 2, boundingVolume.radius * 2, boundingVolume.radius * 2);
  104132. }
  104133. boxTransform.premultiply((new Matrix4()).setPosition(...boundingVolume.center)); //add
  104134. boxGeometry.applyMatrix4(boxTransform);
  104135. const edges = new EdgesGeometry(boxGeometry);
  104136. const dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: boxColor, transparent:true }));
  104137. //dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  104138. dispPlane.matrixAutoUpdate = false; //add
  104139. /* if(tile.content.byteLength == void 0){
  104140. let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane)
  104141. dispPlane.updateMatrixWorld = (a,b)=>{
  104142. oldUpdate(a,b)
  104143. }
  104144. let oldU = dispPlane.updateMatrix.bind(dispPlane)
  104145. dispPlane.updateMatrix = (a,b)=>{
  104146. oldU(a,b)
  104147. }
  104148. } */
  104149. return dispPlane;
  104150. }
  104151. function getMatrix4FromHalfAxes(halfAxes) {
  104152. const m = halfAxes;
  104153. const rotateMatrix = new Matrix4().fromArray([
  104154. m[0] * 2,
  104155. m[1] * 2,
  104156. m[2] * 2,
  104157. 0,
  104158. m[3] * 2,
  104159. m[4] * 2,
  104160. m[5] * 2,
  104161. 0,
  104162. m[6] * 2,
  104163. m[7] * 2,
  104164. m[8] * 2,
  104165. 0,
  104166. 0,
  104167. 0,
  104168. 0,
  104169. 1,
  104170. ]);
  104171. return rotateMatrix;
  104172. }
  104173. /*
  104174. * from https://github.com/tentone/geo-three
  104175. * Tree-shaking did not work, probably due to static class methods
  104176. */
  104177. function datumsToSpherical(latitude, longitude) {
  104178. const EARTH_RADIUS = 6378137;
  104179. const EARTH_PERIMETER = 2 * Math.PI * EARTH_RADIUS;
  104180. const EARTH_ORIGIN = EARTH_PERIMETER / 2.0;
  104181. const x = longitude * EARTH_ORIGIN / 180.0;
  104182. let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360.0)) / (Math.PI / 180.0);
  104183. y = y * EARTH_ORIGIN / 180.0;
  104184. return new Vector2(x, y);
  104185. }
  104186. const Gradients$1 = {
  104187. // From chroma spectral http://gka.github.io/chroma.js/
  104188. SPECTRAL: [
  104189. [0, new Color(0.3686, 0.3098, 0.6353)],
  104190. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  104191. [0.2, new Color(0.4, 0.7608, 0.6471)],
  104192. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  104193. [0.4, new Color(0.902, 0.9608, 0.5961)],
  104194. [0.5, new Color(1.0, 1.0, 0.749)],
  104195. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  104196. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  104197. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  104198. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  104199. [1, new Color(0.6196, 0.0039, 0.2588)],
  104200. ],
  104201. PLASMA: [
  104202. [0.0, new Color(0.241, 0.015, 0.61)],
  104203. [0.1, new Color(0.387, 0.001, 0.654)],
  104204. [0.2, new Color(0.524, 0.025, 0.653)],
  104205. [0.3, new Color(0.651, 0.125, 0.596)],
  104206. [0.4, new Color(0.752, 0.227, 0.513)],
  104207. [0.5, new Color(0.837, 0.329, 0.431)],
  104208. [0.6, new Color(0.907, 0.435, 0.353)],
  104209. [0.7, new Color(0.963, 0.554, 0.272)],
  104210. [0.8, new Color(0.992, 0.681, 0.195)],
  104211. [0.9, new Color(0.987, 0.822, 0.144)],
  104212. [1.0, new Color(0.94, 0.975, 0.131)],
  104213. ],
  104214. YELLOW_GREEN: [
  104215. [0, new Color(0.1647, 0.2824, 0.3451)],
  104216. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  104217. [0.2, new Color(0.061, 0.4319, 0.4864)],
  104218. [0.3, new Color(0.0, 0.5099, 0.5319)],
  104219. [0.4, new Color(0.0, 0.5881, 0.5569)],
  104220. [0.5, new Color(0.137, 0.665, 0.5614)],
  104221. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  104222. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  104223. [0.8, new Color(0.6102, 0.8748, 0.485)],
  104224. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  104225. [1, new Color(0.9804, 0.9804, 0.4314)],
  104226. ],
  104227. VIRIDIS: [
  104228. [0.0, new Color(0.267, 0.005, 0.329)],
  104229. [0.1, new Color(0.283, 0.141, 0.458)],
  104230. [0.2, new Color(0.254, 0.265, 0.53)],
  104231. [0.3, new Color(0.207, 0.372, 0.553)],
  104232. [0.4, new Color(0.164, 0.471, 0.558)],
  104233. [0.5, new Color(0.128, 0.567, 0.551)],
  104234. [0.6, new Color(0.135, 0.659, 0.518)],
  104235. [0.7, new Color(0.267, 0.749, 0.441)],
  104236. [0.8, new Color(0.478, 0.821, 0.318)],
  104237. [0.9, new Color(0.741, 0.873, 0.15)],
  104238. [1.0, new Color(0.993, 0.906, 0.144)],
  104239. ],
  104240. INFERNO: [
  104241. [0.0, new Color(0.077, 0.042, 0.206)],
  104242. [0.1, new Color(0.225, 0.036, 0.388)],
  104243. [0.2, new Color(0.373, 0.074, 0.432)],
  104244. [0.3, new Color(0.522, 0.128, 0.42)],
  104245. [0.4, new Color(0.665, 0.182, 0.37)],
  104246. [0.5, new Color(0.797, 0.255, 0.287)],
  104247. [0.6, new Color(0.902, 0.364, 0.184)],
  104248. [0.7, new Color(0.969, 0.516, 0.063)],
  104249. [0.8, new Color(0.988, 0.683, 0.072)],
  104250. [0.9, new Color(0.961, 0.859, 0.298)],
  104251. [1.0, new Color(0.988, 0.998, 0.645)],
  104252. ],
  104253. GRAYSCALE: [
  104254. [0, new Color(0, 0, 0)],
  104255. [1, new Color(1, 1, 1)],
  104256. ],
  104257. // 16 samples of the TURBU color scheme
  104258. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  104259. // original file licensed under Apache-2.0
  104260. TURBO: [
  104261. [0.0, new Color(0.18995, 0.07176, 0.23217)],
  104262. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  104263. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  104264. [0.2, new Color(0.25862, 0.57958, 0.99876)],
  104265. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  104266. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  104267. [0.4, new Color(0.19659, 0.94901, 0.59466)],
  104268. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  104269. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  104270. [0.6, new Color(0.80473, 0.92452, 0.20459)],
  104271. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  104272. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  104273. [0.8, new Color(0.9836, 0.49291, 0.12849)],
  104274. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  104275. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  104276. [1.0, new Color(0.66449, 0.08436, 0.00424)],
  104277. ],
  104278. RAINBOW: [
  104279. [0, new Color(0.278, 0, 0.714)],
  104280. [1 / 6, new Color(0, 0, 1)],
  104281. [2 / 6, new Color(0, 1, 1)],
  104282. [3 / 6, new Color(0, 1, 0)],
  104283. [4 / 6, new Color(1, 1, 0)],
  104284. [5 / 6, new Color(1, 0.64, 0)],
  104285. [1, new Color(1, 0, 0)],
  104286. ],
  104287. CONTOUR: [
  104288. [0.0, new Color(0, 0, 0)],
  104289. [0.03, new Color(0, 0, 0)],
  104290. [0.04, new Color(1, 1, 1)],
  104291. [1.0, new Color(1, 1, 1)],
  104292. ],
  104293. };
  104294. const PointCloudFS = `
  104295. varying vec3 vColor;
  104296. uniform float alpha;
  104297. void main() {
  104298. if (vColor == vec3(0.0, 0.0, 0.0)) {
  104299. discard;
  104300. } else {
  104301. gl_FragColor = vec4( vColor, alpha);
  104302. }
  104303. }
  104304. `;
  104305. const PointCloudVS = `
  104306. varying vec3 vColor;
  104307. uniform sampler2D gradient;
  104308. uniform sampler2D grayscale;
  104309. attribute float intensity;
  104310. attribute float classification;
  104311. uniform vec3 rootCenter;
  104312. uniform vec3 rootNormal;
  104313. uniform vec2 elevationRange;
  104314. uniform int coloring;
  104315. uniform bool hideGround;
  104316. uniform float maxIntensity;
  104317. uniform float intensityContrast;
  104318. uniform float pointSize;
  104319. #ifdef USE_COLOR
  104320. vec3 getRGB() {
  104321. vec3 rgb = color;
  104322. return rgb;
  104323. }
  104324. #endif
  104325. vec3 getElevation(){
  104326. vec4 world = modelMatrix * vec4( position, 1.0 );
  104327. float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));
  104328. float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);
  104329. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  104330. return cElevation;
  104331. }
  104332. vec3 getIntensity(){
  104333. // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs
  104334. float intmod = pow(intensity, intensityContrast);
  104335. vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;
  104336. return cIntensity;
  104337. }
  104338. vec3 getClassification(){
  104339. float classNormalized = classification / 255.0;
  104340. vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;
  104341. return cClassification;
  104342. }
  104343. vec3 getColor(){
  104344. vec3 color;
  104345. if (hideGround && classification == 2.0) {
  104346. return vec3(0.0, 0.0, 0.0);
  104347. }
  104348. if (coloring == 1) {
  104349. color = getIntensity();
  104350. }
  104351. else if (coloring == 2) {
  104352. color = getClassification();
  104353. } else if (coloring == 3) {
  104354. color = getElevation();
  104355. }
  104356. #ifdef USE_COLOR
  104357. else if (coloring == 4) {
  104358. color = getRGB();
  104359. }
  104360. #endif
  104361. else {
  104362. color = vec3(1.0, 1.0, 1.0);
  104363. }
  104364. return color;
  104365. }
  104366. void main() {
  104367. vColor = getColor();
  104368. gl_PointSize = pointSize;
  104369. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  104370. }
  104371. `;
  104372. /** Types of coloring used when viewing point cloud tiles */
  104373. var PointCloudColoring;
  104374. (function (PointCloudColoring) {
  104375. PointCloudColoring[PointCloudColoring["Intensity"] = 1] = "Intensity";
  104376. PointCloudColoring[PointCloudColoring["Classification"] = 2] = "Classification";
  104377. PointCloudColoring[PointCloudColoring["Elevation"] = 3] = "Elevation";
  104378. PointCloudColoring[PointCloudColoring["RGB"] = 4] = "RGB";
  104379. PointCloudColoring[PointCloudColoring["White"] = 5] = "White";
  104380. })(PointCloudColoring || (PointCloudColoring = {}));
  104381. /** Types of shading used when viewing b3dm (mesh) tiles */
  104382. var Shading;
  104383. (function (Shading) {
  104384. Shading[Shading["FlatTexture"] = 1] = "FlatTexture";
  104385. Shading[Shading["ShadedTexture"] = 2] = "ShadedTexture";
  104386. Shading[Shading["ShadedNoTexture"] = 3] = "ShadedNoTexture";
  104387. })(Shading || (Shading = {}));
  104388. var GeoTransform;
  104389. (function (GeoTransform) {
  104390. GeoTransform[GeoTransform["Reset"] = 1] = "Reset";
  104391. GeoTransform[GeoTransform["Mercator"] = 2] = "Mercator";
  104392. GeoTransform[GeoTransform["WGS84Cartesian"] = 3] = "WGS84Cartesian";
  104393. })(GeoTransform || (GeoTransform = {}));
  104394. const gradient = Gradients$1.RAINBOW;
  104395. const gradientTexture = typeof document != 'undefined' ? generateGradientTexture(gradient) : null;
  104396. const grayscale = Gradients$1.GRAYSCALE;
  104397. const grayscaleTexture = typeof document != 'undefined' ? generateGradientTexture(grayscale) : null;
  104398. const defaultOptions = {
  104399. throttleRequests: true,
  104400. maxRequests: 64,
  104401. updateInterval: 0.1,
  104402. maxConcurrency: 1,
  104403. maximumScreenSpaceError: 16,
  104404. maximumMemoryUsage: 32,
  104405. viewDistanceScale: 1.0,
  104406. skipLevelOfDetail: false,
  104407. updateTransforms: true,
  104408. shading: Shading.FlatTexture,
  104409. transparent: false,
  104410. pointCloudColoring: PointCloudColoring.White,
  104411. pointSize: 1.0,
  104412. worker: true,
  104413. wireframe: false,
  104414. debug: false,
  104415. basisTranscoderPath: null,
  104416. dracoDecoderPath: null,
  104417. material: null,
  104418. computeNormals: false,
  104419. shaderCallback: null,
  104420. geoTransform: GeoTransform.Reset,
  104421. preloadTilesCount: null
  104422. };
  104423. /** 3D Tiles Loader */
  104424. class Loader3DTiles {
  104425. /**
  104426. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  104427. * @public
  104428. *
  104429. * @param props - Properties for this load call {@link LoaderProps}.
  104430. * @returns An object containing the 3D Model to be added to the scene
  104431. * and a runtime engine to be updated every frame.
  104432. */
  104433. static load(props) {
  104434. return __awaiter(this, void 0, void 0, function* () {
  104435. const options = Object.assign(Object.assign({}, defaultOptions), props.options);
  104436. const { url } = props;
  104437. const UPDATE_INTERVAL = options.updateInterval;
  104438. const MAX_DEPTH_FOR_ORIENTATION = 5;
  104439. const loadersGLOptions = {};
  104440. if (options.cesiumIONToken) {
  104441. loadersGLOptions['cesium-ion'] = {
  104442. accessToken: options.cesiumIONToken,
  104443. };
  104444. const metadata = yield CesiumIonLoader.preload(url, loadersGLOptions);
  104445. loadersGLOptions['fetch'] = { headers: metadata.headers };
  104446. }
  104447. if (props.loadingManager) {
  104448. props.loadingManager.itemStart(url);
  104449. }
  104450. const tilesetJson = yield load(url, Tiles3DLoader, Object.assign({}, loadersGLOptions));
  104451. const renderMap = {};
  104452. const boxMap = {};
  104453. const unloadQueue = [];
  104454. const root = new Group();
  104455. const tileBoxes = new Group();
  104456. tileBoxes.matrixAutoUpdate = false;//add
  104457. if (!options.debug) {
  104458. tileBoxes.visible = false;
  104459. }else {
  104460. options.parent.add(tileBoxes); //add
  104461. }
  104462. const pointcloudUniforms = {
  104463. pointSize: { type: 'f', value: options.pointSize },
  104464. gradient: { type: 't', value: gradientTexture },
  104465. grayscale: { type: 't', value: grayscaleTexture },
  104466. rootCenter: { type: 'vec3', value: new Vector3() },
  104467. rootNormal: { type: 'vec3', value: new Vector3() },
  104468. coloring: { type: 'i', value: options.pointCloudColoring },
  104469. hideGround: { type: 'b', value: true },
  104470. elevationRange: { type: 'vec2', value: new Vector2(0, 400) },
  104471. maxIntensity: { type: 'f', value: 1.0 },
  104472. intensityContrast: { type: 'f', value: 1.0 },
  104473. alpha: { type: 'f', value: 1.0 },
  104474. };
  104475. const pointcloudMaterial = new ShaderMaterial({
  104476. uniforms: pointcloudUniforms,
  104477. vertexShader: PointCloudVS,
  104478. fragmentShader: PointCloudFS,
  104479. transparent: options.transparent,
  104480. vertexColors: true
  104481. });
  104482. let cameraReference = null;
  104483. let rendererReference = null;
  104484. const gltfLoader = props.gltfLoader || new GLTFLoader(); //xzw改
  104485. let ktx2Loader = undefined;
  104486. let dracoLoader = undefined;
  104487. if (options.basisTranscoderPath) {
  104488. ktx2Loader = new KTX2Loader();
  104489. ktx2Loader.detectSupport(props.renderer);
  104490. ktx2Loader.setTranscoderPath(options.basisTranscoderPath + '/');
  104491. ktx2Loader.setWorkerLimit(1);
  104492. gltfLoader.setKTX2Loader(ktx2Loader);
  104493. }
  104494. if (options.dracoDecoderPath) {
  104495. dracoLoader = new DRACOLoader();
  104496. dracoLoader.setDecoderPath(options.dracoDecoderPath + '/');
  104497. dracoLoader.setWorkerLimit(options.maxConcurrency);
  104498. gltfLoader.setDRACOLoader(dracoLoader);
  104499. }
  104500. const unlitMaterial = new BasicMaterial({ transparent: options.transparent });
  104501. const tileOptions = {
  104502. maximumMemoryUsage: options.maximumMemoryUsage,
  104503. maximumScreenSpaceError: options.maximumScreenSpaceError,
  104504. viewDistanceScale: options.viewDistanceScale,
  104505. skipLevelOfDetail: options.skipLevelOfDetail,
  104506. updateTransforms: options.updateTransforms,
  104507. throttleRequests: options.throttleRequests,
  104508. maxRequests: options.maxRequests,
  104509. maxDepth: options.maxDepth || 50, // !zeg改
  104510. contentLoader: (tile) => __awaiter(this, void 0, void 0, function* () {
  104511. let tileContent = null;
  104512. switch (tile.type) {
  104513. case TILE_TYPE.POINTCLOUD: {
  104514. tileContent = createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse);
  104515. break;
  104516. }
  104517. case TILE_TYPE.SCENEGRAPH:
  104518. case TILE_TYPE.MESH: {
  104519. tileContent = yield createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse);
  104520. break;
  104521. }
  104522. }
  104523. if (tileContent) {
  104524. tileContent.visible = false;
  104525. renderMap[tile.id] = tileContent;
  104526. root.add(renderMap[tile.id]);
  104527. if (options.debug) {
  104528. const box = loadersBoundingBoxToMesh(tile);
  104529. tileBoxes.add(box);
  104530. boxMap[tile.id] = box;
  104531. }
  104532. //xzw :
  104533. tileset.dispatchEvent({type:'tileLoaded',tileContent}); //每一个tile加载完要更改透明度等
  104534. }
  104535. }),
  104536. onTileLoad: (tile) => __awaiter(this, void 0, void 0, function* () {
  104537. if (tileset) {
  104538. if (!orientationDetected && (tile === null || tile === void 0 ? void 0 : tile.depth) <= MAX_DEPTH_FOR_ORIENTATION) {
  104539. detectOrientation(tile);
  104540. }
  104541. tileset._frameNumber++;
  104542. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  104543. }
  104544. }),
  104545. onTileUnload: (tile) => {
  104546. unloadQueue.push(tile);
  104547. },
  104548. onTileError: (tile, message) => {
  104549. console.error('Tile error', tile.id, message);
  104550. },
  104551. };
  104552. const tileset = new Tileset3D(tilesetJson, Object.assign(Object.assign({}, tileOptions), { loadOptions: Object.assign(Object.assign({}, loadersGLOptions), { maxConcurrency: options.maxConcurrency, worker: options.worker, gltf: {
  104553. loadImages: false,
  104554. }, '3d-tiles': {
  104555. loadGLTF: false
  104556. } }) }));
  104557. //
  104558. // transformations
  104559. const threeMat = new Matrix4();
  104560. const tileTrasnform = new Matrix4();
  104561. const rootCenter = new Vector3();
  104562. let orientationDetected = false;
  104563. if (tileset.root.boundingVolume) {
  104564. if (tileset.root.header.boundingVolume.region) {
  104565. // TODO: Handle region type bounding volumes
  104566. // https://github.com/visgl/loaders.gl/issues/1994
  104567. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");
  104568. options.geoTransform = GeoTransform.WGS84Cartesian;
  104569. }
  104570. tileTrasnform.setPosition(tileset.root.boundingVolume.center[0], tileset.root.boundingVolume.center[1], tileset.root.boundingVolume.center[2]);
  104571. }
  104572. else {
  104573. console.warn("Bounding volume not found, no transformations applied");
  104574. }
  104575. if (options.debug) {
  104576. const box = loadersBoundingBoxToMesh(tileset.root);
  104577. tileBoxes.add(box);
  104578. boxMap[tileset.root.id] = box;
  104579. }
  104580. let disposeFlag = false;
  104581. let loadingEnded = false;
  104582. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  104583. pointcloudUniforms.rootNormal.value.copy(new Vector3(0, 0, 1).normalize());
  104584. // Extra stats
  104585. tileset.stats.get('Loader concurrency').count = options.maxConcurrency;
  104586. tileset.stats.get('Maximum SSE').count = options.maximumScreenSpaceError;
  104587. tileset.stats.get('Maximum mem usage').count = options.maximumMemoryUsage;
  104588. let timer = 0;
  104589. let lastCameraTransform = null;
  104590. let lastCameraAspect = null;
  104591. const lastCameraPosition = new Vector3(Infinity, Infinity, Infinity);
  104592. let sseDenominator = null;
  104593. root.updateMatrixWorld(true);
  104594. const lastRootTransform = new Matrix4().copy(root.matrixWorld);
  104595. const rootTransformInverse = new Matrix4().copy(lastRootTransform).invert();
  104596. detectOrientation(tileset.root);
  104597. updateResetTransform();
  104598. if (options.debug) {
  104599. boxMap[tileset.root.id].applyMatrix4(threeMat);
  104600. tileBoxes.matrixWorld.copy(root.matrixWorld);
  104601. }
  104602. if (options.geoTransform == GeoTransform.Mercator) {
  104603. const coords = datumsToSpherical(tileset.cartographicCenter[1], tileset.cartographicCenter[0]);
  104604. rootCenter.set(coords.x, 0, -coords.y);
  104605. root.position.copy(rootCenter);
  104606. root.rotation.set(-Math.PI / 2, 0, 0);
  104607. root.updateMatrixWorld(true);
  104608. }
  104609. else if (options.geoTransform == GeoTransform.WGS84Cartesian) {
  104610. root.applyMatrix4(tileTrasnform);
  104611. root.updateMatrixWorld(true);
  104612. rootCenter.copy(root.position);
  104613. }
  104614. function detectOrientation(tile) {
  104615. if (!tile.boundingVolume.halfAxes) {
  104616. return;
  104617. }
  104618. const halfAxes = tile.boundingVolume.halfAxes;
  104619. const orientationMatrix = new Matrix4()
  104620. .extractRotation(getMatrix4FromHalfAxes(halfAxes))
  104621. .premultiply(new Matrix4().extractRotation(rootTransformInverse));
  104622. const rotation = new Euler().setFromRotationMatrix(orientationMatrix);
  104623. if (!rotation.equals(new Euler())) {
  104624. orientationDetected = true;
  104625. const pos = new Vector3(tileTrasnform.elements[12], tileTrasnform.elements[13], tileTrasnform.elements[14]);
  104626. tileTrasnform.extractRotation(orientationMatrix);
  104627. tileTrasnform.setPosition(pos);
  104628. updateResetTransform();
  104629. }
  104630. }
  104631. function updateResetTransform() {
  104632. if (options.geoTransform != GeoTransform.WGS84Cartesian) {
  104633. // Reset the current model matrix and apply our own transformation
  104634. threeMat.copy(tileTrasnform).invert();
  104635. threeMat.premultiply(lastRootTransform);
  104636. threeMat.copy(lastRootTransform).multiply(new Matrix4().copy(tileTrasnform).invert());
  104637. tileset.modelMatrix = new Matrix4$1(threeMat.toArray());
  104638. //console.log('update tileset ModelMatrix', tileset.modelMatrix.elements)
  104639. }
  104640. }
  104641. // 更新瓦片显隐和瓦片迭代更新
  104642. function tilesetUpdate(tileset, renderMap, renderer, camera) {
  104643. if (disposeFlag || options.pauseTilesetUpdate) {// !zeg改 pauseTilesetUpdate
  104644. return
  104645. }
  104646. // Assumes camera fov, near and far are not changing
  104647. if (!sseDenominator || camera.aspect != lastCameraAspect) {
  104648. const loadersFrustum = new PerspectiveFrustum({
  104649. fov: (camera.fov / 180) * Math.PI,
  104650. aspectRatio: camera.aspect,
  104651. near: camera.near,
  104652. far: camera.far,
  104653. });
  104654. sseDenominator = loadersFrustum.sseDenominator;
  104655. lastCameraAspect = camera.aspect;
  104656. if(camera.aspect == 0)return//add
  104657. if (options.debug) {
  104658. console.log('Updated sse denonimator:', sseDenominator);
  104659. }
  104660. }
  104661. const frustum = getCameraFrustum(camera);
  104662. const planes = frustum.planes.map((plane) => new Plane$1(plane.normal.toArray(), plane.constant));
  104663. const cullingVolume = new CullingVolume(planes);
  104664. const rendererSize = new Vector2();
  104665. renderer.getSize(rendererSize);
  104666. const frameState = {
  104667. camera: {
  104668. position: lastCameraPosition.toArray(),
  104669. },
  104670. height: rendererSize.y,
  104671. frameNumber: tileset._frameNumber,
  104672. sseDenominator: sseDenominator,
  104673. cullingVolume: cullingVolume,
  104674. viewport: {
  104675. id: 0,
  104676. },
  104677. };
  104678. tileset._cache.reset();
  104679. tileset._traverser.traverse(tileset.root, frameState, tileset.options);
  104680. for (const tile of tileset.tiles) {
  104681. if (tile.selected) {
  104682. if (!renderMap[tile.id]) {
  104683. console.error('TILE SELECTED BUT NOT LOADED!!', tile.id);
  104684. }
  104685. else {
  104686. // Make sure it's visible
  104687. if(!renderMap[tile.id].visible){
  104688. if(visiVertexCount<maxVertexVisi){
  104689. renderMap[tile.id].visible = true;
  104690. visiVertexCount += renderMap[tile.id].vertexCount; //xzw add
  104691. options.debug && (boxMap[tile.id].material.opacity = 1);
  104692. }else {
  104693. //console.log('超出', visiVertexCount)
  104694. }
  104695. }
  104696. /* if(!renderMap[tile.id].realVisible()){
  104697. console.error('!realVisible')
  104698. } */
  104699. }
  104700. }
  104701. else {
  104702. if (renderMap[tile.id]) {
  104703. if(renderMap[tile.id].visible){
  104704. renderMap[tile.id].visible = false;
  104705. options.debug && (boxMap[tile.id].material.opacity = 0.1);
  104706. visiVertexCount -= renderMap[tile.id].vertexCount; //xzw add
  104707. }
  104708. }
  104709. }
  104710. }
  104711. while (unloadQueue.length > 0) {
  104712. const tile = unloadQueue.pop();
  104713. if (renderMap[tile.id] && tile.contentState == TILE_CONTENT_STATE.UNLOADED) {
  104714. //console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减
  104715. root.remove(renderMap[tile.id]);
  104716. disposeNode(renderMap[tile.id]);
  104717. delete renderMap[tile.id];
  104718. }
  104719. if (boxMap[tile.id]) {
  104720. disposeNode(boxMap[tile.id]);
  104721. tileBoxes.remove(boxMap[tile.id]);
  104722. delete boxMap[tile.id];
  104723. }
  104724. }
  104725. const tilesLoaded = tileset.stats.get('Tiles Loaded').count;
  104726. const tilesLoading = tileset.stats.get('Tiles Loading').count;
  104727. if (props.onProgress) {
  104728. props.onProgress(tilesLoaded, tilesLoaded + tilesLoading);
  104729. }
  104730. if (props.loadingManager && !loadingEnded) {
  104731. if (tilesLoading == 0 &&
  104732. (options.preloadTilesCount == null ||
  104733. tilesLoaded >= options.preloadTilesCount)) {
  104734. loadingEnded = true;
  104735. props.loadingManager.itemEnd(props.url);
  104736. }
  104737. }
  104738. return frameState;
  104739. }
  104740. return {
  104741. model: root,
  104742. runtime: {
  104743. getTileset: () => {
  104744. return tileset;
  104745. },
  104746. getStats: () => {
  104747. return tileset.stats;
  104748. },
  104749. showTiles: (visible) => {
  104750. tileBoxes.visible = visible;
  104751. },
  104752. setWireframe: (wireframe) => {
  104753. options.wireframe = wireframe;
  104754. root.traverse((object) => {
  104755. if (object instanceof Mesh) {
  104756. object.material.wireframe = wireframe;
  104757. }
  104758. });
  104759. },
  104760. setDebug: (debug) => {
  104761. options.debug = debug;
  104762. tileBoxes.visible = debug;
  104763. },
  104764. setShading: (shading) => {
  104765. options.shading = shading;
  104766. },
  104767. getTileBoxes: () => {
  104768. return tileBoxes;
  104769. },
  104770. setViewDistanceScale: (scale) => {
  104771. tileset.options.viewDistanceScale = scale;
  104772. tileset._frameNumber++;
  104773. tilesetUpdate(tileset, renderMap, rendererReference, cameraReference);
  104774. },
  104775. setHideGround: (enabled) => {
  104776. pointcloudUniforms.hideGround.value = enabled;
  104777. },
  104778. setPointCloudColoring: (selection) => {
  104779. pointcloudUniforms.coloring.value = selection;
  104780. },
  104781. setElevationRange: (range) => {
  104782. pointcloudUniforms.elevationRange.value.set(range[0], range[1]);
  104783. },
  104784. setMaxIntensity: (intensity) => {
  104785. pointcloudUniforms.maxIntensity.value = intensity;
  104786. },
  104787. setIntensityContrast: (contrast) => {
  104788. pointcloudUniforms.intensityContrast.value = contrast;
  104789. },
  104790. setPointAlpha: (alpha) => {
  104791. pointcloudUniforms.alpha.value = alpha;
  104792. },
  104793. getLatLongHeightFromPosition: (position) => {
  104794. const cartographicPosition = tileset.ellipsoid.cartesianToCartographic(new Vector3().copy(position).applyMatrix4(new Matrix4().copy(threeMat).invert()).toArray());
  104795. return {
  104796. lat: cartographicPosition[1],
  104797. long: cartographicPosition[0],
  104798. height: cartographicPosition[2],
  104799. };
  104800. },
  104801. getPositionFromLatLongHeight: (coord) => {
  104802. const cartesianPosition = tileset.ellipsoid.cartographicToCartesian([coord.long, coord.lat, coord.height]);
  104803. return new Vector3(...cartesianPosition).applyMatrix4(threeMat);
  104804. },
  104805. getCameraFrustum: (camera) => {
  104806. const frustum = getCameraFrustum(camera);
  104807. const meshes = frustum.planes
  104808. .map((plane) => new Plane$1(plane.normal.toArray(), plane.constant))
  104809. .map((loadersPlane) => loadersPlaneToMesh(loadersPlane));
  104810. const model = new Group();
  104811. for (const mesh of meshes)
  104812. model.add(mesh);
  104813. return model;
  104814. },
  104815. update: function (dt, renderer, camera, ifForce) {
  104816. cameraReference = camera;
  104817. rendererReference = renderer;
  104818. timer += dt;
  104819. if(!ifForce) ifForce = tileset.nextForceUpdate;
  104820. tileset.nextForceUpdate = false;
  104821. if(tileset.needRenderNext){//必须在下一帧渲染刷新否则无法显示
  104822. viewer.dispatchEvent('content_changed');
  104823. }
  104824. tileset.needRenderNext = ifForce;
  104825. if (tileset && (timer >= UPDATE_INTERVAL || ifForce)) {
  104826. if (!lastRootTransform.equals(root.matrixWorld)) {
  104827. timer = 0;
  104828. lastRootTransform.copy(root.matrixWorld);
  104829. updateResetTransform();
  104830. const rootCenter = new Vector3().setFromMatrixPosition(lastRootTransform);
  104831. pointcloudUniforms.rootCenter.value.copy(rootCenter);
  104832. pointcloudUniforms.rootNormal.value.copy(new Vector3(0, 0, 1).applyMatrix4(lastRootTransform).normalize());
  104833. rootTransformInverse.copy(lastRootTransform).invert();
  104834. if (options.debug) {
  104835. /* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements)
  104836. boxMap[tileset.root.id].matrix.copy(root.matrixWorld);
  104837. boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */
  104838. //boxMap[tileset.root.id].applyMatrix4(threeMat);
  104839. tileBoxes.matrix.copy(root.matrixWorld);
  104840. //boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  104841. //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  104842. //boxMap[tileset.root.id].updateWorldMatrix()
  104843. }
  104844. }
  104845. if (this.lastCameraTransform == null) {
  104846. this.lastCameraTransform = new Matrix4().copy(camera.matrixWorld);
  104847. }
  104848. else {
  104849. const cameraChanged = !camera.matrixWorld.equals(this.lastCameraTransform) ||
  104850. !(camera.aspect == lastCameraAspect);
  104851. if (cameraChanged || ifForce) {
  104852. timer = 0;
  104853. tileset._frameNumber++;
  104854. camera.getWorldPosition(lastCameraPosition);
  104855. this.lastCameraTransform.copy(camera.matrixWorld);
  104856. tilesetUpdate(tileset, renderMap, renderer, camera);
  104857. }
  104858. }
  104859. }/* else{
  104860. console.log('11')
  104861. } */
  104862. },
  104863. dispose: function () {
  104864. disposeFlag = true;
  104865. tileset._destroy();
  104866. while (root.children.length > 0) {
  104867. const obj = root.children[0];
  104868. disposeNode(obj);
  104869. root.remove(obj);
  104870. }
  104871. while (tileBoxes.children.length > 0) {
  104872. const obj = tileBoxes.children[0];
  104873. tileBoxes.remove(obj);
  104874. obj.geometry.dispose();
  104875. obj.material.dispose();
  104876. }
  104877. if (ktx2Loader) {
  104878. ktx2Loader.dispose();
  104879. }
  104880. if (dracoLoader) {
  104881. dracoLoader.dispose();
  104882. }
  104883. },
  104884. },
  104885. };
  104886. });
  104887. }
  104888. }
  104889. function createGLTFNodes(gltfLoader, tile, unlitMaterial, options, rootTransformInverse) {
  104890. return __awaiter(this, void 0, void 0, function* () {
  104891. return new Promise((resolve, reject) => {
  104892. var _a;
  104893. const rotateX = new Matrix4().makeRotationAxis(new Vector3(1, 0, 0), Math.PI / 2);
  104894. const shouldRotate = ((_a = tile.tileset.asset) === null || _a === void 0 ? void 0 : _a.gltfUpAxis) !== "Z";
  104895. // The computed trasnform already contains the root's transform, so we have to invert it
  104896. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tileMatrix)//.premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱
  104897. const contentTransform = new Matrix4().fromArray(tile.computedTransform).premultiply(tile.tileset.modelMatrix).premultiply(rootTransformInverse);
  104898. // 这句同tile.computedTransform左乘tileTrasnform。 因为tileTrasnform拿不到所以使用modelMatrix。modelMatrix为tileTrasnform左乘rootTransform, 所以再左乘rootTransformInverse
  104899. //改动:contentTransform中的computedTransform 去掉左乘 root.modelMatrixWorld , 因为移动过后这个computedTransform没更新
  104900. if (shouldRotate) {
  104901. contentTransform.multiply(rotateX); // convert from GLTF Y-up to Z-up
  104902. }
  104903. gltfLoader.parse(
  104904. tile.content.type == 'glTF' ? tile.content.gltf.gltfArrayBuffer : tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer,
  104905. tile.contentUrl ? tile.contentUrl.substr(0, tile.contentUrl.lastIndexOf('/') + 1) : '',
  104906. (gltf) => {
  104907. const tileContent = gltf.scenes[0];
  104908. //tileContent.applyMatrix4(contentTransform);
  104909. tileContent.vertexCount = 0; //xzw add
  104910. tileContent.traverse((object) => {
  104911. if (object.type == "Mesh") {
  104912. const mesh = object;
  104913. //mesh.tileId = tile.id//add
  104914. const originalMaterial = mesh.material;
  104915. const originalMap = originalMaterial.map;
  104916. if (options.material) {
  104917. mesh.material = options.material.clone();
  104918. originalMaterial.dispose();
  104919. }
  104920. else if (options.shading == Shading.FlatTexture) {
  104921. mesh.material = unlitMaterial.clone();
  104922. originalMaterial.dispose();
  104923. }
  104924. if (options.shading != Shading.ShadedNoTexture) {
  104925. if (mesh.material.type == "ShaderMaterial" && !(mesh.material instanceof BasicMaterial)) {//改
  104926. mesh.material.uniforms.map = { value: originalMap };
  104927. }
  104928. else {
  104929. mesh.material.map = originalMap;
  104930. }
  104931. }
  104932. else {
  104933. if (originalMap) {
  104934. originalMap.dispose();
  104935. }
  104936. mesh.material.map = null;
  104937. }
  104938. if (options.shaderCallback) {
  104939. mesh.onBeforeRender = options.shaderCallback;
  104940. }
  104941. mesh.material.wireframe = options.wireframe;
  104942. if (options.computeNormals) {
  104943. mesh.geometry.computeVertexNormals();
  104944. }
  104945. //xzw add:
  104946. tileContent.vertexCount += mesh.geometry.attributes.position.count;
  104947. //------------------add on 2023.1.16----zeg
  104948. mesh.geometry.applyMatrix4(contentTransform);
  104949. if (tile.content.rtcCenter) {
  104950. // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json
  104951. mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2]);
  104952. } else {
  104953. mesh.geometry.scale(1, 1, -1); // 调整缩放,对应box也要进行变换(scaleZ对应box[2])
  104954. }
  104955. //---------------------
  104956. }
  104957. });
  104958. resolve(tileContent);
  104959. },
  104960. (e) => {
  104961. reject(new Error(`error parsing gltf in tile ${tile.id}: ${e}`));
  104962. }
  104963. );
  104964. });
  104965. });
  104966. }
  104967. function createPointNodes(tile, pointcloudMaterial, options, rootTransformInverse) {
  104968. const d = {
  104969. rtc_center: tile.content.rtcCenter,
  104970. points: tile.content.attributes.positions,
  104971. intensities: tile.content.attributes.intensity,
  104972. classifications: tile.content.attributes.classification,
  104973. rgb: null,
  104974. rgba: null,
  104975. };
  104976. const { colors } = tile.content.attributes;
  104977. if (colors && colors.size === 3) {
  104978. d.rgb = colors.value;
  104979. }
  104980. if (colors && colors.size === 4) {
  104981. d.rgba = colors.value;
  104982. }
  104983. const geometry = new BufferGeometry();
  104984. geometry.setAttribute('position', new Float32BufferAttribute(d.points, 3));
  104985. const contentTransform = new Matrix4().fromArray(tile.computedTransform).premultiply(rootTransformInverse);
  104986. if (d.rgba) {
  104987. geometry.setAttribute('color', new Float32BufferAttribute(d.rgba, 4));
  104988. }
  104989. else if (d.rgb) {
  104990. geometry.setAttribute('color', new Uint8BufferAttribute(d.rgb, 3, true));
  104991. }
  104992. if (d.intensities) {
  104993. geometry.setAttribute('intensity',
  104994. // Handles both 16bit or 8bit intensity values
  104995. new BufferAttribute(d.intensities, 1, true));
  104996. }
  104997. if (d.classifications) {
  104998. geometry.setAttribute('classification', new Uint8BufferAttribute(d.classifications, 1, false));
  104999. }
  105000. const tileContent = new Points(geometry, options.material || pointcloudMaterial);
  105001. if (d.rtc_center) {
  105002. const c = d.rtc_center;
  105003. contentTransform.multiply(new Matrix4().makeTranslation(c[0], c[1], c[2]));
  105004. }
  105005. tileContent.applyMatrix4(contentTransform);
  105006. return tileContent;
  105007. }
  105008. function disposeMaterial(material) {
  105009. var _a, _b, _c, _d;
  105010. if ((_a = material === null || material === void 0 ? void 0 : material.uniforms) === null || _a === void 0 ? void 0 : _a.map) {
  105011. (_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();
  105012. }
  105013. else if (material.map) {
  105014. (_d = material.map) === null || _d === void 0 ? void 0 : _d.dispose();
  105015. }
  105016. material.dispose();
  105017. }
  105018. function disposeNode(node) {
  105019. node.traverse((object) => {
  105020. if (object.isMesh) {
  105021. object.geometry.dispose();
  105022. if (object.material.isMaterial) {
  105023. disposeMaterial(object.material);
  105024. }
  105025. else {
  105026. // an array of materials
  105027. for (const material of object.material) {
  105028. disposeMaterial(material);
  105029. }
  105030. }
  105031. }
  105032. });
  105033. for (let i = node.children.length - 1; i >= 0; i--) {
  105034. const obj = node.children[i];
  105035. node.remove(obj);
  105036. }
  105037. }
  105038. /*
  105039. 关键搜寻:
  105040. Loader3DTiles : const tileset = new Tileset3D
  105041. tileset.dispatchEvent({type:'tileLoaded',tileContent})
  105042. createGLTFNodes(gltfLoader 创建tile
  105043. executeTraversal(root, frameState) 遍历root
  105044. lastRootTransform rootTransformInverse
  105045. tileset._loadTiles 依次加载tiles
  105046. _getPriority 加载优先级 加了一句
  105047. 笔记:
  105048. 主要类:
  105049. class tileset3D 最外层整体。 获取方法: viewer.objs.children[index].runtime.getTileset()。 .tiles包含所有tiles
  105050. class tileHeader 也就是tileset里面的一个个tile 。 其上有.tileset
  105051. tileset里算的tileTrasnform之后是不会改变的, tile.transform也是,是json里的。
  105052. tileset.modelMatrix (通常这个值很大) 会随着位移改变
  105053. tile.computedTransform 被我修改了,之前左乘了tileset.modelMatrix,现只包含了transform信息 _updateTransform(parentTransfor 其中有_updateBoundingVolume,这个影响可见性, 在computeVisibilityWithPlaneMask中计算
  105054. tileset._cache.trim(), 然后再update //可以将所有不可见的tiles dispose
  105055. 相机靠近容易缺块的bug暂时修改如下: _visible是由computeVisibilityWithPlaneMask计算得
  105056. get isVisibleAndInRequestVolume() {
  105057. return this._inRequestVolume; //去掉了_visible ||
  105058. }
  105059. 显示所有tile似乎也不会卡顿. 但好像影响了加载顺序从而变慢了。visiVertexCount过量。 怀疑应该还是文件的bound有问题。
  105060. 原本会消失的地方虽然不会消失了但一直是模糊的
  105061. */
  105062. /**
  105063. * Description: A THREE loader for PLY ASCII files (known as the Polygon
  105064. * File Format or the Stanford Triangle Format).
  105065. *
  105066. * Limitations: ASCII decoding assumes file is UTF-8.
  105067. *
  105068. * Usage:
  105069. * var loader = new PLYLoader();
  105070. * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) {
  105071. *
  105072. * scene.add( new THREE.Mesh( geometry ) );
  105073. *
  105074. * } );
  105075. *
  105076. * If the PLY file uses non standard property names, they can be mapped while
  105077. * loading. For example, the following maps the properties
  105078. * “diffuse_(red|green|blue)” in the file to standard color names.
  105079. *
  105080. * loader.setPropertyNameMapping( {
  105081. * diffuse_red: 'red',
  105082. * diffuse_green: 'green',
  105083. * diffuse_blue: 'blue'
  105084. * } );
  105085. *
  105086. */
  105087. var PLYLoader = function ( manager ) {
  105088. Loader.call( this, manager );
  105089. this.propertyNameMapping = {};
  105090. };
  105091. PLYLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  105092. constructor: PLYLoader,
  105093. load: function ( url, onLoad, onProgress, onError ) {
  105094. var scope = this;
  105095. var loader = new FileLoader( this.manager );
  105096. loader.setPath( this.path );
  105097. loader.setResponseType( 'arraybuffer' );
  105098. loader.setRequestHeader( this.requestHeader );
  105099. loader.setWithCredentials( this.withCredentials );
  105100. loader.load( url, function ( text ) {
  105101. try {
  105102. onLoad( scope.parse( text ) );
  105103. } catch ( e ) {
  105104. if ( onError ) {
  105105. onError( e );
  105106. } else {
  105107. console.error( e );
  105108. }
  105109. scope.manager.itemError( url );
  105110. }
  105111. }, onProgress, onError );
  105112. },
  105113. setPropertyNameMapping: function ( mapping ) {
  105114. this.propertyNameMapping = mapping;
  105115. },
  105116. parse: function ( data ) {
  105117. function parseHeader( data ) {
  105118. var patternHeader = /ply([\s\S]*)end_header\r?\n/;
  105119. var headerText = '';
  105120. var headerLength = 0;
  105121. var result = patternHeader.exec( data );
  105122. if ( result !== null ) {
  105123. headerText = result[ 1 ];
  105124. headerLength = new Blob( [ result[ 0 ] ] ).size;
  105125. }
  105126. var header = {
  105127. comments: [],
  105128. elements: [],
  105129. headerLength: headerLength,
  105130. objInfo: ''
  105131. };
  105132. var lines = headerText.split( '\n' );
  105133. var currentElement;
  105134. var lineType, lineValues;
  105135. function make_ply_element_property( propertValues, propertyNameMapping ) {
  105136. var property = { type: propertValues[ 0 ] };
  105137. if ( property.type === 'list' ) {
  105138. property.name = propertValues[ 3 ];
  105139. property.countType = propertValues[ 1 ];
  105140. property.itemType = propertValues[ 2 ];
  105141. } else {
  105142. property.name = propertValues[ 1 ];
  105143. }
  105144. if ( property.name in propertyNameMapping ) {
  105145. property.name = propertyNameMapping[ property.name ];
  105146. }
  105147. return property;
  105148. }
  105149. for ( var i = 0; i < lines.length; i ++ ) {
  105150. var line = lines[ i ];
  105151. line = line.trim();
  105152. if ( line === '' ) continue;
  105153. lineValues = line.split( /\s+/ );
  105154. lineType = lineValues.shift();
  105155. line = lineValues.join( ' ' );
  105156. switch ( lineType ) {
  105157. case 'format':
  105158. header.format = lineValues[ 0 ];
  105159. header.version = lineValues[ 1 ];
  105160. break;
  105161. case 'comment':
  105162. header.comments.push( line );
  105163. break;
  105164. case 'element':
  105165. if ( currentElement !== undefined ) {
  105166. header.elements.push( currentElement );
  105167. }
  105168. currentElement = {};
  105169. currentElement.name = lineValues[ 0 ];
  105170. currentElement.count = parseInt( lineValues[ 1 ] );
  105171. currentElement.properties = [];
  105172. break;
  105173. case 'property':
  105174. currentElement.properties.push( make_ply_element_property( lineValues, scope.propertyNameMapping ) );
  105175. break;
  105176. case 'obj_info':
  105177. header.objInfo = line;
  105178. break;
  105179. default:
  105180. console.log( 'unhandled', lineType, lineValues );
  105181. }
  105182. }
  105183. if ( currentElement !== undefined ) {
  105184. header.elements.push( currentElement );
  105185. }
  105186. return header;
  105187. }
  105188. function parseASCIINumber( n, type ) {
  105189. switch ( type ) {
  105190. case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint':
  105191. case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32':
  105192. return parseInt( n );
  105193. case 'float': case 'double': case 'float32': case 'float64':
  105194. return parseFloat( n );
  105195. }
  105196. }
  105197. function parseASCIIElement( properties, line ) {
  105198. var values = line.split( /\s+/ );
  105199. var element = {};
  105200. for ( var i = 0; i < properties.length; i ++ ) {
  105201. if ( properties[ i ].type === 'list' ) {
  105202. var list = [];
  105203. var n = parseASCIINumber( values.shift(), properties[ i ].countType );
  105204. for ( var j = 0; j < n; j ++ ) {
  105205. list.push( parseASCIINumber( values.shift(), properties[ i ].itemType ) );
  105206. }
  105207. element[ properties[ i ].name ] = list;
  105208. } else {
  105209. element[ properties[ i ].name ] = parseASCIINumber( values.shift(), properties[ i ].type );
  105210. }
  105211. }
  105212. return element;
  105213. }
  105214. function parseASCII( data, header ) {
  105215. // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
  105216. var buffer = {
  105217. indices: [],
  105218. vertices: [],
  105219. normals: [],
  105220. uvs: [],
  105221. faceVertexUvs: [],
  105222. colors: []
  105223. };
  105224. var result;
  105225. var patternBody = /end_header\s([\s\S]*)$/;
  105226. var body = '';
  105227. if ( ( result = patternBody.exec( data ) ) !== null ) {
  105228. body = result[ 1 ];
  105229. }
  105230. var lines = body.split( '\n' );
  105231. var currentElement = 0;
  105232. var currentElementCount = 0;
  105233. for ( var i = 0; i < lines.length; i ++ ) {
  105234. var line = lines[ i ];
  105235. line = line.trim();
  105236. if ( line === '' ) {
  105237. continue;
  105238. }
  105239. if ( currentElementCount >= header.elements[ currentElement ].count ) {
  105240. currentElement ++;
  105241. currentElementCount = 0;
  105242. }
  105243. var element = parseASCIIElement( header.elements[ currentElement ].properties, line );
  105244. handleElement( buffer, header.elements[ currentElement ].name, element );
  105245. currentElementCount ++;
  105246. }
  105247. return postProcess( buffer );
  105248. }
  105249. function postProcess( buffer ) {
  105250. var geometry = new BufferGeometry();
  105251. // mandatory buffer data
  105252. if ( buffer.indices.length > 0 ) {
  105253. geometry.setIndex( buffer.indices );
  105254. }
  105255. geometry.setAttribute( 'position', new Float32BufferAttribute( buffer.vertices, 3 ) );
  105256. // optional buffer data
  105257. if ( buffer.normals.length > 0 ) {
  105258. geometry.setAttribute( 'normal', new Float32BufferAttribute( buffer.normals, 3 ) );
  105259. }
  105260. if ( buffer.uvs.length > 0 ) {
  105261. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.uvs, 2 ) );
  105262. }
  105263. if ( buffer.colors.length > 0 ) {
  105264. geometry.setAttribute( 'color', new Float32BufferAttribute( buffer.colors, 3 ) );
  105265. }
  105266. if ( buffer.faceVertexUvs.length > 0 ) {
  105267. geometry = geometry.toNonIndexed();
  105268. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.faceVertexUvs, 2 ) );
  105269. }
  105270. geometry.computeBoundingSphere();
  105271. return geometry;
  105272. }
  105273. function handleElement( buffer, elementName, element ) {
  105274. if ( elementName === 'vertex' ) {
  105275. buffer.vertices.push( element.x, element.y, element.z );
  105276. if ( 'nx' in element && 'ny' in element && 'nz' in element ) {
  105277. buffer.normals.push( element.nx, element.ny, element.nz );
  105278. }
  105279. if ( 's' in element && 't' in element ) {
  105280. buffer.uvs.push( element.s, element.t );
  105281. }
  105282. if ( 'red' in element && 'green' in element && 'blue' in element ) {
  105283. buffer.colors.push( element.red / 255.0, element.green / 255.0, element.blue / 255.0 );
  105284. }
  105285. } else if ( elementName === 'face' ) {
  105286. var vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338
  105287. var texcoord = element.texcoord;
  105288. if ( vertex_indices.length === 3 ) {
  105289. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 2 ] );
  105290. if ( texcoord && texcoord.length === 6 ) {
  105291. buffer.faceVertexUvs.push( texcoord[ 0 ], texcoord[ 1 ] );
  105292. buffer.faceVertexUvs.push( texcoord[ 2 ], texcoord[ 3 ] );
  105293. buffer.faceVertexUvs.push( texcoord[ 4 ], texcoord[ 5 ] );
  105294. }
  105295. } else if ( vertex_indices.length === 4 ) {
  105296. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 3 ] );
  105297. buffer.indices.push( vertex_indices[ 1 ], vertex_indices[ 2 ], vertex_indices[ 3 ] );
  105298. }
  105299. }
  105300. }
  105301. function binaryRead( dataview, at, type, little_endian ) {
  105302. switch ( type ) {
  105303. // corespondences for non-specific length types here match rply:
  105304. case 'int8': case 'char': return [ dataview.getInt8( at ), 1 ];
  105305. case 'uint8': case 'uchar': return [ dataview.getUint8( at ), 1 ];
  105306. case 'int16': case 'short': return [ dataview.getInt16( at, little_endian ), 2 ];
  105307. case 'uint16': case 'ushort': return [ dataview.getUint16( at, little_endian ), 2 ];
  105308. case 'int32': case 'int': return [ dataview.getInt32( at, little_endian ), 4 ];
  105309. case 'uint32': case 'uint': return [ dataview.getUint32( at, little_endian ), 4 ];
  105310. case 'float32': case 'float': return [ dataview.getFloat32( at, little_endian ), 4 ];
  105311. case 'float64': case 'double': return [ dataview.getFloat64( at, little_endian ), 8 ];
  105312. }
  105313. }
  105314. function binaryReadElement( dataview, at, properties, little_endian ) {
  105315. var element = {};
  105316. var result, read = 0;
  105317. for ( var i = 0; i < properties.length; i ++ ) {
  105318. if ( properties[ i ].type === 'list' ) {
  105319. var list = [];
  105320. result = binaryRead( dataview, at + read, properties[ i ].countType, little_endian );
  105321. var n = result[ 0 ];
  105322. read += result[ 1 ];
  105323. for ( var j = 0; j < n; j ++ ) {
  105324. result = binaryRead( dataview, at + read, properties[ i ].itemType, little_endian );
  105325. list.push( result[ 0 ] );
  105326. read += result[ 1 ];
  105327. }
  105328. element[ properties[ i ].name ] = list;
  105329. } else {
  105330. result = binaryRead( dataview, at + read, properties[ i ].type, little_endian );
  105331. element[ properties[ i ].name ] = result[ 0 ];
  105332. read += result[ 1 ];
  105333. }
  105334. }
  105335. return [ element, read ];
  105336. }
  105337. function parseBinary( data, header ) {
  105338. var buffer = {
  105339. indices: [],
  105340. vertices: [],
  105341. normals: [],
  105342. uvs: [],
  105343. faceVertexUvs: [],
  105344. colors: []
  105345. };
  105346. var little_endian = ( header.format === 'binary_little_endian' );
  105347. var body = new DataView( data, header.headerLength );
  105348. var result, loc = 0;
  105349. for ( var currentElement = 0; currentElement < header.elements.length; currentElement ++ ) {
  105350. for ( var currentElementCount = 0; currentElementCount < header.elements[ currentElement ].count; currentElementCount ++ ) {
  105351. result = binaryReadElement( body, loc, header.elements[ currentElement ].properties, little_endian );
  105352. loc += result[ 1 ];
  105353. var element = result[ 0 ];
  105354. handleElement( buffer, header.elements[ currentElement ].name, element );
  105355. }
  105356. }
  105357. return postProcess( buffer );
  105358. }
  105359. //
  105360. var geometry;
  105361. var scope = this;
  105362. if ( data instanceof ArrayBuffer ) {
  105363. var text = LoaderUtils.decodeText( new Uint8Array( data ) );
  105364. var header = parseHeader( text );
  105365. geometry = header.format === 'ascii' ? parseASCII( text, header ) : parseBinary( data, header );
  105366. } else {
  105367. geometry = parseASCII( data, parseHeader( data ) );
  105368. }
  105369. return geometry;
  105370. }
  105371. } );
  105372. /**
  105373. *
  105374. * Supersample Anti-Aliasing Render Pass
  105375. *
  105376. * @author bhouston / http://clara.io/
  105377. *
  105378. * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
  105379. *
  105380. * References: https://en.wikipedia.org/wiki/Supersampling
  105381. *
  105382. */
  105383. //较为原始的一种抗锯齿 (超级采样抗锯齿)
  105384. let SSAARenderPass = function ( clearColor, clearAlpha ) {
  105385. Pass.call( this );
  105386. //this.scene //= scene;
  105387. //this.camera = camera;
  105388. this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  105389. this.unbiased = true;
  105390. // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
  105391. this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000;
  105392. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  105393. this.renderUniforms = {
  105394. bgTex : {value:null},
  105395. outlineTex : {value:null},
  105396. opacity : {value:1},
  105397. };
  105398. this.renderMat = new ShaderMaterial({
  105399. uniforms: this.renderUniforms,
  105400. vertexShader: CopyShader.vertexShader,
  105401. /* fragmentShader: CopyShader.fragmentShader, */
  105402. fragmentShader: `
  105403. uniform sampler2D bgTex;
  105404. uniform sampler2D outlineTex;
  105405. uniform float opacity;
  105406. varying vec2 vUv;
  105407. void main() {
  105408. vec4 color1 = texture2D( bgTex, vUv );
  105409. vec4 color2 = texture2D( outlineTex, vUv );
  105410. gl_FragColor = opacity * mix(color1, color2, color2.a) ;
  105411. }
  105412. `,
  105413. premultipliedAlpha: true,
  105414. blending: AdditiveBlending,
  105415. depthTest: false,
  105416. depthWrite: false,
  105417. transparent: true
  105418. });
  105419. this.renderMat2 = new ShaderMaterial({
  105420. uniforms: UniformsUtils.clone(CopyShader.uniforms) ,
  105421. vertexShader: CopyShader.vertexShader,
  105422. fragmentShader:`uniform float opacity;
  105423. uniform sampler2D tDiffuse;
  105424. varying vec2 vUv;
  105425. void main() {
  105426. vec4 texel = texture2D( tDiffuse, vUv );
  105427. if(texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0){
  105428. discard;
  105429. }else{
  105430. gl_FragColor = opacity * texel;
  105431. }
  105432. }
  105433. ` ,
  105434. depthTest: false,
  105435. depthWrite: false,
  105436. transparent: true
  105437. });
  105438. ////////////////////
  105439. /* this.renderMat.blendSrc = THREE.OneFactor //即将写入缓冲区的颜色。
  105440. this.renderMat.blendDst = THREE.OneFactor //缓冲区已经存在的颜色
  105441. this.renderMat.blendEquation = THREE.AddEquation;
  105442. this.renderMat.blendEquationAlpha = THREE.AddEquation;
  105443. this.renderMat.blendDstAlpha = THREE.SrcAlphaFactor
  105444. this.renderMat.blendSrcAlpha = THREE.SrcAlphaFactor */
  105445. this.camera2 = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  105446. this.scene2 = new Scene();
  105447. this.quad2 = new Mesh( new PlaneBufferGeometry( 2, 2 ), this.renderMat/* this.copyMaterial */ );
  105448. this.quad2.frustumCulled = false; // Avoid getting clipped
  105449. this.scene2.add( this.quad2 );
  105450. this.copyPass = new ShaderPass( CopyShader );
  105451. this.copyPass.renderToScreen = true;
  105452. };
  105453. SSAARenderPass.prototype = Object.assign( Object.create( Pass.prototype ), {
  105454. constructor: SSAARenderPass,
  105455. dispose: function () {
  105456. if ( this.sampleRenderTarget ) {
  105457. this.sampleRenderTarget.dispose();
  105458. this.sampleRenderTarget = null;
  105459. }
  105460. },
  105461. setSize: function ( width, height ) {
  105462. if ( this.sampleRenderTarget ) this.sampleRenderTarget.setSize( width, height );
  105463. this.childPass && this.childPass.setSize(width, height);
  105464. },
  105465. addPass: function (pass){
  105466. this.childPass = pass;
  105467. },
  105468. render: function (scene, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun ) {
  105469. if(this.useCopy ){
  105470. scene = this.copyPass.scene; camera = this.copyPass.camera;
  105471. }
  105472. if ( ! this.sampleRenderTarget ) {
  105473. this.sampleRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat } );
  105474. this.sampleRenderTarget.texture.name = "SSAARenderPass.sample";
  105475. }
  105476. var jitterOffsets = SSAARenderPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
  105477. var autoClear = renderer.autoClear;
  105478. renderer.autoClear = false;
  105479. var oldClearColor = renderer.getClearColor(new Color).getHex();
  105480. var oldClearAlpha = renderer.getClearAlpha();
  105481. renderer.setClearColor( this.clearColor, this.clearAlpha );
  105482. var baseSampleWeight = 1.0 / jitterOffsets.length;
  105483. var roundingRange = 1 / 32;
  105484. //this.copyUniforms[ "tDiffuse" ].value = this.sampleRenderTarget.texture;
  105485. let oldTarget = renderer.getRenderTarget();
  105486. if(oldTarget){
  105487. if(oldTarget.scissorTest){
  105488. var width = oldTarget.scissor.w, height = oldTarget.scissor.z;
  105489. }else {
  105490. var width = oldTarget.width, height = oldTarget.height;
  105491. }
  105492. }else {
  105493. var width = readBuffer.width, height = readBuffer.height;
  105494. }
  105495. // render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
  105496. let opa = 0;
  105497. for ( var i = 0; i < jitterOffsets.length; i ++ ) {
  105498. var jitterOffset = jitterOffsets[ i ];
  105499. if ( camera.setViewOffset ) {
  105500. camera.setViewOffset( width, height,
  105501. jitterOffset[ 0 ] * 0.0625 , jitterOffset[ 1 ] * 0.0625 , // 0.0625 = 1 / 16
  105502. width, height );
  105503. }
  105504. var sampleWeight = baseSampleWeight;
  105505. if ( this.unbiased ) {//更柔和
  105506. var uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
  105507. sampleWeight += roundingRange * uniformCenteredDistribution;
  105508. }
  105509. renderer.setRenderTarget(this.sampleRenderTarget);
  105510. renderer.clear();
  105511. if(this.useCopy){
  105512. this.copyPass.render(scene,camera, null,renderer, writeBuffer, readBuffer );
  105513. }else {
  105514. if(renderFun){
  105515. renderFun({target : this.sampleRenderTarget});
  105516. }else {
  105517. renderer.render( scene, camera );
  105518. }
  105519. }
  105520. renderer.setRenderTarget(oldTarget);
  105521. //---------------------
  105522. //获取outline tex
  105523. let hasOutline = this.childPass && this.childPass.render(scene, camera, renderer, writeBuffer, readBuffer, null, renderFun );
  105524. //合成到该材质
  105525. this.renderUniforms[ "bgTex" ].value = this.sampleRenderTarget.texture;
  105526. this.renderUniforms[ "outlineTex" ].value = hasOutline ? readBuffer.texture : null;
  105527. this.renderUniforms[ "opacity" ].value = sampleWeight;
  105528. /* console.log('sampleWeight', sampleWeight)
  105529. opa += sampleWeight */
  105530. if(!this.renderToScreen){
  105531. renderer.setRenderTarget(writeBuffer);
  105532. }
  105533. if(i === 0 ){
  105534. renderer.setClearColor( 0x000000, 0 ); //叠加前颜色必须0
  105535. renderer.clear();
  105536. }
  105537. renderer.render( this.scene2, this.camera2); // , this.renderToScreen ? null : writeBuffer, ( i === 0 )
  105538. if(!this.renderToScreen){
  105539. renderer.setRenderTarget(oldTarget);
  105540. }
  105541. //if(i==2)break;
  105542. }
  105543. //console.log('sum:',opa)
  105544. if ( camera.clearViewOffset )camera.clearViewOffset();
  105545. //renderer.setRenderTarget(readBuffer)
  105546. //renderer.setClearColor( 0x000000, 0 );
  105547. //renderer.clear()
  105548. /* this.quad2.material = this.renderMat2
  105549. this.renderMat2.uniforms.tDiffuse.value = writeBuffer.texture;
  105550. renderer.render( this.scene2, this.camera2);
  105551. this.quad2.material = this.renderMat */
  105552. //renderer.setRenderTarget(oldTarget)
  105553. renderer.autoClear = autoClear;
  105554. renderer.setClearColor( oldClearColor, oldClearAlpha );
  105555. /* 试了好几次,测量线的透明度还是还原不了。 clearAlpha十分影响结果。
  105556. 因为绘制测量线需要背景透明。 或许可以先全部绘制完后,再 copyshader中 抗锯齿?
  105557. 另外会有黑边。
  105558. */
  105559. }
  105560. } );
  105561. // These jitter vectors are specified in integers because it is easier.
  105562. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  105563. // before being used, thus these integers need to be scaled by 1/16.
  105564. //
  105565. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  105566. SSAARenderPass.JitterVectors = [
  105567. [
  105568. [ 0, 0 ]
  105569. ],
  105570. [
  105571. [ 4, 4 ], [ - 4, - 4 ]
  105572. ],
  105573. [
  105574. [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
  105575. ],
  105576. [
  105577. [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
  105578. [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
  105579. ],
  105580. [
  105581. [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
  105582. [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
  105583. [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
  105584. [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
  105585. ],
  105586. [
  105587. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  105588. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  105589. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  105590. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  105591. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  105592. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  105593. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  105594. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  105595. ]
  105596. ];
  105597. class MaskPass extends Pass {
  105598. constructor( scene, camera ) {
  105599. super();
  105600. this.scene = scene;
  105601. this.camera = camera;
  105602. this.clear = true;
  105603. this.needsSwap = false;
  105604. this.inverse = false;
  105605. }
  105606. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  105607. const context = renderer.getContext();
  105608. const state = renderer.state;
  105609. // don't update color or depth
  105610. state.buffers.color.setMask( false );
  105611. state.buffers.depth.setMask( false );
  105612. // lock buffers
  105613. state.buffers.color.setLocked( true );
  105614. state.buffers.depth.setLocked( true );
  105615. // set up stencil
  105616. let writeValue, clearValue;
  105617. if ( this.inverse ) {
  105618. writeValue = 0;
  105619. clearValue = 1;
  105620. } else {
  105621. writeValue = 1;
  105622. clearValue = 0;
  105623. }
  105624. state.buffers.stencil.setTest( true );
  105625. state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE );
  105626. state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff );
  105627. state.buffers.stencil.setClear( clearValue );
  105628. state.buffers.stencil.setLocked( true );
  105629. // draw into the stencil buffer
  105630. renderer.setRenderTarget( readBuffer );
  105631. if ( this.clear ) renderer.clear();
  105632. renderer.render( this.scene, this.camera );
  105633. renderer.setRenderTarget( writeBuffer );
  105634. if ( this.clear ) renderer.clear();
  105635. renderer.render( this.scene, this.camera );
  105636. // unlock color and depth buffer for subsequent rendering
  105637. state.buffers.color.setLocked( false );
  105638. state.buffers.depth.setLocked( false );
  105639. // only render where stencil is set to 1
  105640. state.buffers.stencil.setLocked( false );
  105641. state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1
  105642. state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP );
  105643. state.buffers.stencil.setLocked( true );
  105644. }
  105645. }
  105646. class ClearMaskPass extends Pass {
  105647. constructor() {
  105648. super();
  105649. this.needsSwap = false;
  105650. }
  105651. render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  105652. renderer.state.buffers.stencil.setLocked( false );
  105653. renderer.state.buffers.stencil.setTest( false );
  105654. }
  105655. }
  105656. /**
  105657. * @author alteredq / http://alteredqualia.com/
  105658. */
  105659. var EffectComposer = function ( renderer, renderTarget ) {
  105660. this.renderer = renderer;
  105661. if ( renderTarget === undefined ) {
  105662. var parameters = {
  105663. minFilter: LinearFilter,
  105664. magFilter: LinearFilter,
  105665. format: RGBAFormat,
  105666. stencilBuffer: false,
  105667. };
  105668. var size = renderer.getDrawingBufferSize(new Vector2);
  105669. renderTarget = new WebGLRenderTarget( size.width, size.height , parameters );
  105670. renderTarget.texture.name = 'EffectComposer.rt1';
  105671. }
  105672. this.renderTarget1 = renderTarget;
  105673. this.renderTarget2 = renderTarget.clone();
  105674. this.renderTarget2.texture.name = 'EffectComposer.rt2';
  105675. this.writeBuffer = this.renderTarget1;
  105676. this.readBuffer = this.renderTarget2;
  105677. this.passes = [];
  105678. // dependencies
  105679. /* if ( THREE.CopyShader === undefined ) {
  105680. console.error( 'THREE.EffectComposer relies on THREE.CopyShader' );
  105681. }
  105682. if ( THREE.ShaderPass === undefined ) {
  105683. console.error( 'THREE.EffectComposer relies on THREE.ShaderPass' );
  105684. } */
  105685. this.copyPass = new ShaderPass( CopyShader );
  105686. viewer.addEventListener('resize',(e)=>{ //readTarget的话是渲染一整张的,暂时无法一个个viewport渲染所以不用
  105687. this.readTarget || this.setSize(e.viewport.resolution2.x,e.viewport.resolution2.y); //暂时假设composer渲染的viewer的viewports.length == 1
  105688. });
  105689. };
  105690. Object.assign( EffectComposer.prototype, {
  105691. swapBuffers: function () {
  105692. var tmp = this.readBuffer;
  105693. this.readBuffer = this.writeBuffer;
  105694. this.writeBuffer = tmp;
  105695. },
  105696. addPass: function ( pass ) {
  105697. this.passes.push( pass );
  105698. var size = this.renderer.getDrawingBufferSize(new Vector2);
  105699. pass.setSize( size.width, size.height );
  105700. },
  105701. removePass: function(pass){ //add
  105702. let index = this.passes.indexOf(pass);
  105703. index > -1 && this.passes.splice(index,1);
  105704. },
  105705. insertPass: function ( pass, index ) {
  105706. this.passes.splice( index, 0, pass );
  105707. },
  105708. render: function ( scene, camera, viewports, renderFun ) {
  105709. var maskActive = false;
  105710. let passes = this.passes.filter(e=>e.enabled);
  105711. var pass, i, il = passes.length;
  105712. let oldTarget = this.renderer.getRenderTarget();
  105713. if(this.readTarget && oldTarget){ //add 使用当前renderTarget中的像素
  105714. this.setSize(oldTarget.width, oldTarget.height);//所有viewports一起渲染,整个画面 因暂时没办法一个个copy
  105715. oldTarget.viewport.set(0, 0, oldTarget.width, oldTarget.height);
  105716. oldTarget.scissorTest = false;
  105717. this.copyPass.render( scene, camera,viewports, this.renderer, this.readBuffer, oldTarget );
  105718. }
  105719. for ( i = 0; i < il; i ++ ) {
  105720. pass = passes[ i ];
  105721. //if(i == il-1)pass.renderToScreen = true//
  105722. pass.render( scene, camera, viewports, this.renderer, this.writeBuffer, this.readBuffer, maskActive, renderFun );
  105723. if ( pass.needsSwap ) {
  105724. if ( maskActive ) {
  105725. var context = this.renderer.context;
  105726. context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
  105727. this.copyPass.render(null,null, viewports, this.renderer, this.writeBuffer, this.readBuffer );// delta
  105728. context.stencilFunc( context.EQUAL, 1, 0xffffffff );
  105729. }
  105730. this.swapBuffers();
  105731. }
  105732. if ( MaskPass !== undefined ) {
  105733. if ( pass instanceof MaskPass ) {
  105734. maskActive = true;
  105735. } else if ( pass instanceof ClearMaskPass ) {
  105736. maskActive = false;
  105737. }
  105738. }
  105739. }
  105740. this.renderer.setRenderTarget(oldTarget);
  105741. //add
  105742. if(!pass.renderToScreen){ //最后一个如果没有绘制到屏幕or target上
  105743. this.copyPass.renderToScreen = true;
  105744. this.copyPass.render(null,null, viewports,this.renderer, this.writeBuffer, this.readBuffer);
  105745. }
  105746. },
  105747. reset: function ( renderTarget ) {
  105748. if ( renderTarget === undefined ) {
  105749. var size = this.renderer.getDrawingBufferSize(new Vector2);
  105750. renderTarget = this.renderTarget1.clone();
  105751. renderTarget.setSize( size.width, size.height );
  105752. }
  105753. this.renderTarget1.dispose();
  105754. this.renderTarget2.dispose();
  105755. this.renderTarget1 = renderTarget;
  105756. this.renderTarget2 = renderTarget.clone();
  105757. this.writeBuffer = this.renderTarget1;
  105758. this.readBuffer = this.renderTarget2;
  105759. },
  105760. setSize: function ( width, height, scaleRatio ) {
  105761. scaleRatio = scaleRatio || this.scaleRatio || 1;
  105762. //console.log('setSize', width * scaleRatio, height * scaleRatio)
  105763. let maxTexWidth = 4096;
  105764. let w = width * scaleRatio;
  105765. let h = height * scaleRatio;
  105766. if(w > maxTexWidth || h > maxTexWidth){ //超出会崩溃
  105767. if(w>h){
  105768. scaleRatio = maxTexWidth / width;
  105769. }else {
  105770. scaleRatio = maxTexWidth / height;
  105771. }
  105772. }
  105773. w = width * scaleRatio;
  105774. h = height * scaleRatio;
  105775. this.renderTarget1.setSize( w, h );
  105776. this.renderTarget2.setSize( w, h );
  105777. for ( var i = 0; i < this.passes.length; i ++ ) {
  105778. this.passes[ i ].setSize( w, h );
  105779. }
  105780. }
  105781. } );
  105782. /**
  105783. * @author alteredq / http://alteredqualia.com/
  105784. */
  105785. class RenderPass extends Pass {
  105786. constructor( overrideMaterial, clearColor, clearAlpha ) {
  105787. super();
  105788. /* this.scene = scene;
  105789. this.camera = camera; */
  105790. this.overrideMaterial = overrideMaterial;
  105791. this.clearColor = clearColor;
  105792. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  105793. this.clear = true;
  105794. this.clearDepth = false;
  105795. this.needsSwap = false;
  105796. this._oldClearColor = new Color();
  105797. }
  105798. render(scene, camera, viewports,renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  105799. const oldAutoClear = renderer.autoClear;
  105800. renderer.autoClear = false;
  105801. let oldClearAlpha, oldOverrideMaterial;
  105802. if ( this.overrideMaterial !== undefined ) {
  105803. oldOverrideMaterial = this.scene.overrideMaterial;
  105804. scene.overrideMaterial = this.overrideMaterial;
  105805. }
  105806. if ( this.clearColor ) {
  105807. renderer.getClearColor( this._oldClearColor );
  105808. oldClearAlpha = renderer.getClearAlpha();
  105809. renderer.setClearColor( this.clearColor, this.clearAlpha );
  105810. }
  105811. if ( this.clearDepth ) {
  105812. renderer.clearDepth();
  105813. }
  105814. let oldTarget = renderer.getRenderTarget();
  105815. if(!this.renderToScreen)renderer.setRenderTarget( readBuffer );
  105816. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  105817. if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  105818. renderer.render( scene, camera );
  105819. if(!this.renderToScreen)renderer.setRenderTarget( oldTarget );
  105820. if ( this.clearColor ) {
  105821. renderer.setClearColor( this._oldClearColor, oldClearAlpha );
  105822. }
  105823. if ( this.overrideMaterial !== undefined ) {
  105824. scene.overrideMaterial = oldOverrideMaterial;
  105825. }
  105826. renderer.setRenderTarget(oldTarget);
  105827. renderer.autoClear = oldAutoClear;
  105828. }
  105829. }
  105830. /**
  105831. * NVIDIA FXAA by Timothy Lottes
  105832. * https://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf
  105833. * - WebGL port by @supereggbert
  105834. * http://www.glge.org/demos/fxaa/
  105835. * Further improved by Daniel Sturk
  105836. */
  105837. const FXAAShader = {
  105838. uniforms: {
  105839. 'tDiffuse': { value: null },
  105840. 'resolution': { value: new Vector2( 1 / 1024, 1 / 512 ) }
  105841. },
  105842. vertexShader: /* glsl */`
  105843. varying vec2 vUv;
  105844. void main() {
  105845. vUv = uv;
  105846. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  105847. }`,
  105848. fragmentShader: `
  105849. precision highp float;
  105850. uniform sampler2D tDiffuse;
  105851. uniform vec2 resolution;
  105852. varying vec2 vUv;
  105853. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  105854. //----------------------------------------------------------------------------------
  105855. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  105856. // SDK Version: v3.00
  105857. // Email: gameworks@nvidia.com
  105858. // Site: http://developer.nvidia.com/
  105859. //
  105860. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  105861. //
  105862. // Redistribution and use in source and binary forms, with or without
  105863. // modification, are permitted provided that the following conditions
  105864. // are met:
  105865. // * Redistributions of source code must retain the above copyright
  105866. // notice, this list of conditions and the following disclaimer.
  105867. // * Redistributions in binary form must reproduce the above copyright
  105868. // notice, this list of conditions and the following disclaimer in the
  105869. // documentation and/or other materials provided with the distribution.
  105870. // * Neither the name of NVIDIA CORPORATION nor the names of its
  105871. // contributors may be used to endorse or promote products derived
  105872. // from this software without specific prior written permission.
  105873. //
  105874. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  105875. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  105876. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  105877. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  105878. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  105879. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  105880. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  105881. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  105882. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  105883. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  105884. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  105885. //
  105886. //----------------------------------------------------------------------------------
  105887. #ifndef FXAA_DISCARD
  105888. //
  105889. // Only valid for PC OpenGL currently.
  105890. // Probably will not work when FXAA_GREEN_AS_LUMA = 1.
  105891. //
  105892. // 1 = Use discard on pixels which don't need AA.
  105893. // For APIs which enable concurrent TEX+ROP from same surface.
  105894. // 0 = Return unchanged color on pixels which don't need AA.
  105895. //
  105896. #define FXAA_DISCARD 0
  105897. #endif
  105898. /*--------------------------------------------------------------------------*/
  105899. //第三个参数加入后只能在片元着色器中调用,且只对采样器为mipmap类型纹理时有效。不明白作用??? 但警告说范围在16之内
  105900. #define FxaaTexTop(t, p) texture2D(t, p, -15.0); //-100.0);
  105901. #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), -15.0); //-100.0)
  105902. /*--------------------------------------------------------------------------*/
  105903. #define NUM_SAMPLES 5
  105904. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  105905. float contrast( vec4 a, vec4 b ) {
  105906. vec4 diff = abs( a - b );
  105907. return max( max( max( diff.r, diff.g ), diff.b ), diff.a );
  105908. }
  105909. /*============================================================================
  105910. FXAA3 QUALITY - PC
  105911. ============================================================================*/
  105912. /*--------------------------------------------------------------------------*/
  105913. vec4 FxaaPixelShader(
  105914. vec2 posM,
  105915. sampler2D tex,
  105916. vec2 fxaaQualityRcpFrame,
  105917. float fxaaQualityEdgeThreshold,
  105918. float fxaaQualityinvEdgeThreshold
  105919. ) {
  105920. vec4 rgbaM = FxaaTexTop(tex, posM);
  105921. vec4 rgbaS = FxaaTexOff(tex, posM, vec2( 0.0, 1.0), fxaaQualityRcpFrame.xy);
  105922. vec4 rgbaE = FxaaTexOff(tex, posM, vec2( 1.0, 0.0), fxaaQualityRcpFrame.xy);
  105923. vec4 rgbaN = FxaaTexOff(tex, posM, vec2( 0.0,-1.0), fxaaQualityRcpFrame.xy);
  105924. vec4 rgbaW = FxaaTexOff(tex, posM, vec2(-1.0, 0.0), fxaaQualityRcpFrame.xy);
  105925. // . S .
  105926. // W M E
  105927. // . N .
  105928. bool earlyExit = max( max( max(
  105929. contrast( rgbaM, rgbaN ),
  105930. contrast( rgbaM, rgbaS ) ),
  105931. contrast( rgbaM, rgbaE ) ),
  105932. contrast( rgbaM, rgbaW ) )
  105933. < fxaaQualityEdgeThreshold;
  105934. // . 0 .
  105935. // 0 0 0
  105936. // . 0 .
  105937. #if (FXAA_DISCARD == 1)
  105938. if(earlyExit) FxaaDiscard;
  105939. #else
  105940. if(earlyExit) return rgbaM;
  105941. #endif
  105942. float contrastN = contrast( rgbaM, rgbaN );
  105943. float contrastS = contrast( rgbaM, rgbaS );
  105944. float contrastE = contrast( rgbaM, rgbaE );
  105945. float contrastW = contrast( rgbaM, rgbaW );
  105946. float relativeVContrast = ( contrastN + contrastS ) - ( contrastE + contrastW );
  105947. relativeVContrast *= fxaaQualityinvEdgeThreshold;
  105948. bool horzSpan = relativeVContrast > 0.;
  105949. // . 1 .
  105950. // 0 0 0
  105951. // . 1 .
  105952. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  105953. if( abs( relativeVContrast ) < .3 ) {
  105954. // locate the edge
  105955. vec2 dirToEdge;
  105956. dirToEdge.x = contrastE > contrastW ? 1. : -1.;
  105957. dirToEdge.y = contrastS > contrastN ? 1. : -1.;
  105958. // . 2 . . 1 .
  105959. // 1 0 2 ~= 0 0 1
  105960. // . 1 . . 0 .
  105961. // tap 2 pixels and see which ones are "outside" the edge, to
  105962. // determine if the edge is vertical or horizontal
  105963. vec4 rgbaAlongH = FxaaTexOff(tex, posM, vec2( dirToEdge.x, -dirToEdge.y ), fxaaQualityRcpFrame.xy);
  105964. float matchAlongH = contrast( rgbaM, rgbaAlongH );
  105965. // . 1 .
  105966. // 0 0 1
  105967. // . 0 H
  105968. vec4 rgbaAlongV = FxaaTexOff(tex, posM, vec2( -dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy);
  105969. float matchAlongV = contrast( rgbaM, rgbaAlongV );
  105970. // V 1 .
  105971. // 0 0 1
  105972. // . 0 .
  105973. relativeVContrast = matchAlongV - matchAlongH;
  105974. relativeVContrast *= fxaaQualityinvEdgeThreshold;
  105975. if( abs( relativeVContrast ) < .3 ) { // 45 deg edge
  105976. // 1 1 .
  105977. // 0 0 1
  105978. // . 0 1
  105979. // do a simple blur
  105980. return mix(
  105981. rgbaM,
  105982. (rgbaN + rgbaS + rgbaE + rgbaW) * .25,
  105983. .4
  105984. );
  105985. }
  105986. horzSpan = relativeVContrast > 0.;
  105987. }
  105988. if(!horzSpan) rgbaN = rgbaW;
  105989. if(!horzSpan) rgbaS = rgbaE;
  105990. // . 0 . 1
  105991. // 1 0 1 -> 0
  105992. // . 0 . 1
  105993. bool pairN = contrast( rgbaM, rgbaN ) > contrast( rgbaM, rgbaS );
  105994. if(!pairN) rgbaN = rgbaS;
  105995. vec2 offNP;
  105996. offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;
  105997. offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;
  105998. bool doneN = false;
  105999. bool doneP = false;
  106000. float nDist = 0.;
  106001. float pDist = 0.;
  106002. vec2 posN = posM;
  106003. vec2 posP = posM;
  106004. int iterationsUsed = 0;
  106005. int iterationsUsedN = 0;
  106006. int iterationsUsedP = 0;
  106007. for( int i = 0; i < NUM_SAMPLES; i++ ) {
  106008. iterationsUsed = i;
  106009. float increment = float(i + 1);
  106010. if(!doneN) {
  106011. nDist += increment;
  106012. posN = posM + offNP * nDist;
  106013. vec4 rgbaEndN = FxaaTexTop(tex, posN.xy);
  106014. doneN = contrast( rgbaEndN, rgbaM ) > contrast( rgbaEndN, rgbaN );
  106015. iterationsUsedN = i;
  106016. }
  106017. if(!doneP) {
  106018. pDist += increment;
  106019. posP = posM - offNP * pDist;
  106020. vec4 rgbaEndP = FxaaTexTop(tex, posP.xy);
  106021. doneP = contrast( rgbaEndP, rgbaM ) > contrast( rgbaEndP, rgbaN );
  106022. iterationsUsedP = i;
  106023. }
  106024. if(doneN || doneP) break;
  106025. }
  106026. if ( !doneP && !doneN ) return rgbaM; // failed to find end of edge
  106027. float dist = min(
  106028. doneN ? float( iterationsUsedN ) / float( NUM_SAMPLES - 1 ) : 1.,
  106029. doneP ? float( iterationsUsedP ) / float( NUM_SAMPLES - 1 ) : 1.
  106030. );
  106031. // hacky way of reduces blurriness of mostly diagonal edges
  106032. // but reduces AA quality
  106033. dist = pow(dist, .5);
  106034. dist = 1. - dist;
  106035. return mix(
  106036. rgbaM,
  106037. rgbaN,
  106038. dist * .5
  106039. );
  106040. }
  106041. void main() {
  106042. const float edgeDetectionQuality = 0.1 ;//.05 ; //越高,越保留细节;越低,越平滑 但模糊
  106043. const float invEdgeDetectionQuality = 1. / edgeDetectionQuality;
  106044. gl_FragColor = FxaaPixelShader(
  106045. vUv,
  106046. tDiffuse,
  106047. resolution,
  106048. edgeDetectionQuality, // [0,1] contrast needed, otherwise early discard
  106049. invEdgeDetectionQuality
  106050. );
  106051. //单独渲染测量线有黑边,因为透明区域的clearColor是(0,0,0),模糊化的时候采用了这些黑色因子来混色。因为测量线颜色可能多种,也不能直接修改clearColor为其颜色,且还有label。
  106052. //故而无法单独渲染测量线,而需要将底图一起渲染。
  106053. }
  106054. `
  106055. };
  106056. /**
  106057. * @author spidersharma / http://eduperiment.com/
  106058. */
  106059. let OutlinePass = function ( selectedObjects ) {
  106060. /* scene = scene;
  106061. camera = camera; */
  106062. this.selectedObjects = selectedObjects !== undefined ? selectedObjects : [];
  106063. this.visibleEdgeColor = new Color( 1, 1, 1 );
  106064. this.hiddenEdgeColor = new Color( 0.1, 0.04, 0.02 );
  106065. this.edgeGlow = 0.0;
  106066. this.usePatternTexture = false;
  106067. //this.edgeThickness = 1.0;
  106068. this.edgeStrength = 50;
  106069. this.downSampleRatio = 1;//2; // 抗锯齿 值越低renderTarget size越大,抗锯齿越强,线条可越细(或许可以把模糊化去掉?)
  106070. this.pulsePeriod = 0;
  106071. this.showHiddenPart = false; //是否判断被遮住的部分,以设置hiddenEdgeColor。一般不需要
  106072. Pass.call( this );
  106073. this.resolution = new Vector2( 256, 256 );
  106074. var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  106075. var resx = Math.round( this.resolution.x / this.downSampleRatio );
  106076. var resy = Math.round( this.resolution.y / this.downSampleRatio );
  106077. this.renderTargetMaskBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
  106078. this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask";
  106079. this.renderTargetMaskBuffer.texture.generateMipmaps = false;
  106080. this.depthMaterial = new MeshDepthMaterial();
  106081. this.depthMaterial.side = DoubleSide;
  106082. this.depthMaterial.depthPacking = RGBADepthPacking;
  106083. this.depthMaterial.blending = NoBlending;
  106084. this.prepareMaskMaterial = this.getPrepareMaskMaterial();
  106085. this.prepareMaskMaterial.side = DoubleSide;
  106086. this.renderTargetDepthBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
  106087. this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth";
  106088. this.renderTargetDepthBuffer.texture.generateMipmaps = false;
  106089. this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(this.edgeStrength);
  106090. this.renderTargetEdgeBuffer1 = new WebGLRenderTarget( resx, resy, pars );
  106091. this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1";
  106092. this.renderTargetEdgeBuffer1.texture.generateMipmaps = false;
  106093. // Overlay material
  106094. this.overlayMaterial = this.getOverlayMaterial();
  106095. // copy material
  106096. this.copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
  106097. this.copyUniforms[ "opacity" ].value = 1.0;
  106098. this.materialCopy = new ShaderMaterial( {
  106099. uniforms: this.copyUniforms,
  106100. vertexShader: CopyShader.vertexShader,
  106101. fragmentShader: CopyShader.fragmentShader,
  106102. blending: NoBlending,
  106103. depthTest: false,
  106104. depthWrite: false,
  106105. transparent: true
  106106. } );
  106107. this.enabled = true;
  106108. this.needsSwap = false;
  106109. this.oldClearColor = new Color();
  106110. this.oldClearAlpha = 1;
  106111. this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  106112. this.scene = new Scene();
  106113. this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), null );
  106114. this.quad.frustumCulled = false; // Avoid getting clipped
  106115. this.scene.add( this.quad );
  106116. this.textureMatrix = new Matrix4();
  106117. };
  106118. OutlinePass.prototype = Object.assign( Object.create( Pass.prototype ), {
  106119. constructor: OutlinePass,
  106120. dispose: function () {
  106121. this.renderTargetMaskBuffer.dispose();
  106122. this.renderTargetEdgeBuffer1.dispose();
  106123. this.renderTargetDepthBuffer.dispose();
  106124. },
  106125. replaceDepthToViewZ( camera ) {
  106126. var type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
  106127. if(type == this.lastCameraType )return
  106128. this.lastCameraType = type;
  106129. this.prepareMaskMaterial.fragmentShader = this.prepareMaskMaterial.fragmentShader.replace( /DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ' );
  106130. this.prepareMaskMaterial.needsUpdate = true;
  106131. },
  106132. setSize: function ( width, height ) {
  106133. this.renderTargetEdgeBuffer1.setSize( width, height );
  106134. this.renderTargetMaskBuffer.setSize( width, height );
  106135. this.resolution.set(width,height);
  106136. },
  106137. changeVisibilityOfSelectedObjects: function ( bVisible ) {
  106138. function gatherSelectedMeshesCallBack( object ) {
  106139. /* if ( object.isMesh ) { */
  106140. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  106141. /* if ( bVisible ) {
  106142. object.visible = object.userData.oldVisible;
  106143. delete object.userData.oldVisible;
  106144. } else {
  106145. object.userData.oldVisible = object.visible;
  106146. object.visible = bVisible;
  106147. } */
  106148. Potree.Utils.updateVisible(object, 'overlinePass', bVisible);
  106149. }
  106150. }
  106151. for ( var i = 0; i < this.selectedObjects.length; i ++ ) {
  106152. var selectedObject = this.selectedObjects[ i ];
  106153. selectedObject.traverse( gatherSelectedMeshesCallBack );
  106154. }
  106155. },
  106156. changeVisibilityOfNonSelectedObjects: function ( bVisible , scenes) {
  106157. var selectedMeshes = [];
  106158. function gatherSelectedMeshesCallBack( object ) {
  106159. //if ( object.isMesh ) selectedMeshes.push( object );
  106160. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  106161. selectedMeshes.push( object );
  106162. }
  106163. }
  106164. for ( var i = 0; i < this.selectedObjects.length; i ++ ) {
  106165. var selectedObject = this.selectedObjects[ i ];
  106166. selectedObject.traverse( gatherSelectedMeshesCallBack );
  106167. }
  106168. function VisibilityChangeCallBack( object ) {
  106169. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  106170. var bFound = false;
  106171. for ( var i = 0; i < selectedMeshes.length; i ++ ) {
  106172. var selectedObjectId = selectedMeshes[ i ].id;
  106173. if ( selectedObjectId === object.id ) {
  106174. bFound = true;
  106175. break;
  106176. }
  106177. }
  106178. if ( ! bFound ) {
  106179. var visibility = object.visible;
  106180. Potree.Utils.updateVisible(object, 'overlinePass', bVisible); //add
  106181. //但保不齐在设置为false后,渲染时又true了,所以在其他地方update时设置visible 得用updateVisible
  106182. if(!bVisible){
  106183. object.visible = false;
  106184. }else {
  106185. object.visible = !!object.bVisible;
  106186. }
  106187. object.bVisible = visibility;
  106188. //这两种updateVisible 和 visible 设置都不能去掉, 第一块是为了防止有的visible不是通过updateVisible设置的; 第二块是为了防止渲染时updateVisible又修改了visible为true, 另外渲染时
  106189. return {stopContinue:true} //for pointcloud
  106190. }
  106191. }
  106192. }
  106193. scenes.forEach(scene=>scene.traverse( VisibilityChangeCallBack ));
  106194. },
  106195. updateTextureMatrix: function (camera) {
  106196. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  106197. 0.0, 0.5, 0.0, 0.5,
  106198. 0.0, 0.0, 0.5, 0.5,
  106199. 0.0, 0.0, 0.0, 1.0 );
  106200. this.textureMatrix.multiply( camera.projectionMatrix );
  106201. this.textureMatrix.multiply( camera.matrixWorldInverse );
  106202. },
  106203. render: function (scenes, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun ) {
  106204. if(!(scenes instanceof Array))scenes = [scenes];
  106205. if ( this.selectedObjects.length > 0 && this.edgeStrength > 0) {
  106206. let render2 = (target, dontRenderRtEDL=true)=>{
  106207. if(renderFun){
  106208. renderFun({target , dontRenderRtEDL });
  106209. }else {
  106210. renderer.setRenderTarget(target);
  106211. renderer.clear();
  106212. scenes.forEach(scene=>renderer.render( scene, camera));
  106213. }
  106214. };
  106215. this.oldClearColor.copy( renderer.getClearColor(new Color) );
  106216. this.oldClearAlpha = renderer.getClearAlpha();
  106217. let oldAutoClear = renderer.autoClear;
  106218. let oldTarget = renderer.getRenderTarget();
  106219. renderer.autoClear = false;
  106220. if ( maskActive ) renderer.context.disable( renderer.context.STENCIL_TEST );
  106221. renderer.setClearColor( 0xffffff, 1 );
  106222. let oldBG = viewer.background, oldBgOpacity = viewer.backgroundOpacity;
  106223. viewer.background = new Color(1,1,1);
  106224. viewer.backgroundOpacity = 1;
  106225. if(this.showHiddenPart){ //几乎不会使用
  106226. viewports.forEach(e=>{
  106227. e.oldBeforeRender = e.beforeRender;
  106228. e.beforeRender = ()=>{
  106229. e.oldBeforeRender && e.oldBeforeRender();
  106230. this.replaceDepthToViewZ( e.camera );
  106231. };
  106232. });
  106233. // Make selected objects invisible
  106234. this.changeVisibilityOfSelectedObjects( false );
  106235. scenes.forEach(scene=>{
  106236. scene.currentBackground = scene.background;
  106237. scene.background = null;
  106238. // 1. Draw Non Selected objects in the depth buffer
  106239. scene.overrideMaterial = this.depthMaterial;
  106240. });
  106241. render2(this.renderTargetDepthBuffer);
  106242. // Make selected objects visible
  106243. this.changeVisibilityOfSelectedObjects( true );
  106244. viewports.forEach(e=>{
  106245. e.beforeRender = ()=>{
  106246. e.oldBeforeRender && e.oldBeforeRender();
  106247. // Update Texture Matrix for Depth compare
  106248. this.updateTextureMatrix(e.camera);
  106249. this.prepareMaskMaterial.uniforms[ "cameraNearFar" ].value = new Vector2( e.camera.near, e.camera.far );
  106250. };
  106251. });
  106252. }else {
  106253. //不渲染背景
  106254. scenes.forEach(scene=>{
  106255. scene.currentBackground = scene.background;
  106256. scene.background = null;
  106257. });
  106258. }
  106259. let colorType, colors = new Map() , opas = new Map();
  106260. {//绘制选中部分
  106261. // Make non selected objects invisible, and draw only the selected objects, by comparing the depth buffer of non selected objects
  106262. this.changeVisibilityOfNonSelectedObjects( false , scenes);
  106263. scenes.forEach(scene=>{
  106264. scene.overrideMaterial = this.prepareMaskMaterial;
  106265. });
  106266. if(this.showHiddenPart){
  106267. this.prepareMaskMaterial.uniforms[ "depthTexture" ].value = this.renderTargetDepthBuffer.texture;
  106268. this.prepareMaskMaterial.uniforms[ "textureMatrix" ].value = this.textureMatrix;
  106269. }
  106270. //因为点云不受prepareMaskMaterial作用,所以手动将他们变为黑色不透明
  106271. viewer.scene.pointclouds.forEach(e=>{ //先将点云透明度变为1,因为点云透明度莫名其妙会影响其r值//
  106272. colorType = e.material.activeAttributeName;
  106273. e.material.activeAttributeName = 'color';
  106274. colors.set(e, e.material.color);
  106275. e.material.color = '#000000';
  106276. opas.set(e, e.material.opacity);
  106277. e.material.opacity = 1;
  106278. });
  106279. }
  106280. render2(this.renderTargetMaskBuffer);
  106281. {//恢复
  106282. viewer.scene.pointclouds.forEach(e=>{
  106283. e.material.activeAttributeName = colorType;
  106284. e.material.color = colors.get(e);
  106285. e.material.opacity = opas.get(e);
  106286. });
  106287. if(this.showHiddenPart){
  106288. viewports.forEach((e)=>{e.beforeRender = e.oldBeforeRender;});
  106289. }
  106290. scenes.forEach(scene=>{
  106291. scene.overrideMaterial = null;
  106292. scene.background = scene.currentBackground;
  106293. });
  106294. viewer.background = oldBG;
  106295. viewer.backgroundOpacity = oldBgOpacity;
  106296. this.changeVisibilityOfNonSelectedObjects( true , scenes);
  106297. }
  106298. //检测边缘并绘制
  106299. // 3. Apply Edge Detection Pass
  106300. this.quad.material = this.edgeDetectionMaterial;
  106301. this.edgeDetectionMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture;//this.renderTargetMaskDownSampleBuffer.texture;
  106302. this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new Vector2(this.resolution.x, this.resolution.y );//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  106303. //this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new THREE.Vector2(this.renderTargetMaskBuffer.width, this.renderTargetMaskBuffer.height)//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  106304. this.edgeDetectionMaterial.uniforms[ "edgeStrength" ].value = this.edgeStrength;
  106305. this.edgeDetectionMaterial.uniforms[ "visibleEdgeColor" ].value = this.visibleEdgeColor;//this.tempPulseColor1;
  106306. this.edgeDetectionMaterial.uniforms[ "hiddenEdgeColor" ].value = this.hiddenEdgeColor; //this.tempPulseColor2;
  106307. let buffer;
  106308. if ( this.renderToScreen ) {
  106309. this.quad.material.transparent = true;
  106310. buffer = null;
  106311. renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
  106312. render2(null,false); //普通绘制原场景
  106313. //绘制到全屏
  106314. let renderSize = renderer.getSize(new Vector2()); //是client大小
  106315. renderer.setViewport(0, 0, renderSize.x, renderSize.y); //规定视口,影响图形变换(画布的使用范围)
  106316. renderer.setScissorTest( false );
  106317. }else {
  106318. buffer = readBuffer;
  106319. renderer.setClearColor( 0x000000, 0 );
  106320. renderer.clear();
  106321. }
  106322. renderer.setRenderTarget( buffer );
  106323. renderer.render( this.scene, this.camera ); //将边缘覆盖上去
  106324. renderer.setRenderTarget(oldTarget);
  106325. renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
  106326. renderer.autoClear = oldAutoClear;
  106327. return true
  106328. }
  106329. },
  106330. getPrepareMaskMaterial: function () {
  106331. if(this.showHiddenPart){
  106332. return new ShaderMaterial( {
  106333. uniforms: {
  106334. "depthTexture": { value: null },
  106335. "cameraNearFar": { value: new Vector2( 0.5, 0.5 ) },
  106336. "textureMatrix": { value: new Matrix4() }
  106337. },
  106338. vertexShader: [
  106339. 'varying vec4 projTexCoord;',
  106340. 'varying vec4 vPosition;',
  106341. 'uniform mat4 textureMatrix;',
  106342. 'void main() {',
  106343. ' vPosition = modelViewMatrix * vec4( position, 1.0 );',
  106344. ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
  106345. ' projTexCoord = textureMatrix * worldPosition;',
  106346. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  106347. '}'
  106348. ].join( '\n' ),
  106349. fragmentShader: [
  106350. '#include <packing>',
  106351. 'varying vec4 vPosition;',
  106352. 'varying vec4 projTexCoord;',
  106353. 'uniform sampler2D depthTexture;',
  106354. 'uniform vec2 cameraNearFar;',
  106355. 'void main() {',
  106356. ' float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord ));',
  106357. ' float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y );',
  106358. ' float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0;', //决定是否为hiddenPart
  106359. ' gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0);',
  106360. '}'
  106361. ].join( '\n' )
  106362. } );//没有绘制部分的颜色是clearColor,255
  106363. }else {
  106364. return new MeshBasicMaterial({color:'#000000'}) //不检测深度,不判断遮挡
  106365. }
  106366. },
  106367. getEdgeDetectionMaterial: function (edgeStrength) {
  106368. return new ShaderMaterial( {
  106369. uniforms: {
  106370. "edgeStrength": { value: edgeStrength },
  106371. "maskTexture": { value: null },
  106372. "texSize": { value: new Vector2( 10, 10 ) },
  106373. "visibleEdgeColor": { value: new Vector3( 1.0, 1.0, 1.0 ) },
  106374. "hiddenEdgeColor": { value: new Vector3( 1.0, 1.0, 1.0 ) },
  106375. },
  106376. vertexShader:
  106377. "varying vec2 vUv;\n\
  106378. void main() {\n\
  106379. vUv = uv;\n\
  106380. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  106381. }",
  106382. /* fragmentShader:
  106383. "varying vec2 vUv;\
  106384. uniform sampler2D maskTexture;\
  106385. uniform vec2 texSize;\
  106386. uniform vec3 visibleEdgeColor;\
  106387. uniform vec3 hiddenEdgeColor;\
  106388. \
  106389. void main() {\n\
  106390. vec2 invSize = 1.0 / texSize;\
  106391. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\
  106392. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\
  106393. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\
  106394. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\
  106395. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\
  106396. float diff1 = (c1.r - c2.r)*0.5;\
  106397. float diff2 = (c3.r - c4.r)*0.5;\
  106398. float d = length( vec2(diff1, diff2) );\
  106399. float a1 = min(c1.g, c2.g);\
  106400. float a2 = min(c3.g, c4.g);\
  106401. float visibilityFactor = min(a1, a2);\
  106402. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\
  106403. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);\
  106404. }" */
  106405. fragmentShader:
  106406. `varying vec2 vUv;
  106407. uniform sampler2D maskTexture;
  106408. uniform float edgeStrength;
  106409. uniform vec2 texSize;
  106410. uniform vec3 visibleEdgeColor;
  106411. uniform vec3 hiddenEdgeColor;
  106412. void main() {
  106413. const float thickness = 1.0;
  106414. vec2 invSize = thickness / texSize;
  106415. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);
  106416. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);
  106417. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);
  106418. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);
  106419. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);
  106420. float diff1 = (c1.r - c2.r)*0.5; //检测边缘,
  106421. float diff2 = (c3.r - c4.r)*0.5;
  106422. float d = length( vec2(diff1, diff2) ) * edgeStrength;
  106423. float a1 = min(c1.g, c2.g);
  106424. float a2 = min(c3.g, c4.g);
  106425. float visibilityFactor = min(a1, a2); //检测深度值,是否被遮挡
  106426. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;
  106427. //gl_FragColor = vec4(0.0,1.0,0.0,1.0);
  106428. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);
  106429. }`
  106430. } );
  106431. //为什么vec4(0.0,1.0,1.0,1.0); 显示出来的是rgb(109,255,255) ? 几乎只有绿色通道会影响红色通道
  106432. },
  106433. getSeperableBlurMaterial: function ( maxRadius ) {
  106434. return new ShaderMaterial( {
  106435. defines: {
  106436. "MAX_RADIUS": maxRadius,
  106437. },
  106438. uniforms: {
  106439. "colorTexture": { value: null },
  106440. "texSize": { value: new Vector2( 0.5, 0.5 ) },
  106441. "direction": { value: new Vector2( 0.5, 0.5 ) },
  106442. "kernelRadius": { value: 1.0 }
  106443. },
  106444. vertexShader:
  106445. "varying vec2 vUv;\n\
  106446. void main() {\n\
  106447. vUv = uv;\n\
  106448. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  106449. }",
  106450. fragmentShader:
  106451. "#include <common>\
  106452. varying vec2 vUv;\
  106453. uniform sampler2D colorTexture;\
  106454. uniform vec2 texSize;\
  106455. uniform vec2 direction;\
  106456. uniform float kernelRadius;\
  106457. \
  106458. float gaussianPdf(in float x, in float sigma) {\
  106459. return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\
  106460. }\
  106461. void main() {\
  106462. vec2 invSize = 1.0 / texSize;\
  106463. float weightSum = gaussianPdf(0.0, kernelRadius);\
  106464. vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\
  106465. vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS);\
  106466. vec2 uvOffset = delta;\
  106467. for( int i = 1; i <= MAX_RADIUS; i ++ ) {\
  106468. float w = gaussianPdf(uvOffset.x, kernelRadius);\
  106469. vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\
  106470. vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\
  106471. diffuseSum += ((sample1 + sample2) * w);\
  106472. weightSum += (2.0 * w);\
  106473. uvOffset += delta;\
  106474. }\
  106475. gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\
  106476. }"
  106477. } );
  106478. },
  106479. getOverlayMaterial: function () {//对边缘线进一步处理,已被废弃
  106480. return new ShaderMaterial( {
  106481. uniforms: {
  106482. "maskTexture": { value: null },
  106483. "edgeTexture1": { value: null },
  106484. "edgeTexture2": { value: null },
  106485. "patternTexture": { value: null },
  106486. "edgeStrength": { value: 1.0 },
  106487. "edgeGlow": { value: 1.0 },
  106488. "usePatternTexture": { value: 0.0 }
  106489. },
  106490. vertexShader:
  106491. "varying vec2 vUv;\n\
  106492. void main() {\n\
  106493. vUv = uv;\n\
  106494. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  106495. }",
  106496. /* fragmentShader:
  106497. "varying vec2 vUv;\
  106498. uniform sampler2D maskTexture;\
  106499. uniform sampler2D edgeTexture1;\
  106500. uniform sampler2D edgeTexture2;\
  106501. uniform sampler2D patternTexture;\
  106502. uniform float edgeStrength;\
  106503. uniform float edgeGlow;\
  106504. uniform bool usePatternTexture;\
  106505. \
  106506. void main() {\
  106507. vec4 edgeValue1 = texture2D(edgeTexture1, vUv);\
  106508. vec4 edgeValue2 = texture2D(edgeTexture2, vUv);\
  106509. vec4 maskColor = texture2D(maskTexture, vUv);\
  106510. vec4 patternColor = texture2D(patternTexture, 6.0 * vUv);\
  106511. float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;\
  106512. vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow;\
  106513. vec4 finalColor = edgeStrength * maskColor.r * edgeValue;\ // 删除 * maskColor.r 也就是去掉遮罩,使模型部分也有outline
  106514. if(usePatternTexture)\
  106515. finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r);\
  106516. gl_FragColor = finalColor;\
  106517. }", */
  106518. fragmentShader:
  106519. `varying vec2 vUv;
  106520. uniform sampler2D edgeTexture1;
  106521. uniform float edgeStrength;
  106522. void main() {
  106523. gl_FragColor = edgeStrength * texture2D(edgeTexture1, vUv);
  106524. }`,
  106525. blending: AdditiveBlending,
  106526. depthTest: false,
  106527. depthWrite: false,
  106528. transparent: true
  106529. } );
  106530. }
  106531. } );
  106532. OutlinePass.BlurDirectionX = new Vector2( 1.0, 0.0 );
  106533. OutlinePass.BlurDirectionY = new Vector2( 0.0, 1.0 );
  106534. /*
  106535. 渲染步骤:(没有showHiddenPart时)
  106536. 仅绘制选中部分,材质为普通的单色材质,颜色是黑色不透明。未绘制部分的clearColor是白色不透明。
  106537. (详见prepareMaskMaterial,输出的r要为0)
  106538. 然后在上面绘制的图中,根据r的差值,得到边缘线。
  106539. 正常绘制场景之后,将上面的边缘线覆盖于其上。
  106540. (如果showHiddenPart,最开始还要先隐藏选中部分,这是为了得到非选中部分的深度值,然后再绘制选中部分时去比较选中和非选中部分之间的深度差异。以判断是否被遮挡。)
  106541. */
  106542. /**
  106543. * @author mschuetz / http://mschuetz.at
  106544. *
  106545. * adapted from THREE.OrbitControls by
  106546. *
  106547. * @author qiao / https://github.com/qiao
  106548. * @author mrdoob / http://mrdoob.com
  106549. * @author alteredq / http://alteredqualia.com/
  106550. * @author WestLangley / http://github.com/WestLangley
  106551. * @author erich666 / http://erichaines.com
  106552. *
  106553. *
  106554. *
  106555. */
  106556. let minRadius = 2;
  106557. class OrbitControls extends EventDispatcher{
  106558. constructor(viewer, viewport){
  106559. super();
  106560. this.viewer = viewer;
  106561. this.renderer = viewer.renderer;
  106562. this.scene = null;
  106563. this.sceneControls = new Scene();
  106564. this.rotationSpeed = 3; //旋转速度
  106565. viewport = viewport || viewer.viewports[0];
  106566. this.setCurrentViewport({hoverViewport:viewport, force:true}); //this.currentViewport = viewport
  106567. this.fadeFactor = 20;
  106568. this.yawDelta = 0;
  106569. this.pitchDelta = 0;
  106570. this.panDelta = new Vector2(0, 0);
  106571. this.radiusDelta = 0;
  106572. this.doubleClockZoomEnabled = true;
  106573. this.tweens = [];
  106574. this.dollyStart = new Vector2;
  106575. this.dollyEnd = new Vector2;
  106576. this.keys = {
  106577. FORWARD: ['W'.charCodeAt(0), 38],
  106578. BACKWARD: ['S'.charCodeAt(0), 40],
  106579. LEFT: ['A'.charCodeAt(0), 37],
  106580. RIGHT: ['D'.charCodeAt(0), 39],
  106581. UP: ['Q'.charCodeAt(0)],
  106582. DOWN: ['E'.charCodeAt(0)],
  106583. };
  106584. let drag = (e) => {
  106585. if(!this.enabled)return
  106586. let viewport = e.dragViewport;
  106587. if(!viewport /* || viewport.camera.type == "OrthographicCamera" */)return
  106588. //let camera = viewport.camera
  106589. if (e.drag.object !== null) {
  106590. return;
  106591. }
  106592. let mode;
  106593. if(e.isTouch){
  106594. if(e.touches.length == 1){
  106595. mode = 'rotate';
  106596. }else {
  106597. mode = 'scale-pan';
  106598. }
  106599. }else {
  106600. mode = e.buttons === Potree.defines.Buttons.LEFT ? 'rotate' : 'pan';
  106601. }
  106602. if (e.drag.startHandled === undefined) {
  106603. e.drag.startHandled = true;
  106604. this.dispatchEvent({type: 'start'});
  106605. }
  106606. let ndrag = e.drag.pointerDelta.clone();//.add(new THREE.Vector2(1,1)).multiplyScalar(0.5)
  106607. ndrag.y *= -1;
  106608. if (mode == 'rotate') {
  106609. this.yawDelta += ndrag.x * this.rotationSpeed;
  106610. this.pitchDelta += ndrag.y * this.rotationSpeed;
  106611. } else if(mode == 'pan'){
  106612. this.panDelta.x += ndrag.x;
  106613. this.panDelta.y += ndrag.y;
  106614. }else if(mode == 'scale-pan'){ //add
  106615. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  106616. var scale = this.dollyEnd.length() / this.dollyStart.length();
  106617. this.dollyStart.copy(this.dollyEnd);
  106618. this.radiusDelta = (1-scale) * this.currentViewport.view.radius;
  106619. //------------------------
  106620. //平移
  106621. let pointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  106622. let delta = new Vector2().subVectors(pointer, this.lastScalePointer);
  106623. delta.y *= -1;
  106624. this.panDelta.add(delta);
  106625. this.lastScalePointer = pointer.clone();
  106626. //console.log('scale ',scale, this.radiusDelta)
  106627. }
  106628. this.stopTweens();
  106629. };
  106630. let drop = e => {
  106631. if(!this.enabled)return
  106632. this.dispatchEvent({type: 'end'});
  106633. };
  106634. let scroll = (e) => {
  106635. if(!this.enabled)return
  106636. let resolvedRadius = this.currentViewport.view.radius + this.radiusDelta;
  106637. if(resolvedRadius < 0.1 && e.delta>0)return; //防止缩放太小,导致很慢
  106638. this.radiusDelta += -e.delta * resolvedRadius * 0.1;
  106639. this.stopTweens();
  106640. };
  106641. let dblclick = (e) => {
  106642. if(!this.enabled)return
  106643. if(this.doubleClockZoomEnabled){
  106644. this.zoomToLocation(e.mouse);
  106645. }
  106646. };
  106647. let previousTouch = null;
  106648. let touchStart = e => {
  106649. previousTouch = e;
  106650. };
  106651. let touchEnd = e => {
  106652. previousTouch = e;
  106653. };
  106654. let touchMove = e => {
  106655. if(!this.enabled)return
  106656. if (e.touches.length === 2 && previousTouch.touches.length === 2){
  106657. let prev = previousTouch;
  106658. let curr = e;
  106659. let prevDX = prev.touches[0].pageX - prev.touches[1].pageX;
  106660. let prevDY = prev.touches[0].pageY - prev.touches[1].pageY;
  106661. let prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY);
  106662. let currDX = curr.touches[0].pageX - curr.touches[1].pageX;
  106663. let currDY = curr.touches[0].pageY - curr.touches[1].pageY;
  106664. let currDist = Math.sqrt(currDX * currDX + currDY * currDY);
  106665. let delta = currDist / prevDist;
  106666. let resolvedRadius = this.currentViewport.view.radius + this.radiusDelta;
  106667. let newRadius = resolvedRadius / delta;
  106668. this.radiusDelta = newRadius - resolvedRadius;
  106669. this.stopTweens();
  106670. }else if(e.touches.length === 3 && previousTouch.touches.length === 3){
  106671. let prev = previousTouch;
  106672. let curr = e;
  106673. let prevMeanX = (prev.touches[0].pageX + prev.touches[1].pageX + prev.touches[2].pageX) / 3;
  106674. let prevMeanY = (prev.touches[0].pageY + prev.touches[1].pageY + prev.touches[2].pageY) / 3;
  106675. let currMeanX = (curr.touches[0].pageX + curr.touches[1].pageX + curr.touches[2].pageX) / 3;
  106676. let currMeanY = (curr.touches[0].pageY + curr.touches[1].pageY + curr.touches[2].pageY) / 3;
  106677. let delta = {
  106678. x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth,
  106679. y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight
  106680. };
  106681. this.panDelta.x += delta.x;
  106682. this.panDelta.y += delta.y;
  106683. this.stopTweens();
  106684. }
  106685. previousTouch = e;
  106686. };
  106687. this.addEventListener('touchstart', touchStart);
  106688. this.addEventListener('touchend', touchEnd);
  106689. this.addEventListener('touchmove', touchMove);
  106690. this.viewer.addEventListener('global_drag', drag);
  106691. this.viewer.addEventListener('global_drop', drop);
  106692. this.viewer.addEventListener('global_mousewheel', scroll);
  106693. this.viewer.addEventListener('global_dblclick', dblclick);
  106694. this.viewer.addEventListener('global_touchmove', (e)=>{
  106695. if(e.touches.length>1){//单指的就触发上一句
  106696. //console.log('global_touchmove' )
  106697. drag(e);
  106698. }
  106699. });
  106700. let prepareScale = (e)=>{//触屏的scale
  106701. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  106702. this.lastScalePointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  106703. };
  106704. this.viewer.addEventListener('global_touchstart', (e)=>{
  106705. if(this.enabled && e.touches.length==2){//只监听开头两个指头
  106706. prepareScale(e);
  106707. }
  106708. });
  106709. /* this.viewer.addEventListener('global_touchend', (e)=>{
  106710. if(!this.enabled)return
  106711. if(e.touches.length==1){//停止scale,开始rotate
  106712. prepareRotate(e)
  106713. //this.pointerDragStart = null
  106714. //console.log('只剩一个', e.pointer.toArray())
  106715. }
  106716. }) */
  106717. this.viewer.addEventListener('focusOnObject',(o)=>{
  106718. if(o.position && o.CamTarget){
  106719. let distance = o.position.distanceTo(o.CamTarget);
  106720. if(distance < minRadius) minRadius = distance * 0.5; //融合页面当focus一个很小的物体时,需要将minRadius也调小
  106721. }
  106722. });
  106723. }
  106724. setScene (scene) {
  106725. this.scene = scene;
  106726. }
  106727. setCurrentViewport(o={}){//add
  106728. if(!this.enabled && !o.force )return
  106729. if(o.hoverViewport && this.currentViewport != o.hoverViewport ){
  106730. this.currentViewport = o.hoverViewport;
  106731. }
  106732. }
  106733. setEnable(enabled){
  106734. this.enabled = enabled;
  106735. }
  106736. stop(){
  106737. this.yawDelta = 0;
  106738. this.pitchDelta = 0;
  106739. this.radiusDelta = 0;
  106740. this.panDelta.set(0, 0);
  106741. }
  106742. /* zoomToLocation(mouse){
  106743. if(!this.enabled)return
  106744. let camera = this.scene.getActiveCamera();
  106745. let I = Utils.getMousePointCloudIntersection(
  106746. null, mouse, this.viewer.inputHandler.pointer,
  106747. camera,
  106748. this.viewer,
  106749. this.scene.pointclouds,
  106750. {pickClipped: true});
  106751. if (I === null) {
  106752. return;
  106753. }
  106754. let targetRadius = 0;
  106755. {
  106756. let minimumJumpDistance = 0.2;
  106757. let domElement = this.renderer.domElement;
  106758. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer , camera, domElement.clientWidth, domElement.clientHeight);
  106759. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  106760. let lastNode = nodes[nodes.length - 1];
  106761. let radius = lastNode.getBoundingSphere(new THREE.Sphere()).radius;
  106762. targetRadius = Math.min(this.currentViewport.view.radius, radius);
  106763. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  106764. }
  106765. let d = this.currentViewport.view.direction.multiplyScalar(-1);
  106766. let cameraTargetPosition = new THREE.Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  106767. // TODO Unused: let controlsTargetPosition = I.location;
  106768. let animationDuration = 600;
  106769. let easing = TWEEN.Easing.Quartic.Out;
  106770. { // animate
  106771. let value = {x: 0};
  106772. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  106773. tween.easing(easing);
  106774. this.tweens.push(tween);
  106775. let startPos = this.currentViewport.view.position.clone();
  106776. let targetPos = cameraTargetPosition.clone();
  106777. let startRadius = this.currentViewport.view.radius;
  106778. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  106779. tween.onUpdate(() => {
  106780. let t = value.x;
  106781. this.currentViewport.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  106782. this.currentViewport.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  106783. this.currentViewport.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  106784. this.currentViewport.view.radius = (1 - t) * startRadius + t * targetRadius;
  106785. this.viewer.setMoveSpeed(this.currentViewport.view.radius);
  106786. });
  106787. tween.onComplete(() => {
  106788. this.tweens = this.tweens.filter(e => e !== tween);
  106789. });
  106790. tween.start();
  106791. }
  106792. } */
  106793. zoomToLocation(mouse){
  106794. let I = viewer.inputHandler.intersect;
  106795. if(!I)return
  106796. let object = I.object || I.pointcloud;
  106797. I = I.location;
  106798. if(!I || !object)return;
  106799. let dis = this.currentViewport.view.position.distanceTo(I);
  106800. let bound = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  106801. let size = bound.getSize(new Vector3);
  106802. let len = size.length();
  106803. let distance = MathUtils.clamp(dis, 0.1, Math.max(len * 0.1, 3) );
  106804. minRadius = distance;
  106805. viewer.focusOnObject({ position:I }, 'point', null, {distance});
  106806. }
  106807. stopTweens () {
  106808. this.tweens.forEach(e => e.stop());
  106809. this.tweens = [];
  106810. }
  106811. update (delta) {
  106812. if(!this.enabled)return
  106813. let view = this.currentViewport.view;//this.currentViewport.view;
  106814. let camera = this.currentViewport.camera;
  106815. { // accelerate while input is given
  106816. let ih = this.viewer.inputHandler;
  106817. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  106818. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  106819. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  106820. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  106821. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  106822. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  106823. let px = 0 , py = 0, pz = 0;
  106824. if(moveForward){
  106825. py = 1;
  106826. }else if(moveBackward){
  106827. py = -1;
  106828. }
  106829. if(moveLeft){
  106830. px = -1;
  106831. }else if(moveRight){
  106832. px = 1;
  106833. }
  106834. if(moveUp){
  106835. pz = 1;
  106836. }else if(moveDown){
  106837. pz = -1;
  106838. }
  106839. (px!=0 || py!=0 || pz!=0) && view.translate(px, py, pz, true);
  106840. }
  106841. { // apply rotation
  106842. let progression = Math.min(1, this.fadeFactor * delta);
  106843. let yaw = view.yaw;
  106844. let pitch = view.pitch;
  106845. let pivot = view.getPivot();
  106846. yaw -= progression * this.yawDelta;
  106847. pitch -= progression * this.pitchDelta;
  106848. view.yaw = yaw;
  106849. view.pitch = pitch;
  106850. let V = this.currentViewport.view.direction.multiplyScalar(-view.radius);
  106851. let position = new Vector3().addVectors(pivot, V);
  106852. view.position.copy(position);
  106853. }
  106854. if(camera.type != 'OrthographicCamera'){ // apply pan
  106855. /* let progression = Math.min(1, this.fadeFactor * delta);
  106856. let panDistance = progression * view.radius * 3; */
  106857. let panDistance = 2 * view.radius * Math.tan(MathUtils.degToRad(camera.fov / 2));//参照4dkk。 平移target(也就是平移镜头位置),但还是难以保证跟手(navvis也不一定跟手,但是很奇怪在居中时中心点居然是跟手的,可能计算方式不同)
  106858. //计算了下确实是这么算的。 平移pivot。
  106859. let px = -this.panDelta.x * panDistance;
  106860. let py = this.panDelta.y * panDistance;
  106861. view.pan(px, py);
  106862. }
  106863. { // apply zoom
  106864. let progression = 1;//Math.min(1, this.fadeFactor * delta);
  106865. // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1;
  106866. let radius = view.radius + progression * this.radiusDelta;
  106867. let V = view.direction.multiplyScalar(-radius);
  106868. let position = new Vector3().addVectors(view.getPivot(), V);
  106869. if(this.constantlyForward) {// 到达中心点后还能继续向前移动,也就是能推进中心点
  106870. if(radius < minRadius){
  106871. radius = minRadius;
  106872. }
  106873. }
  106874. view.radius = radius;
  106875. view.position.copy(position);
  106876. }
  106877. {
  106878. let speed = view.radius;
  106879. this.viewer.setMoveSpeed && this.viewer.setMoveSpeed(speed);
  106880. }
  106881. { // decelerate over time
  106882. /* let progression = Math.min(1, this.fadeFactor * delta);
  106883. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  106884. this.yawDelta *= attenuation;
  106885. this.pitchDelta *= attenuation;
  106886. this.panDelta.multiplyScalar(attenuation);
  106887. // this.radiusDelta *= attenuation;
  106888. this.radiusDelta -= progression * this.radiusDelta; */
  106889. //取消衰减,直接stop
  106890. this.stop();
  106891. }
  106892. }
  106893. };
  106894. // Adapted from three.js VRButton
  106895. class VRButton {
  106896. constructor(){
  106897. this.onStartListeners = [];
  106898. this.onEndListeners = [];
  106899. this.element = null;
  106900. }
  106901. onStart(callback){
  106902. this.onStartListeners.push(callback);
  106903. }
  106904. onEnd(callback){
  106905. this.onEndListeners.push(callback);
  106906. }
  106907. static async createButton( renderer, options ) {
  106908. if ( options ) {
  106909. console.error( 'THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.' );
  106910. }
  106911. const button = new VRButton();
  106912. const element = document.createElement( 'button' );
  106913. button.element = element;
  106914. function setEnter(){
  106915. button.element.innerHTML = `
  106916. <div style="font-size: 0.5em;">ENTER</div>
  106917. <div style="font-weight: bold;">VR</div>
  106918. `;
  106919. }
  106920. function setExit(){
  106921. button.element.innerHTML = `
  106922. <div style="font-size: 0.5em;">EXIT</div>
  106923. <div style="font-weight: bold;">VR</div>
  106924. `;
  106925. }
  106926. function showEnterVR( /*device*/ ) {
  106927. let currentSession = null;
  106928. function onSessionStarted( session ) {
  106929. session.addEventListener( 'end', onSessionEnded );
  106930. for(let listener of button.onStartListeners){
  106931. listener();
  106932. }
  106933. renderer.xr.setSession( session );
  106934. setExit();
  106935. currentSession = session;
  106936. }
  106937. function onSessionEnded( /*event*/ ) {
  106938. currentSession.removeEventListener( 'end', onSessionEnded );
  106939. for(let listener of button.onEndListeners){
  106940. listener();
  106941. }
  106942. setEnter();
  106943. currentSession = null;
  106944. }
  106945. //
  106946. button.element.style.display = '';
  106947. button.element.style.cursor = 'pointer';
  106948. setEnter();
  106949. button.element.onmouseenter = function () {
  106950. button.element.style.opacity = '1.0';
  106951. };
  106952. button.element.onmouseleave = function () {
  106953. button.element.style.opacity = '0.7';
  106954. };
  106955. button.element.onclick = function () {
  106956. if ( currentSession === null ) {
  106957. // WebXR's requestReferenceSpace only works if the corresponding feature
  106958. // was requested at session creation time. For simplicity, just ask for
  106959. // the interesting ones as optional features, but be aware that the
  106960. // requestReferenceSpace call will fail if it turns out to be unavailable.
  106961. // ('local' is always available for immersive sessions and doesn't need to
  106962. // be requested separately.)
  106963. const sessionInit = { optionalFeatures: [ 'local-floor', 'bounded-floor', 'hand-tracking' ] };
  106964. navigator.xr.requestSession( 'immersive-vr', sessionInit ).then( onSessionStarted );
  106965. } else {
  106966. currentSession.end();
  106967. }
  106968. };
  106969. }
  106970. function stylizeElement( element ) {
  106971. element.style.position = 'absolute';
  106972. element.style.bottom = '20px';
  106973. element.style.padding = '12px 6px';
  106974. element.style.border = '1px solid #fff';
  106975. element.style.borderRadius = '4px';
  106976. element.style.background = 'rgba(0,0,0,0.1)';
  106977. element.style.color = '#fff';
  106978. element.style.font = 'normal 13px sans-serif';
  106979. element.style.textAlign = 'center';
  106980. element.style.opacity = '0.7';
  106981. element.style.outline = 'none';
  106982. element.style.zIndex = '999';
  106983. }
  106984. if ( 'xr' in navigator ) {
  106985. button.element.id = 'VRButton';
  106986. button.element.style.display = 'none';
  106987. stylizeElement( button.element );
  106988. let supported = await navigator.xr.isSessionSupported( 'immersive-vr' );
  106989. if(supported){
  106990. showEnterVR();
  106991. return button;
  106992. }else {
  106993. return null;
  106994. }
  106995. } else {
  106996. if ( window.isSecureContext === false ) {
  106997. console.log("WEBXR NEEDS HTTPS");
  106998. } else {
  106999. console.log("WEBXR not available");
  107000. }
  107001. return null;
  107002. }
  107003. }
  107004. }
  107005. const manager = new LoadingManager();
  107006. let loaders = {};
  107007. let mapArea;
  107008. let shelterHistory = [];
  107009. Potree.isIframeChild = window.parent!=window; //子页面
  107010. /* if(Potree.isIframeChild){
  107011. let rootWin = Common.getRootWindow()
  107012. rootWin && rootWin.viewer.dispatchEvent({type:'createIframe', window}) //给祖先页面发送信息,得不到可能跨域了或无viewer
  107013. } */
  107014. /* window.addEventListener('focus',()=>{
  107015. console.log('focus',window.winIndex)
  107016. })
  107017. window.addEventListener('blur',()=>{
  107018. console.log('blur',window.winIndex)
  107019. }) */
  107020. class Viewer extends ViewerBase{
  107021. constructor(domElement, mapArea_, args = {}){
  107022. super(domElement, $.extend(args,{name:'mainViewer', antialias:true, preserveDrawingBuffer:true}));
  107023. //注:viewer因为要分屏,尤其是四屏,preserveDrawingBuffer需要为true, 否则无法局部clear
  107024. window.viewer = this;
  107025. mapArea = mapArea_;
  107026. if(Potree.settings.editType == "pano" || Potree.settings.editType == "merge"){
  107027. this.modules = {
  107028. Alignment,
  107029. SiteModel
  107030. };
  107031. Potree.settings.useDepthTex = false;
  107032. if(Potree.settings.editType == "pano" ){
  107033. this.modules.PanoEditor = PanoEditor$1;
  107034. }else if(Potree.settings.editType == "merge"){
  107035. this.modules.MergeEditor = MergeEditor;
  107036. this.modules.CamAniEditor = CamAniEditor;
  107037. }
  107038. }else {
  107039. this.modules = {
  107040. Clip,
  107041. Alignment,
  107042. SiteModel,
  107043. RouteGuider : new RouteGuider,
  107044. clipping: new Clipping,
  107045. ParticleEditor,
  107046. CamAniEditor,
  107047. };
  107048. }
  107049. {
  107050. Potree.timeCollect = {
  107051. //median预置一个中等值,以防止cpu过低的设备首次卡顿
  107052. //depthSampler : {minCount:400, median: 1}, //旧的 实时从图片中获取色值的用时,但是现在直接从data中取
  107053. depthSamChangeImg:{minCount:200, median: 25} //换图的用时。 需要一开始就start
  107054. };
  107055. for(let i in Potree.timeCollect){
  107056. Potree.timeCollect[i].measures = [];
  107057. Potree.timeCollect[i].sum = 0;
  107058. }
  107059. setTimeout(()=>{
  107060. for(let i in Potree.timeCollect){
  107061. Potree.timeCollect[i].start = true;
  107062. }
  107063. /* setTimeout(()=>{
  107064. console.log('timeCollect', Potree.timeCollect.depthSampler.median, Potree.timeCollect.depthSampler.ave, Potree.timeCollect.depthSampler.measures.length)
  107065. },10000) */
  107066. },2000);
  107067. }
  107068. this.navigateMode = 'free'; // 'panorama'; 'free'自由模式是只显示点云或者未进入到漫游点,
  107069. this.isEdit = true;
  107070. this.waitQueue = [];
  107071. this.unitConvert = new UoMService();
  107072. this.visible = true;
  107073. this.fpVisiDatasets = [];
  107074. this.atDatasets = [];
  107075. this.objs = new Object3D;
  107076. this.testMaxNodeCount = 0;
  107077. this.tiles3dVisiVCount = 0;
  107078. //this.lastPos = new THREE.Vector3(Infinity,Infinity,Infinity)
  107079. //-------------
  107080. var supportExtFragDepth = !!Potree.Features.EXT_DEPTH.isSupported(this.renderer.getContext()) ;//iphoneX居然不支持
  107081. //这意味着边缘增强和测量线遮挡失效
  107082. if(!supportExtFragDepth)console.error('ExtFragDepth unsupported! 边缘增强和测量线遮挡失效');
  107083. this.guiLoaded = false;
  107084. this.guiLoadTasks = [];
  107085. this.onVrListeners = [];
  107086. this.messages = [];
  107087. this.elMessages = $(`
  107088. <div id="message_listing"
  107089. style="position: absolute; z-index: 1000; left: 10px; bottom: 10px">
  107090. </div>`);
  107091. $(domElement).append(this.elMessages);
  107092. this.fakeMeasure = {};
  107093. try{
  107094. if(!Potree.settings.isOfficial)
  107095. { // generate missing dom hierarchy
  107096. if ($(domElement).find('#potree_map').length === 0) {
  107097. let potreeMap = $(`
  107098. <div id="potree_map" class="mapBox" style="position: absolute; left: 50px; top: 50px; width: 400px; height: 400px; display: none">
  107099. <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;">
  107100. </div>
  107101. <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>
  107102. </div>
  107103. `);
  107104. $(domElement).append(potreeMap);
  107105. }
  107106. if ($(domElement).find('#potree_description').length === 0) {
  107107. let potreeDescription = $(`<div id="potree_description" class="potree_info_text"></div>`);
  107108. $(domElement).append(potreeDescription);
  107109. }
  107110. if ($(domElement).find('#potree_annotations').length === 0) {
  107111. let potreeAnnotationContainer = $(`
  107112. <div id="potree_annotation_container"
  107113. style="position: absolute; z-index: 100000; width: 100%; height: 100%; pointer-events: none;"></div>`);
  107114. $(domElement).append(potreeAnnotationContainer);
  107115. }
  107116. if ($(domElement).find('#potree_quick_buttons').length === 0) {
  107117. let potreeMap = $(`
  107118. <div id="potree_quick_buttons" class="quick_buttons_container" style="">
  107119. </div>
  107120. `);
  107121. $(domElement).append(potreeMap);
  107122. }
  107123. //add
  107124. {
  107125. if(!mapArea && Potree.settings.editType != 'merge'){
  107126. $(domElement).append($("<div id='potree_labels'></div>"));
  107127. mapArea = $("<div id='mapGaode'></div>");
  107128. $(domElement).append(mapArea);
  107129. mapArea = mapArea[0];
  107130. }
  107131. }
  107132. /* let domRoot = this.renderer.domElement.parentElement;
  107133. let elAttach = $("<input type='button' value='test'></input>");
  107134. elAttach.css({
  107135. position : "absolute",
  107136. right : '10%',
  107137. bottom: '20px',
  107138. zIndex: "10000",
  107139. fontSize:'1em', color:"black",
  107140. background:'rgba(255,255,255,0.8)',
  107141. })
  107142. let state = false
  107143. elAttach.on("click", () => {
  107144. window.buttonFunction && window.buttonFunction()
  107145. });
  107146. domRoot.appendChild(elAttach[0]); */
  107147. }
  107148. this.tiles3dMemoryUsage = 0;
  107149. this.pointCloudLoadedCallback = args.onPointCloudLoaded || function () {};
  107150. // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  107151. // defaultSettings.navigation = "Orbit";
  107152. // }
  107153. this.server = null;
  107154. this.fov = 60;
  107155. this.isFlipYZ = false;
  107156. this.useDEMCollisions = false;
  107157. this.generateDEM = false;
  107158. this.minNodeSize = 30; //允许加载的node的最小可见像素宽度。越大越省性能
  107159. this.edlStrength = 1.0;
  107160. this.edlRadius = 1.4;
  107161. this.edlOpacity = 1.0;
  107162. this.useEDL = false;
  107163. this.description = "";
  107164. this.classifications = ClassificationScheme.DEFAULT;
  107165. this.moveSpeed = 1;
  107166. this.lengthUnit = LengthUnits.METER;
  107167. this.lengthUnitDisplay = LengthUnits.METER;
  107168. this.showBoundingBox = false;
  107169. this.showAnnotations = true;
  107170. this.freeze = false;
  107171. this.elevationGradientRepeat = ElevationGradientRepeat.CLAMP;
  107172. this.filterReturnNumberRange = [0, 7];
  107173. this.filterNumberOfReturnsRange = [0, 7];
  107174. this.filterGPSTimeRange = [-Infinity, Infinity];
  107175. this.filterPointSourceIDRange = [0, 65535];
  107176. this.potreeRenderer = null;
  107177. this.edlRenderer = null;
  107178. this.pRenderer = null;
  107179. this.scene = null;
  107180. this.sceneVR = null;
  107181. this.overlay = null;
  107182. this.overlayCamera = null;
  107183. this.inputHandler = null;
  107184. this.controls = null;
  107185. this.clippingTool = null;
  107186. this.transformationTool = null;
  107187. this.navigationCube = null;
  107188. this.compass = null;
  107189. this.skybox = null;
  107190. this.clock = new Clock();
  107191. this.background = null;
  107192. this.buffers = new Map;
  107193. if(args.noDragAndDrop){
  107194. }else {
  107195. this.initDragAndDrop();
  107196. }
  107197. if(typeof Stats !== "undefined"){
  107198. this.stats = new Stats();
  107199. this.stats.showPanel( 0 ); // 0: fps, 1: ms, 2: mb, 3+: custom
  107200. document.body.appendChild( this.stats.dom );
  107201. }
  107202. {
  107203. this.overlay = new Scene();
  107204. this.overlayCamera = new OrthographicCamera(
  107205. 0, 1,
  107206. 1, 0,
  107207. -1000, 1000
  107208. );
  107209. }
  107210. this.pRenderer = new Renderer$1(this.renderer);
  107211. {
  107212. let near = 2.5;
  107213. let far = 10.0;
  107214. let fov = 90;
  107215. this.shadowTestCam = new PerspectiveCamera(90, 1, near, far);
  107216. this.shadowTestCam.position.set(3.50, -2.80, 8.561);
  107217. this.shadowTestCam.lookAt(new Vector3(0, 0, 4.87));
  107218. }
  107219. let scene = new ExtendScene(this.renderer);
  107220. { // create VR scene
  107221. this.sceneVR = new Scene();
  107222. // let texture = new THREE.TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  107223. // let plane = new THREE.PlaneBufferGeometry(1, 1, 1, 1);
  107224. // let infoMaterial = new THREE.MeshBasicMaterial({map: texture});
  107225. // let infoNode = new THREE.Mesh(plane, infoMaterial);
  107226. // infoNode.position.set(-0.5, 1, 0);
  107227. // infoNode.scale.set(0.4, 0.3, 1);
  107228. // infoNode.lookAt(0, 1, 0)
  107229. // this.sceneVR.add(infoNode);
  107230. // window.infoNode = infoNode;
  107231. }
  107232. this.setScene(scene);
  107233. //add: for 截图时抗锯齿
  107234. {
  107235. /* this.composer = new EffectComposer( this.renderer );
  107236. this.ssaaRenderPass = new SSAARenderPass(0x000000, 0);
  107237. this.composer.addPass( this.ssaaRenderPass );
  107238. */
  107239. //this.ssaaRenderPass.useCopy = true
  107240. //this.ssaaRenderPass.renderToScreen = true;
  107241. //this.ssaaRenderPass.needsSwap = false
  107242. //见 https://threejs.org/examples/?q=AA#webgl_postprocessing_fxaa 效果和SSAA差不多,都对透明不太友好。
  107243. /* let outlinePass = this.outlinePass = new OutlinePass( );
  107244. this.ssaaRenderPass.addPass(outlinePass)
  107245. */
  107246. //ssaa有透明度、发黑的问题所以不用了
  107247. //--------------------------
  107248. this.composer = new EffectComposer( this.renderer );
  107249. this.composer.scaleRatio = 4; //将底图和测量线绘制在一张高倍贴图上,for测量线不模糊
  107250. this.composer.readTarget = true; //把底图和测量线一起fxaa
  107251. /* const renderPass = new RenderPass();
  107252. //renderPass.clearColor = new THREE.Color( 0,0,0 );
  107253. //renderPass.clearAlpha = 0;
  107254. renderPass.clear = !this.composer.readTarget
  107255. this.composer.addPass( renderPass );
  107256. */
  107257. //for 融合页面
  107258. let outlinePass = this.outlinePass = new OutlinePass( );
  107259. outlinePass.renderToScreen = true; //这样更流畅,不用ssaa了,缺点是outline有锯齿
  107260. outlinePass.enabled = false;
  107261. this.composer.addPass( outlinePass );
  107262. outlinePass.edgeStrength = 4;
  107263. outlinePass.edgeGlow = 0;
  107264. outlinePass.visibleEdgeColor = new Color("#09a1b3");
  107265. /* this.fxaaPass = new ShaderPass( FXAAShader );
  107266. this.fxaaPass.readTarget = true //add
  107267. this.fxaaPass.setSize = function(width, height){
  107268. this.material.uniforms[ 'resolution' ].value.x = 1 / ( width ) ;
  107269. this.material.uniforms[ 'resolution' ].value.y = 1 / ( height ) ;
  107270. }
  107271. this.fxaaPass.renderToScreen = true;
  107272. this.composer.addPass( this.fxaaPass ); */
  107273. //抗锯齿截图 效果时而好时而不好,文字比较模糊
  107274. //这两个暂时不能一起用。目前刚好不需要一起用
  107275. }
  107276. {
  107277. this.mainViewport = new Viewport( this.scene.view, this.scene.cameraP, {
  107278. left:0, bottom:0, width:1, height: 1, name:'MainView'
  107279. });
  107280. this.viewports = [this.mainViewport];
  107281. Potree.settings.showCompass && (this.compass = new Compass(Potree.settings.compassDom, this.mainViewport));
  107282. this.magnifier = new Magnifier(this);
  107283. this.reticule = new Reticule(this);
  107284. this.scene.scene.add(this.magnifier);
  107285. this.scene.scene.add(this.reticule);
  107286. if(Potree.settings.editType != "pano" && Potree.settings.editType != 'merge'){
  107287. this.mapViewer = new MapViewer(mapArea/* $('#mapGaode')[0] */);
  107288. }
  107289. this.inputHandler = new InputHandler(this, this.scene.scene);
  107290. this.inputHandler.containsMouse = true;//初始化,使键盘事件在mainViewer有效
  107291. //this.inputHandler.setScene(this.scene);
  107292. //this.inputHandler.addInputListener(this);//add
  107293. this.clippingTool = new ClippingTool(this);
  107294. this.transformationTool = new TransformationTool(this);
  107295. this.navigationCube = new NavigationCube(this);
  107296. this.navigationCube.visible = false;
  107297. this.createControls();
  107298. this.clippingTool.setScene(this.scene);
  107299. let onPointcloudAdded = (e) => {
  107300. if (this.scene.pointclouds.length === 1) {
  107301. let speed = e.pointcloud.boundingBox.getSize(new Vector3()).length();
  107302. speed = speed / 2000;
  107303. this.setMoveSpeed(speed);
  107304. }
  107305. };
  107306. let onVolumeRemoved = (e) => {
  107307. this.inputHandler.deselect(e.volume);
  107308. };
  107309. this.addEventListener('scene_changed', (e) => {
  107310. this.inputHandler.setScene(e.scene);
  107311. this.clippingTool.setScene(this.scene);
  107312. if(!e.scene.hasEventListener("pointcloud_added", onPointcloudAdded)){
  107313. e.scene.addEventListener("pointcloud_added", onPointcloudAdded);
  107314. }
  107315. if(!e.scene.hasEventListener("volume_removed", onPointcloudAdded)){
  107316. e.scene.addEventListener("volume_removed", onVolumeRemoved);
  107317. }
  107318. });
  107319. this.scene.addEventListener("volume_removed", onVolumeRemoved);
  107320. this.scene.addEventListener('pointcloud_added', onPointcloudAdded);
  107321. }
  107322. { // set defaults
  107323. this.setFOV(60);
  107324. this.setEDLEnabled(false);
  107325. this.setEDLRadius(3);
  107326. this.setEDLStrength(0.01);
  107327. this.setEDLOpacity(1.0);
  107328. this.setPointBudget(1*1000*1000);
  107329. this.setShowBoundingBox(false);
  107330. this.setFreeze(false);
  107331. this.setControls(this.fpControls/* orbitControls */);
  107332. this.setBackground( new Color(Potree.config.background),1 /* 'gradient' */ );
  107333. this.scaleFactor = 1;
  107334. this.loadSettingsFromURL();
  107335. }
  107336. // start rendering!
  107337. //if(args.useDefaultRenderLoop === undefined || args.useDefaultRenderLoop === true){
  107338. //requestAnimationFrame(this.loop.bind(this));
  107339. //}
  107340. this.renderer.setAnimationLoop(this.loop.bind(this));
  107341. this.loadGUI = this.loadGUI.bind(this);
  107342. this.annotationTool = new AnnotationTool(this);
  107343. this.measuringTool = new MeasuringTool(this);
  107344. //this.profileTool = new ProfileTool(this);
  107345. this.volumeTool = new VolumeTool(this);
  107346. this.tagTool = new TagTool(this);
  107347. //-----------
  107348. CursorDeal.init(this, this.mapViewer ? [this, this.mapViewer] : [this]);//ADD
  107349. if(Potree.settings.editType == "pano"){
  107350. this.modules.PanoEditor.init();
  107351. }else if(Potree.settings.editType == "merge"){
  107352. this.modules.MergeEditor.init();
  107353. }else {
  107354. this.modules.SiteModel.init();
  107355. this.modules.ParticleEditor.init();
  107356. }
  107357. this.modules.Alignment.init();
  107358. this.images360 = new Images360(this);
  107359. this.scene.scene.add(this.objs);
  107360. loaders = {
  107361. objLoader : new OBJLoader( manager ),
  107362. mtlLoader : new MTLLoader( manager ),
  107363. glbLoader : new GLTFLoader(undefined, this.renderer, Potree.settings.libsUrl ),
  107364. plyLoader : new PLYLoader( manager ),
  107365. };
  107366. //add test
  107367. /* const environment = new RoomEnvironment();
  107368. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  107369. this.scene.scene.environment = pmremGenerator.fromScene( environment ).texture;
  107370. */
  107371. //-----------
  107372. }catch(e){
  107373. this.onCrash(e);
  107374. }
  107375. //-----------------------add----------------------------------------------------
  107376. /* {
  107377. let ratio
  107378. this.addEventListener('resize',(e)=>{
  107379. if(ratio != e.deviceRatio){ //因为devicePixelRatio会影响到点云大小,所以改变时计算下点云大小
  107380. viewer.scene.pointclouds.forEach(p => {
  107381. p.changePointSize()
  107382. })
  107383. }
  107384. ratio = e.deviceRatio
  107385. })
  107386. } */
  107387. {
  107388. let pointDensity = '';
  107389. Object.defineProperty(Potree.settings , "pointDensity",{
  107390. get: function() {
  107391. return pointDensity
  107392. },
  107393. set: (density)=>{
  107394. if(density && density != pointDensity){
  107395. let pointBudget;
  107396. var config = Potree.config.pointDensity[density];
  107397. if(this.magnifier.visible){//放大镜打开时不要切换pointBudget,否则点云会闪烁。这时使用最高密度。
  107398. pointBudget = Potree.config.pointDensity['magnifier'].pointBudget;
  107399. }else {
  107400. pointBudget = config.pointBudget;
  107401. }
  107402. viewer.setMinNodeSize(config.minNodeSize || Potree.config.minNodeSize);
  107403. viewer.setPointBudget(pointBudget );
  107404. //Potree.maxPointLevel = config.maxLevel
  107405. pointDensity = density;
  107406. this.setPointLevels();
  107407. this.dispatchEvent('pointDensityChanged');
  107408. }
  107409. }
  107410. });
  107411. let UserPointDensity = '';
  107412. Object.defineProperty(Potree.settings , "UserPointDensity",{
  107413. get: function() {
  107414. return UserPointDensity
  107415. },
  107416. set: (density)=>{
  107417. if(UserPointDensity != density){
  107418. if(Potree.settings.displayMode == 'showPointCloud' && this.viewports.length != 4){//漫游模式和四屏时都有自己的pointDensity
  107419. Potree.settings.pointDensity = density;
  107420. }
  107421. UserPointDensity = density;
  107422. this.dispatchEvent('UserPointDensityChanged');
  107423. }
  107424. }
  107425. });
  107426. }
  107427. {
  107428. let cameraFar = Potree.settings.cameraFar;
  107429. Object.defineProperty(Potree.settings , "cameraFar",{
  107430. get: function() {
  107431. return cameraFar
  107432. },
  107433. set: (far)=>{
  107434. if(far != cameraFar){
  107435. if(Potree.settings.displayMode != 'showPanos' && !this.fixCamFar){
  107436. this.mainViewport.camera.far = far;
  107437. this.mainViewport.camera.updateProjectionMatrix();
  107438. }
  107439. cameraFar = far;
  107440. }
  107441. }
  107442. });
  107443. }
  107444. /* this.reticule.addEventListener('update',(e)=>{
  107445. this.needRender = true
  107446. if(this.mapViewer && this.mapViewer.attachedToViewer)this.mapViewer.needRender = true //分屏时mapViewer也有reticule
  107447. }) */
  107448. this.reticule.addEventListener('update',(e)=>{
  107449. this.reticule.hoverViewport && (this.reticule.hoverViewport.needRender = true);
  107450. this.lazyRenderViewports();
  107451. if(this.mapViewer && this.mapViewer.attachedToViewer &&
  107452. (this.mapViewer.viewports[0].needRender || this.needRender ) ) this.mapViewer.needRender = true; //分屏时mapViewer也有reticule
  107453. });
  107454. this.addEventListener('pointcloud_changed',(e)=>{
  107455. if(this.screenshoting){
  107456. this.viewports.filter(e=>!e.noPointcloud).forEach(e =>e.needRender = true);
  107457. }
  107458. else this.lazyRenderViewports();
  107459. });
  107460. this.addEventListener('allLoaded', ()=>{
  107461. setTimeout(this.testPointcloudsMaxLevel.bind(this), 1000); //延迟一丢丢,等画面出现
  107462. this.scene.pointclouds.forEach(pointcloud=>{
  107463. pointcloud.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  107464. //console.log('pointcloud isVisible', this.id, e.visible)
  107465. if(e.reason != 'displayMode' ){
  107466. this.updateModelBound('visibleChanged');
  107467. }
  107468. this.dispatchEvent('pointcloud_changed');
  107469. });
  107470. pointcloud.material.addEventListener('material_property_changed',()=>{
  107471. this.dispatchEvent('pointcloud_changed');
  107472. });
  107473. });
  107474. });
  107475. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  107476. this.addEventListener('switchFloorplanSelect',(e)=>{//进入平面图设置后 切换选中的数据集
  107477. this.selectedFloorplan = e.pointcloud; //绝对显示
  107478. this.updateFpVisiDatasets();
  107479. let pointclouds;
  107480. if(e.pointcloud){
  107481. pointclouds = [e.pointcloud];
  107482. }else if(this.fpVisiDatasets.length){
  107483. pointclouds = this.fpVisiDatasets;
  107484. }
  107485. pointclouds && this.mapViewer.fitToDatasets(pointclouds);
  107486. });
  107487. this.modules.SiteModel.bus.addEventListener('FloorChange',(e)=>{
  107488. this.updateFpVisiDatasets();
  107489. this.updatePanosVisibles(e.currentFloor); //问:编辑空间模型时,需不需要改为显示当前选择的楼层。因为若所在楼层和选中的不一致,修改选中楼层的轮廓却改不了marker显示很奇怪,尤其刚好在一个建筑内时。
  107490. });
  107491. this.mapViewer.mapLayer.addEventListener('floorplanLoaded',()=>{
  107492. this.updateCadVisibles(this.fpVisiDatasets, true); //加载完成后重新更新下
  107493. });
  107494. /* this.modules.Clip.bus.addEventListener('updateSelectedDatasets',()=>{
  107495. this.updateFpVisiDatasets()
  107496. }) */
  107497. }
  107498. {
  107499. let updated, zoomLevel;
  107500. let update = (e)=>{
  107501. if(e.type == 'updateModelBound' || e.viewport == this.mainViewport && (e.changeInfo.positionChanged || zoomLevel != this.images360.zoomLevel)){
  107502. zoomLevel = this.images360.zoomLevel; //对updateMarkerVisibles有影响
  107503. //e.changeInfo.positionChanged && shelterHistory.clear() //清空
  107504. (e.type == 'updateModelBound' || e.changeInfo.positionChanged) && this.updateDatasetAt(); //更新所在数据集
  107505. if(Potree.settings.ifShowMarker && Potree.settings.editType != 'merge'){
  107506. Common$1. intervalTool.isWaiting('updateMarkerVisibles', ()=>{
  107507. if(!this.mainViewport.view.isFlying() ){
  107508. this.updateMarkerVisibles();
  107509. }
  107510. },500);
  107511. }
  107512. }
  107513. };
  107514. this.addEventListener('camera_changed', update);
  107515. this.addEventListener('updateModelBound', update);
  107516. this.addEventListener('showMarkerChanged',()=>{
  107517. this.updatePanosVisibles(this.modules.SiteModel.currentFloor);
  107518. this.updateMarkerVisibles();
  107519. });
  107520. /* if(!Potree.Features.EXT_DEPTH.isSupported()){
  107521. this.images360.addEventListener('endChangeMode',(e)=>{
  107522. if(e.mode == 'showPanos'){
  107523. this.updateMarkerVisibles()
  107524. }
  107525. }) */
  107526. this.images360.addEventListener('getNeighbourAuto',(e)=>{
  107527. if(/* Potree.settings.displayMode == 'showPanos' && */e.panos.includes(this.images360.currentPano)){
  107528. Common$1.intervalTool.isWaiting('updateMarkerVisibles', ()=>{
  107529. this.updateMarkerVisibles();
  107530. },500);
  107531. }
  107532. });
  107533. /* } */
  107534. }
  107535. {
  107536. let interval;
  107537. document.addEventListener('visibilitychange',(e)=>{
  107538. let v = !document.hidden;
  107539. //console.warn('visibilitychange', v )
  107540. this.dispatchEvent({type:'pageVisible', v } );
  107541. if(this.screenshoting && !v){//截图过程中离开页面需要照常loop。但是尽量别离开页面,效果只能达到90%
  107542. interval = setInterval(()=>{
  107543. //console.log('force loop', Date.now())
  107544. if(this.screenshoting){ //截图完成时如果还没回来就不loop
  107545. this.loop(Date.now());
  107546. }
  107547. },50); //实际>1000, 浏览器会放慢定时器,放慢多少不确定
  107548. }else if(v && interval){
  107549. clearInterval(interval);
  107550. }
  107551. });
  107552. }
  107553. /* if(!Potree.isIframeChild){
  107554. window.winIndex = 0;
  107555. let index = 1;
  107556. this.addEventListener('createIframe',(e)=>{//创建了子页面
  107557. let child = e.window;
  107558. child.winIndex = index ++;
  107559. })
  107560. //不知道删除iframe时是否那些模型还在内存里,需要释放吗? 如果要需要加一个事件
  107561. } */
  107562. /* {
  107563. let setInteract = ()=>{
  107564. this.interacted = true //标记这一帧用户有操作屏幕
  107565. }
  107566. this.addEventListener('global_mousedown', setInteract)
  107567. this.addEventListener('global_touchmove', setInteract)
  107568. this.addEventListener('global_mousewheel', setInteract)
  107569. }
  107570. {//针对数据集偏离中心很远后产生的精度损失而抖动
  107571. this.addEventListener('camera_changed', e => {
  107572. if(e.viewport == this.mainViewport && (e.changeInfo.positionChanged)){
  107573. if(Potree.settings.editType != 'merge' && Potree.settings.editType != 'pano'){
  107574. if(!this.mainViewport.view.isFlying() ){
  107575. let pos = this.mainViewport.view.position.clone() // this.mainViewport.camera.getWorldPosition(new THREE.Vector3)
  107576. if(pos.lengthSq() > 25000000){
  107577. Common.intervalTool.isWaiting('moveWorldCenter', ()=>{
  107578. pos = this.mainViewport.view.position.clone()
  107579. this.mainViewport.view.translateWorld(-pos.x, -pos.y, -pos.z)
  107580. this.scene.scene.position.sub(pos)
  107581. console.log('变位置', pos)
  107582. this.scene.pointclouds.forEach(cloud=>{
  107583. Alignment.setMatrix(cloud)
  107584. })
  107585. },500)
  107586. }
  107587. }
  107588. }
  107589. }
  107590. })
  107591. }*/
  107592. }
  107593. lazyRenderViewports(updateCount){
  107594. //本来要写this.needRender = true的, 但在分四个屏时防止太卡而排队render
  107595. let viewports = this.viewports;
  107596. if(viewports.length == 1 || this.needRender){
  107597. return this.needRender = true
  107598. }
  107599. const maxWaitTime = 200;
  107600. let now = Date.now();
  107601. let maxRenderCount = 1;
  107602. viewports.forEach(e=>{
  107603. if(now - e.lastRenderTime > maxWaitTime){
  107604. e.needRender = true;
  107605. }
  107606. });
  107607. let renderCount = viewports.filter(e=>e.needRender).length;
  107608. //console.log('renderCount', renderCount)
  107609. let list = viewports.filter(e=>!e.needRender).sort((a,b)=>a.lastRenderTime - b.lastRenderTime);//没有准备render的,按上次渲染时间排序,作为候补
  107610. if(renderCount < maxRenderCount){ //还有名额,补齐
  107611. list.slice(0, maxRenderCount - renderCount).forEach(e=>{
  107612. e.needRender = true;
  107613. });
  107614. }else if(list[0] && now - list[0].lastRenderTime > maxWaitTime){//名额不足时,考虑候补队列第一个是否超时,超时的话也渲染
  107615. list[0].needRender = true;
  107616. }
  107617. }
  107618. ifPointBlockedByIntersect(point , panoId, soon ){//点是否被遮挡
  107619. let ifShelter;
  107620. let now = Date.now();
  107621. let extraPanoId = panoId != void 0;
  107622. if(!this.shelterCount)return
  107623. let history = shelterHistory.find(e=>e.point.equals(point));
  107624. let cameraPos = this.mainViewport.view.position.clone();
  107625. if(panoId == void 0){
  107626. if(this.images360.isAtPano(0.05)){
  107627. panoId = this.images360.currentPano.id;
  107628. }
  107629. }
  107630. if(history){
  107631. if(panoId != void 0){
  107632. ifShelter = history.panos[panoId];
  107633. }else {
  107634. if(history.notAtPano.cameraPos && history.notAtPano.cameraPos.equals(cameraPos)){
  107635. ifShelter = history.notAtPano.ifShelter;
  107636. }
  107637. }
  107638. let index = shelterHistory.indexOf(history); //先取出,稍后放回
  107639. shelterHistory.splice(index, 1);
  107640. }else {//新增
  107641. history = {point, panos:{}, notAtPano:{}};
  107642. const minCount = 100;
  107643. if(shelterHistory.length > minCount){//去除最早的
  107644. let old;
  107645. while(old = shelterHistory[0], now - old.lastTime > 1000){//因为不知热点个数,所以需要加上时间限制,超过时间才能删。
  107646. if(old == history || shelterHistory.length == minCount)break;
  107647. shelterHistory.splice(0,1);
  107648. //console.log('delete')
  107649. }
  107650. }
  107651. }
  107652. if(ifShelter == void 0){
  107653. delete history.waitCompute;
  107654. if(this.mainViewport.view.isFlying()){
  107655. return useLastResult()
  107656. }
  107657. if(panoId != void 0){
  107658. let pano = this.images360.getPano(panoId);
  107659. if((soon || this.shelterCount.byTex<this.shelterCount.maxByTex) && pano.depthTex){
  107660. ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({point, margin:Potree.config.shelterMargin, useDepthTex:true, pano, viewport:this.mainViewport } );
  107661. history.panos[panoId] = ifShelter;
  107662. this.shelterCount.byTex ++ ;
  107663. //console.log('computeByTex direct', panoId, point, ifShelter)
  107664. }else {
  107665. //console.log('延迟tex',panoId, point )
  107666. history.waitCompute = {panoId, forceGet:extraPanoId };
  107667. return useLastResult()
  107668. }
  107669. }else {
  107670. if(/* history.ifShelter == void 0 || */ this.shelterCount.byCloud<this.shelterCount.maxByCloud){//弊端:第一个总是直接计算,后面的都是延后。但无法改进,因是一个个传进来的,无法预测。
  107671. ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({point, margin:Potree.config.shelterMargin, pickWindowSize:3} );
  107672. history.notAtPano = {cameraPos , ifShelter };
  107673. this.shelterCount.byCloud ++ ;
  107674. //console.log('computeByCloud direct', point.toArray())
  107675. }else {
  107676. //console.log('延迟cloud' )
  107677. history.waitCompute = {cameraPos};
  107678. return useLastResult()
  107679. }
  107680. }
  107681. }
  107682. history.ifShelter = ifShelter;
  107683. history.lastTime = now;
  107684. shelterHistory.push(history); //最新使用的保持在最后一个,使队列按照从旧到新排列
  107685. function useLastResult(){//暂时先用上一次的值
  107686. shelterHistory.push(history);
  107687. history.lastTime = now;
  107688. return history.ifShelter
  107689. }
  107690. return ifShelter
  107691. }
  107692. computeShelter(){
  107693. //先算用深度图的,然后再点云;
  107694. //let depthTiming = Potree.timeCollect.depthSampler.median
  107695. let byTex=0, byCloud=0;
  107696. let len = shelterHistory.length;
  107697. let waitCloud = [];
  107698. let maxTexCount = Common$1.getBestCount('shelterMaxDepthSample', 1, 50, 1, 13 /* ,true */ );
  107699. for(let i=len-1; i>=0; i--){
  107700. let history = shelterHistory[i];
  107701. if(history.waitCompute){
  107702. if(history.waitCompute.panoId != void 0){
  107703. if(!history.waitCompute.forceGet && (history.waitCompute.panoId != this.images360.currentPano.id || !this.images360.isAtPano(0.1))){
  107704. delete history.waitCompute; //取消计算
  107705. }else {
  107706. if(this.images360.currentPano.depthTex){
  107707. if(byTex >= maxTexCount)break
  107708. byTex ++;
  107709. let ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({point:history.point, margin:Potree.config.shelterMargin, useDepthTex:true, viewport:this.mainViewport } );
  107710. history.panos[this.images360.currentPano.id] = ifShelter;
  107711. history.ifShelter = ifShelter;
  107712. delete history.waitCompute;
  107713. //console.log('补1', history.point.toArray())
  107714. }else {
  107715. if(this.images360.currentPano.pointcloud.hasDepthTex){
  107716. //先等待加载完深度图
  107717. }else {
  107718. waitCloud.push(history);
  107719. }
  107720. }
  107721. }
  107722. }else {
  107723. waitCloud.push(history);
  107724. }
  107725. }
  107726. }
  107727. let maxCloudCount;
  107728. if(byTex < maxTexCount && waitCloud.length ){
  107729. maxCloudCount = this.lastFrameChanged ? Common$1.getBestCount('shelterMaxCloud', 0, 2, 4, 8 /* ,true */ ) : 5;
  107730. let waitCloud2 = [];
  107731. if(maxCloudCount){
  107732. for(let i=0; i<waitCloud.length; i++){
  107733. let history = waitCloud[i];
  107734. if(history.waitCompute.cameraPos){
  107735. if(!viewer.mainViewport.view.position.equals(history.waitCompute.cameraPos)){
  107736. delete history.waitCompute;
  107737. //console.log('delete history.waitCompute', history)
  107738. continue; //取消计算
  107739. }else {
  107740. waitCloud2.push(history);
  107741. }
  107742. }else {
  107743. waitCloud2.push(history);
  107744. }
  107745. }
  107746. let list = waitCloud2.map(e=>e.point);
  107747. let result = Common$1.batchHandling.getSlice('shelterByCloud', list, {maxUseCount:maxCloudCount,useEquals:true, stopWhenAllUsed:true} ); //iphonex稳定后大概在7-10。
  107748. //list.length>0 && console.log('list',list, maxCloudCount)
  107749. result.list.forEach(e=>{
  107750. let history = waitCloud2.find(a=>a.point.equals(e));
  107751. let ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({point:history.point, margin: Potree.config.shelterMargin , pickWindowSize:3, viewport:this.mainViewport} );
  107752. if(history.waitCompute.cameraPos){
  107753. history.notAtPano = {cameraPos: history.waitCompute.cameraPos , ifShelter };
  107754. }else {
  107755. history.panos[this.images360.currentPano.id] = ifShelter;
  107756. }
  107757. history.ifShelter = ifShelter;
  107758. byCloud++;
  107759. //console.log('补2', history.point.toArray())
  107760. delete history.waitCompute;
  107761. });
  107762. }
  107763. }
  107764. if(byTex || byCloud){
  107765. //console.log('shelterComputed',byTex,byCloud, maxTexCount, maxCloudCount)
  107766. Common$1.intervalTool.isWaiting('shelterComputed', ()=>{
  107767. //console.log('shelterComputed update')
  107768. this.dispatchEvent('shelterComputed');
  107769. },340);
  107770. }
  107771. }
  107772. updateDatasetAt(force){//更新所在数据集
  107773. let fun = ()=>{
  107774. let currPos = viewer.mainViewport.view.position;
  107775. //if(force || !currPos.equals(this.lastPos)){
  107776. //this.lastPos.copy(currPos)
  107777. var at = this.scene.pointclouds.filter(e=>
  107778. (e.visible || e.unvisibleReasons && e.unvisibleReasons.length == 1 && e.unvisibleReasons[0].reason == 'displayMode')
  107779. && e.ifContainsPoint(currPos)
  107780. );
  107781. if(Common$1.getDifferenceSet(at, this.atDatasets).length){
  107782. //console.log('atDatasets', at)
  107783. this.atDatasets = at;
  107784. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge')this.updateFpVisiDatasets();
  107785. this.dispatchEvent({type:'pointcloudAtChange',pointclouds:at});
  107786. }
  107787. force = false;
  107788. };
  107789. //}
  107790. if(force)fun();
  107791. else Common$1.intervalTool.isWaiting('atWhichDataset', fun , 300);
  107792. }
  107793. updatePanosVisibles(currentFloor){//显示当前楼层的所有panos
  107794. if(!Potree.settings.ifShowMarker)return
  107795. let inEntity = currentFloor;
  107796. if(!inEntity) inEntity = this.atDatasets[0];
  107797. viewer.images360.panos.forEach(pano=>{
  107798. let visible = inEntity && inEntity.panos.includes(pano);
  107799. Potree.Utils.updateVisible(pano, 'buildingChange', visible, 2);
  107800. });
  107801. this.dispatchEvent('content_changed');
  107802. } //注:非official的没有获取sitemodel的信息所以不执行楼层判断,marker显示不对是正常的
  107803. /* 2023.11.24 针对部分场景的楼层很矮,很容易就到楼层外了,且不能修改楼高。如SG-t-9NdCpxrUPLL#/,采取如下措施:
  107804. 1 如果不在任何一楼层,但在某个数据集中,就显示该数据集所有的marker
  107805. 2 如果当前楼层无,则显示上一次的currentFloor的marker
  107806. (目前先使用方案1)
  107807. */
  107808. updateMarkerVisibles(){//限制显示的marker个数,因镜头内marker多的时候可能会卡
  107809. if(!Potree.settings.ifShowMarker)return
  107810. const minRadius = 8 * this.images360.zoomLevel, //当视线垂直于marker时的最小可见距离,此范围内可见的pano绝对可见
  107811. maxRadius = 50 * this.images360.zoomLevel, //当视线垂直于marker时的最大可见距离,此范围外绝对不可见
  107812. hopeCount = browser.isMobile() ? 8 : 15; //期望达到的真实可见的marker数
  107813. let sheltered = (pano)=>{
  107814. if(/* Potree.settings.displayMode == 'showPanos' && !Potree.Features.EXT_DEPTH.isSupported() && */this.images360.isAtPano() && !this.mainViewport.view.isFlying()){
  107815. return !this.images360.currentPano.neighbours.includes(pano) && this.images360.currentPano != pano //起初因不支持EXT_DEPTH时无法用depthTex遮住marker, 后为了减少绘制,都判断
  107816. }
  107817. };
  107818. let panoMap = new Map; //先记录想要设置为可见的
  107819. let set = ()=>{//最后确定设置
  107820. let count = 0;
  107821. viewer.images360.panos.forEach(pano=>{
  107822. let v = panoMap.get(pano).visible;
  107823. v && count++;
  107824. Potree.Utils.updateVisible(pano.marker, 'limitMarkerShow', v );
  107825. });
  107826. //console.log('updateMarkerVisibles marker显示个数', count)
  107827. this.dispatchEvent('content_changed');
  107828. };
  107829. let isWithinDis = (pano,maxDis)=>{//是否marker到相机的距离 没有超出可视距离。可视距离考虑上倾斜角,倾斜越大可视距离越短
  107830. let camPos = viewer.mainViewport.camera.position;
  107831. let o = panoMap.get(pano);
  107832. o.dis = o.dis || camPos.distanceTo(pano.marker.position);
  107833. o.sin = o.sin || Math.sqrt(Math.abs(camPos.z - pano.marker.position.z) / o.dis); //和地面夹角的sin。 按公式是不加Math.sqrt的,但是这样大马路上在贴近地面时算出的个数非常少,所以增大点……
  107834. return o.dis < maxDis * o.sin
  107835. };
  107836. viewer.images360.panos.forEach(pano=>{//minRadius内的记录为可见
  107837. let o = {};
  107838. panoMap.set(pano, o);
  107839. if(pano.visible && !sheltered(pano) && isWithinDis(pano, minRadius)){
  107840. o.visible = true;
  107841. }
  107842. });
  107843. //不超过hopeCount的话,可以直接确定设置
  107844. if(viewer.images360.panos.filter(pano=> panoMap.get(pano).visible ).length >= hopeCount)return set()
  107845. //距离超过maxRadius就绝对不可见
  107846. let insideOutCirle = viewer.images360.panos.filter(pano=> pano.visible && !sheltered(pano) && isWithinDis(pano, maxRadius));
  107847. if(insideOutCirle.length <= hopeCount){
  107848. insideOutCirle.forEach(pano=>panoMap.get(pano).visible = true );
  107849. return set()
  107850. }
  107851. //数量超过hopeCount时,根据距离排序
  107852. insideOutCirle.sort((a,b)=>{return panoMap.get(a).dis - panoMap.get(b).dis });
  107853. let slice = insideOutCirle.slice(0,hopeCount);
  107854. slice.forEach(pano=>panoMap.get(pano).visible = true );
  107855. set();
  107856. }
  107857. updateFpVisiDatasets(){
  107858. let Clip = this.modules.Clip;
  107859. let SiteModel = this.modules.SiteModel;
  107860. let Alignment = this.modules.Alignment;
  107861. var currentFloor = SiteModel.currentFloor;
  107862. /* if(Clip.editing){//下载页面已经改为和普通时一样,根据位置判断
  107863. this.updateCadVisibles(Clip.selectedDatasets)
  107864. }else */if(this.selectedFloorplan){//平面图设置中 或 地理设置
  107865. let pointclouds = [this.selectedFloorplan];
  107866. this.updateCadVisibles(pointclouds);
  107867. }else if(SiteModel.editing || Alignment.editing){//只显示勾选的,也就是显示的点云的
  107868. let pointclouds = this.scene.pointclouds.filter(p => Potree.Utils.getObjVisiByReason(p,'datasetSelection') );
  107869. this.updateCadVisibles(pointclouds);
  107870. //this.updatePanosVisibles(currentFloor/* , pointclouds */)
  107871. }else {
  107872. let pointclouds = currentFloor ? this.findPointcloudsAtFloor(currentFloor) : [];
  107873. if(pointclouds.length == 0){
  107874. if(this.focusDatasets){
  107875. pointclouds = this.focusDatasets;
  107876. }
  107877. }
  107878. if(pointclouds.length == 0){//如果当前不在任何楼层或楼层中无数据集,就用当前所在数据集
  107879. pointclouds = this.atDatasets;
  107880. }
  107881. this.updateCadVisibles(pointclouds);
  107882. //this.updatePanosVisibles(currentFloor/* , pointclouds */)
  107883. }
  107884. }
  107885. /* findPointcloudsAtFloor(entity){//找当前楼层需要显示哪些数据集。
  107886. //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含)
  107887. //重叠体积>50% 或 包含>50%的漫游点
  107888. const ratio1 = 0.2, ratio2 = 0.5, ratio3 = 0.95
  107889. var lowScores = []
  107890. var pointclouds = viewer.scene.pointclouds.filter(e=>{
  107891. let score = 0
  107892. if(e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)){//条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间)
  107893. return true
  107894. }
  107895. if(e.panos.length){//条件2
  107896. var insidePanos = e.panos.filter(a=>entity.ifContainsPoint(a.position));
  107897. let panoCountRatio = insidePanos.length / e.panos.length
  107898. if(panoCountRatio > ratio2)return true
  107899. score += panoCountRatio
  107900. }
  107901. //条件3
  107902. let volume = entity.intersectPointcloudVolume(e);
  107903. let volumeRatio = volume / entity.getVolume(true) //注:hole加入计算
  107904. if(volumeRatio > ratio3){ //ratio3要高一些,因为点云bounding可能很大,包含很多无点云的空间。即使整个数据集包含entity都不一定看起来在数据集中。(千万要防止两层楼都显示了)
  107905. return true
  107906. }else{
  107907. score += volumeRatio
  107908. }
  107909. lowScores.push({score, pointcloud:e})
  107910. })
  107911. if(pointclouds.length == 0){//从低分项挑一个出来。
  107912. lowScores.sort((a,b)=>{return a.score - b.score})
  107913. if(lowScores[0].score > 0.4){
  107914. pointclouds = [lowScores[0].pointcloud]
  107915. }
  107916. }
  107917. return pointclouds
  107918. } */
  107919. findPointcloudsAtFloor(entity){//找当前楼层需要显示哪些数据集。
  107920. //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含)
  107921. //重叠体积>50% 或 包含>50%的漫游点
  107922. const ratio1 = 0.2, ratio2 = 0.5, ratio3 = 0.95;
  107923. var lowScores = [];
  107924. var pointclouds = viewer.scene.pointclouds.filter(e=>{
  107925. let score = 0;
  107926. if(e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)){//条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间)
  107927. return true
  107928. }
  107929. if(e.panos.length){//条件2
  107930. var insidePanos = e.panos.filter(a=>entity.ifContainsPoint(a.position));
  107931. let panoCountRatio = insidePanos.length / e.panos.length;
  107932. if(panoCountRatio > ratio2)return true
  107933. score += panoCountRatio * 2;
  107934. }
  107935. //条件3
  107936. let coverHeightRatio = entity.coverPointcloudHeight(e,true);//重叠高度占楼层高度的比率。
  107937. if(coverHeightRatio < 0.2) return
  107938. let {toEntity,toPointcloud} = entity.intersectPointcloudArea(e,true); //重叠面积占比
  107939. let coverAreaRatio = Math.max(toEntity,toPointcloud);//占数据集俯视面积的比率 和 占楼层的面积比率,挑一个大的。 (有的数据集被划分多个楼层,所以每层都应该显示该数据集的图。还有的数据集比较大,可能包含多个建筑,则看占楼层面积)
  107940. if(coverAreaRatio < 0.2) return
  107941. score += coverAreaRatio * coverHeightRatio;
  107942. lowScores.push({score, pointcloud:e});
  107943. });
  107944. /* if(pointclouds.length == 0){//从低分项挑一个出来。
  107945. lowScores.sort((a,b)=>{return a.score - b.score})
  107946. if(lowScores[0].score > 0.4){
  107947. pointclouds = [lowScores[0].pointcloud]
  107948. }
  107949. } */
  107950. lowScores.forEach(e=>{//一个楼层里可以包含许多个数据集 调试SG-t-ds27ym7xzjJ
  107951. if(e.score > 0.5){
  107952. pointclouds.push(e.pointcloud);
  107953. }
  107954. });
  107955. return pointclouds
  107956. }
  107957. updateCadVisibles(visiClouds, force){
  107958. let oldVisi = this.fpVisiDatasets;
  107959. var visiClouds = this.fpVisiDatasets = visiClouds;
  107960. if(!force){
  107961. var difference = Common$1.getDifferenceSet(oldVisi , visiClouds);
  107962. if(difference.length == 0)return
  107963. }
  107964. //console.log('visiClouds',visiClouds.map(e=>e.name))
  107965. viewer.scene.pointclouds.forEach(pointcloud=>{
  107966. var floorplan = viewer.mapViewer.mapLayer.getFloorplan(pointcloud.dataset_id);
  107967. var visi = visiClouds.includes(pointcloud);
  107968. if(floorplan){
  107969. Potree.Utils.updateVisible(floorplan.objectGroup, 'buildingChange', visi);
  107970. }/* else if(!visi){
  107971. let changeVisi = (e)=>{
  107972. Potree.Utils.updateVisible(e.floorplan.objectGroup, 'buildingChange', this.fpVisiDatasets.includes(pointcloud))
  107973. viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', changeVisi)
  107974. console.log('updateCadVisibles加载后更改显示',e)
  107975. }
  107976. viewer.mapViewer.mapLayer.addEventListener('floorplanLoaded', changeVisi)
  107977. } */
  107978. //已经添加了全局的 floorplanLoaded后会updateCadVisibles,这段就删了
  107979. });
  107980. viewer.mapViewer.mapLayer.needUpdate = true; //可能需要更新加载的level程度
  107981. viewer.mapViewer.needRender = true; //若上句不触发加载也要立即重新绘制
  107982. }
  107983. //促使点云加载出最高级别
  107984. testPointcloudsMaxLevel(){ //所有点云都无需testMaxNodeLevel 就停止
  107985. let camera_changed, count = 0;
  107986. let test = (e={})=>{
  107987. camera_changed = true;
  107988. let camera = e.camera || this.scene.getActiveCamera();
  107989. Common$1.intervalTool.isWaiting('testPointcloudsMaxLevel', ()=>{
  107990. if(!camera_changed && count>50 || Potree.settings.displayMode == 'showPanos' )return //只有当camera_changed后才继续循环, 除了最开始几次需要连续加载下
  107991. camera_changed = false;
  107992. count ++;
  107993. //console.log('testPointcloudsMaxLevel中', camera.type /* count */)
  107994. let oldCount = this.testMaxNodeCount;
  107995. var success = true;
  107996. viewer.scene.pointclouds.forEach(e=>{
  107997. var wait = e.testMaxNodeLevel(camera);
  107998. if(wait){
  107999. success = false;
  108000. }
  108001. });
  108002. /* if(oldCount<=Potree.config.testNodeCount1 && this.testMaxNodeCount>Potree.config.testNodeCount1 ){//差不多等当前所在数据集nodeMaxLevel加载出来
  108003. viewer.scene.pointclouds.forEach(e=>{e.changePointSize()}) //重新更新一下大小。因之前用的是nodeMaxLevelPredict (防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现
  108004. } */
  108005. if(!success)return true //没有全部加载完,继续循环
  108006. else {
  108007. this.removeEventListener('camera_changed',test);
  108008. console.log('testPointcloudsMaxLevel结束');
  108009. }
  108010. }, count<10 ? 250 : 500);
  108011. };
  108012. this.addEventListener('camera_changed',test);
  108013. test();
  108014. /* 检验:
  108015. viewer.scene.pointclouds.sort((a,b)=>a.nodeMaxLevelPredict.min - b.nodeMaxLevelPredict.min).forEach(e=>console.log(e.nodeMaxLevel, e.nodeMaxLevelPredict.min))
  108016. */
  108017. }
  108018. setPointLevels(){
  108019. this.scene.pointclouds.forEach(e=>{
  108020. e.setPointLevel();
  108021. });
  108022. }
  108023. onCrash(error){
  108024. console.error(error);
  108025. $(this.renderArea).empty();
  108026. if ($(this.renderArea).find('#potree_failpage').length === 0) {
  108027. let elFailPage = $(`
  108028. <div id="#potree_failpage" class="potree_failpage">
  108029. <h1>Potree Encountered An Error </h1>
  108030. <p>
  108031. This may happen if your browser or graphics card is not supported.
  108032. <br>
  108033. We recommend to use
  108034. <a href="https://www.google.com/chrome/browser" target="_blank" style="color:initial">Chrome</a>
  108035. or
  108036. <a href="https://www.mozilla.org/" target="_blank">Firefox</a>.
  108037. </p>
  108038. <p>
  108039. Please also visit <a href="http://webglreport.com/" target="_blank">webglreport.com</a> and
  108040. check whether your system supports WebGL.
  108041. </p>
  108042. <p>
  108043. If you are already using one of the recommended browsers and WebGL is enabled,
  108044. consider filing an issue report at <a href="https://github.com/potree/potree/issues" target="_blank">github</a>,<br>
  108045. including your operating system, graphics card, browser and browser version, as well as the
  108046. error message below.<br>
  108047. Please do not report errors on unsupported browsers.
  108048. </p>
  108049. <pre id="potree_error_console" style="width: 100%; height: 100%"></pre>
  108050. </div>`);
  108051. let elErrorMessage = elFailPage.find('#potree_error_console');
  108052. elErrorMessage.html(error.stack);
  108053. $(this.renderArea).append(elFailPage);
  108054. }
  108055. throw error;
  108056. }
  108057. // ------------------------------------------------------------------------------------
  108058. // Viewer API
  108059. // ------------------------------------------------------------------------------------
  108060. setScene (scene) {
  108061. if (scene === this.scene) {
  108062. return;
  108063. }
  108064. let oldScene = this.scene;
  108065. this.scene = scene;
  108066. this.dispatchEvent({
  108067. type: 'scene_changed',
  108068. oldScene: oldScene,
  108069. scene: scene
  108070. });
  108071. { // Annotations
  108072. $('.annotation').detach();
  108073. // for(let annotation of this.scene.annotations){
  108074. // this.renderArea.appendChild(annotation.domElement[0]);
  108075. // }
  108076. this.scene.annotations.traverse(annotation => {
  108077. this.renderArea.appendChild(annotation.domElement[0]);
  108078. });
  108079. if (!this.onAnnotationAdded) {
  108080. this.onAnnotationAdded = e => {
  108081. // console.log("annotation added: " + e.annotation.title);
  108082. e.annotation.traverse(node => {
  108083. $("#potree_annotation_container").append(node.domElement);
  108084. //this.renderArea.appendChild(node.domElement[0]);
  108085. node.scene = this.scene;
  108086. });
  108087. };
  108088. }
  108089. if (oldScene) {
  108090. oldScene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  108091. }
  108092. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  108093. }
  108094. };
  108095. setControls(controls/* , setSpeed */){
  108096. if (controls !== this.controls) {
  108097. if (this.controls) {
  108098. this.controls.setEnable(false);
  108099. //this.inputHandler.removeInputListener(this.controls);
  108100. this.controls.moveSpeed = this.moveSpeed; //记录 (因为orbit的radius很大,转为firstPerson时要缩小)
  108101. }
  108102. this.controls = controls;
  108103. controls.moveSpeed && this.setMoveSpeed(controls.moveSpeed); //add
  108104. this.controls.setEnable(true);
  108105. //this.inputHandler.addInputListener(this.controls);
  108106. }
  108107. }
  108108. getControls () {
  108109. if(this.renderer.xr.isPresenting){
  108110. return this.vrControls;
  108111. }else {
  108112. return this.controls;
  108113. }
  108114. }
  108115. getMinNodeSize () {
  108116. return this.minNodeSize;
  108117. };
  108118. setMinNodeSize (value) {
  108119. if (this.minNodeSize !== value) {
  108120. this.minNodeSize = value;
  108121. this.dispatchEvent({'type': 'minnodesize_changed', 'viewer': this});
  108122. }
  108123. };
  108124. getBackground () {
  108125. return this.background;
  108126. }
  108127. setBackground(bg, src){
  108128. /* if (this.background === bg ) {
  108129. return;
  108130. } */
  108131. if(bg === "skybox"){
  108132. if(!src)src = Potree.resourcePath+'/textures/skybox/xingkong.jpg';
  108133. this.skybox = Utils.loadSkybox(src, this.skybox);
  108134. }
  108135. this.background = bg;
  108136. this.backgroundOpacity = 1;//add
  108137. this.dispatchEvent({'type': 'background_changed', 'viewer': this});
  108138. }
  108139. setDescription (value) {
  108140. this.description = value;
  108141. $('#potree_description').html(value);
  108142. //$('#potree_description').text(value);
  108143. }
  108144. getDescription(){
  108145. return this.description;
  108146. }
  108147. setShowBoundingBox (value) {
  108148. if (this.showBoundingBox !== value) {
  108149. this.showBoundingBox = value;
  108150. this.dispatchEvent({'type': 'show_boundingbox_changed', 'viewer': this});
  108151. }
  108152. };
  108153. getShowBoundingBox () {
  108154. return this.showBoundingBox;
  108155. };
  108156. setMoveSpeed (value) {
  108157. if (this.getMoveSpeed() !== value) {
  108158. this.mainViewport.setMoveSpeed(value);
  108159. this.dispatchEvent({'type': 'move_speed_changed', 'viewer': this, 'speed': value});
  108160. }
  108161. };
  108162. getMoveSpeed () {
  108163. return this.mainViewport.moveSpeed;
  108164. };
  108165. setWeightClassification (w) {
  108166. for (let i = 0; i < this.scene.pointclouds.length; i++) {
  108167. this.scene.pointclouds[i].material.weightClassification = w;
  108168. this.dispatchEvent({'type': 'attribute_weights_changed' + i, 'viewer': this});
  108169. }
  108170. };
  108171. setFreeze (value) {
  108172. value = Boolean(value);
  108173. if (this.freeze !== value) {
  108174. this.freeze = value;
  108175. this.dispatchEvent({'type': 'freeze_changed', 'viewer': this});
  108176. }
  108177. };
  108178. getFreeze () {
  108179. return this.freeze;
  108180. };
  108181. setElevationGradientRepeat(value){
  108182. if(this.elevationGradientRepeat !== value){
  108183. this.elevationGradientRepeat = value;
  108184. this.dispatchEvent({
  108185. type: "elevation_gradient_repeat_changed",
  108186. viewer: this});
  108187. }
  108188. }
  108189. setPointBudget (value) { //pointBudget: 每次刷新显示点数量的最大值。 缓存中的点数量也跟此有关,但大于这个数值。
  108190. if (Potree.pointBudget !== value) {
  108191. Potree.pointBudget = parseInt(value);
  108192. this.dispatchEvent({'type': 'point_budget_changed', 'viewer': this});
  108193. }
  108194. };
  108195. getPointBudget () {
  108196. return Potree.pointBudget;
  108197. };
  108198. setShowAnnotations (value) {
  108199. if (this.showAnnotations !== value) {
  108200. this.showAnnotations = value;
  108201. this.dispatchEvent({'type': 'show_annotations_changed', 'viewer': this});
  108202. }
  108203. }
  108204. getShowAnnotations () {
  108205. return this.showAnnotations;
  108206. }
  108207. setDEMCollisionsEnabled(value){
  108208. if(this.useDEMCollisions !== value){
  108209. this.useDEMCollisions = value;
  108210. this.dispatchEvent({'type': 'use_demcollisions_changed', 'viewer': this});
  108211. };
  108212. };
  108213. getDEMCollisionsEnabled () {
  108214. return this.useDEMCollisions;
  108215. };
  108216. setEDLEnabled (value) {
  108217. value = Boolean(value) && Features.SHADER_EDL.isSupported();
  108218. if (this.useEDL !== value) {
  108219. this.useEDL = value;
  108220. this.dispatchEvent({'type': 'use_edl_changed', 'viewer': this});
  108221. this.dispatchEvent('pointcloud_changed');
  108222. }
  108223. };
  108224. getEDLEnabled () {
  108225. return this.useEDL;
  108226. };
  108227. setEDLRadius (value) {
  108228. if (this.edlRadius !== value) {
  108229. this.edlRadius = value;
  108230. this.dispatchEvent({'type': 'edl_radius_changed', 'viewer': this});
  108231. this.dispatchEvent('pointcloud_changed');
  108232. }
  108233. };
  108234. getEDLRadius () {
  108235. return this.edlRadius;
  108236. };
  108237. setEDLStrength (value) {
  108238. if (this.edlStrength !== value) {
  108239. this.edlStrength = value;
  108240. this.dispatchEvent({'type': 'edl_strength_changed', 'viewer': this});
  108241. this.dispatchEvent('pointcloud_changed');
  108242. }
  108243. };
  108244. getEDLStrength () {
  108245. return this.edlStrength;
  108246. };
  108247. setEDLOpacity (value) {
  108248. if (this.edlOpacity !== value) {
  108249. this.edlOpacity = value;
  108250. this.dispatchEvent({'type': 'edl_opacity_changed', 'viewer': this});
  108251. this.dispatchEvent('pointcloud_changed');
  108252. }
  108253. };
  108254. getEDLOpacity () {
  108255. return this.edlOpacity;
  108256. };
  108257. setFOV (value) {
  108258. if (this.fov !== value) {
  108259. let oldFov = this.fov;
  108260. this.fov = value;
  108261. this.scene.cameraP.fov = this.fov; //add
  108262. this.scene.cameraP.updateProjectionMatrix(); //add
  108263. this.dispatchEvent({'type': 'fov_changed', 'viewer': this, oldFov, fov:this.fov});
  108264. }
  108265. };
  108266. getFOV () {
  108267. return this.fov;
  108268. };
  108269. disableAnnotations () {
  108270. this.scene.annotations.traverse(annotation => {
  108271. annotation.domElement.css('pointer-events', 'none');
  108272. // return annotation.visible;
  108273. });
  108274. };
  108275. enableAnnotations () {
  108276. this.scene.annotations.traverse(annotation => {
  108277. annotation.domElement.css('pointer-events', 'auto');
  108278. // return annotation.visible;
  108279. });
  108280. }
  108281. setClassifications(classifications){
  108282. this.classifications = classifications;
  108283. this.dispatchEvent({'type': 'classifications_changed', 'viewer': this});
  108284. }
  108285. setClassificationVisibility (key, value) {
  108286. if (!this.classifications[key]) {
  108287. this.classifications[key] = {visible: value, name: 'no name'};
  108288. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  108289. } else if (this.classifications[key].visible !== value) {
  108290. this.classifications[key].visible = value;
  108291. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  108292. }
  108293. }
  108294. toggleAllClassificationsVisibility(){
  108295. let numVisible = 0;
  108296. let numItems = 0;
  108297. for(const key of Object.keys(this.classifications)){
  108298. if(this.classifications[key].visible){
  108299. numVisible++;
  108300. }
  108301. numItems++;
  108302. }
  108303. let visible = true;
  108304. if(numVisible === numItems){
  108305. visible = false;
  108306. }
  108307. let somethingChanged = false;
  108308. for(const key of Object.keys(this.classifications)){
  108309. if(this.classifications[key].visible !== visible){
  108310. this.classifications[key].visible = visible;
  108311. somethingChanged = true;
  108312. }
  108313. }
  108314. if(somethingChanged){
  108315. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  108316. }
  108317. }
  108318. setFilterReturnNumberRange(from, to){
  108319. this.filterReturnNumberRange = [from, to];
  108320. this.dispatchEvent({'type': 'filter_return_number_range_changed', 'viewer': this});
  108321. }
  108322. setFilterNumberOfReturnsRange(from, to){
  108323. this.filterNumberOfReturnsRange = [from, to];
  108324. this.dispatchEvent({'type': 'filter_number_of_returns_range_changed', 'viewer': this});
  108325. }
  108326. setFilterGPSTimeRange(from, to){
  108327. this.filterGPSTimeRange = [from, to];
  108328. this.dispatchEvent({'type': 'filter_gps_time_range_changed', 'viewer': this});
  108329. }
  108330. setFilterPointSourceIDRange(from, to){
  108331. this.filterPointSourceIDRange = [from, to];
  108332. this.dispatchEvent({'type': 'filter_point_source_id_range_changed', 'viewer': this});
  108333. }
  108334. setLengthUnit (value) {
  108335. switch (value) {
  108336. case 'm':
  108337. this.lengthUnit = LengthUnits.METER;
  108338. this.lengthUnitDisplay = LengthUnits.METER;
  108339. break;
  108340. case 'ft':
  108341. this.lengthUnit = LengthUnits.FEET;
  108342. this.lengthUnitDisplay = LengthUnits.FEET;
  108343. break;
  108344. case 'in':
  108345. this.lengthUnit = LengthUnits.INCH;
  108346. this.lengthUnitDisplay = LengthUnits.INCH;
  108347. break;
  108348. }
  108349. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: value});
  108350. };
  108351. setLengthUnitAndDisplayUnit(lengthUnitValue, lengthUnitDisplayValue) {
  108352. switch (lengthUnitValue) {
  108353. case 'm':
  108354. this.lengthUnit = LengthUnits.METER;
  108355. break;
  108356. case 'ft':
  108357. this.lengthUnit = LengthUnits.FEET;
  108358. break;
  108359. case 'in':
  108360. this.lengthUnit = LengthUnits.INCH;
  108361. break;
  108362. }
  108363. switch (lengthUnitDisplayValue) {
  108364. case 'm':
  108365. this.lengthUnitDisplay = LengthUnits.METER;
  108366. break;
  108367. case 'ft':
  108368. this.lengthUnitDisplay = LengthUnits.FEET;
  108369. break;
  108370. case 'in':
  108371. this.lengthUnitDisplay = LengthUnits.INCH;
  108372. break;
  108373. }
  108374. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: lengthUnitValue });
  108375. };
  108376. zoomTo(node, factor, animationDuration = 0){
  108377. let view = this.scene.view;
  108378. let camera = this.scene.cameraP.clone();
  108379. camera.rotation.copy(this.scene.cameraP.rotation);
  108380. camera.rotation.order = "ZXY";
  108381. camera.rotation.x = Math.PI / 2 + view.pitch;
  108382. camera.rotation.z = view.yaw;
  108383. camera.updateMatrix();
  108384. camera.updateMatrixWorld();
  108385. camera.zoomTo(node, factor);
  108386. let bs;
  108387. if (node.boundingSphere) {
  108388. bs = node.boundingSphere;
  108389. } else if (node.geometry && node.geometry.boundingSphere) {
  108390. bs = node.geometry.boundingSphere;
  108391. } else {
  108392. bs = node.boundingBox.getBoundingSphere(new Sphere());
  108393. }
  108394. bs = bs.clone().applyMatrix4(node.matrixWorld);
  108395. let startPosition = view.position.clone();
  108396. let endPosition = camera.position.clone();
  108397. let startTarget = view.getPivot();
  108398. let endTarget = bs.center;
  108399. let startRadius = view.radius;
  108400. let endRadius = endPosition.distanceTo(endTarget);
  108401. let easing = TWEEN.Easing.Quartic.Out;
  108402. { // animate camera position
  108403. let pos = startPosition.clone();
  108404. let tween = new TWEEN.Tween(pos).to(endPosition, animationDuration);
  108405. tween.easing(easing);
  108406. tween.onUpdate(() => {
  108407. view.position.copy(pos);
  108408. });
  108409. tween.start();
  108410. }
  108411. { // animate camera target
  108412. let target = startTarget.clone();
  108413. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  108414. tween.easing(easing);
  108415. tween.onUpdate(() => {
  108416. view.lookAt(target);
  108417. });
  108418. tween.onComplete(() => {
  108419. view.lookAt(target);
  108420. this.dispatchEvent({type: 'focusing_finished', target: this});
  108421. });
  108422. this.dispatchEvent({type: 'focusing_started', target: this});
  108423. tween.start();
  108424. }
  108425. };
  108426. moveToGpsTimeVicinity(time){
  108427. const result = Potree.Utils.findClosestGpsTime(time, viewer);
  108428. const box = result.node.pointcloud.deepestNodeAt(result.position).getBoundingBox();
  108429. const diameter = box.min.distanceTo(box.max);
  108430. const camera = this.scene.getActiveCamera();
  108431. const offset = camera.getWorldDirection(new Vector3()).multiplyScalar(diameter);
  108432. const newCamPos = result.position.clone().sub(offset);
  108433. this.scene.view.position.copy(newCamPos);
  108434. this.scene.view.lookAt(result.position);
  108435. }
  108436. showAbout () {
  108437. $(function () {
  108438. $('#about-panel').dialog();
  108439. });
  108440. };
  108441. getGpsTimeExtent(){
  108442. const range = [Infinity, -Infinity];
  108443. for(const pointcloud of this.scene.pointclouds){
  108444. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  108445. const aGpsTime = attributes.find(a => a.name === "gps-time");
  108446. if(aGpsTime){
  108447. range[0] = Math.min(range[0], aGpsTime.range[0]);
  108448. range[1] = Math.max(range[1], aGpsTime.range[1]);
  108449. }
  108450. }
  108451. return range;
  108452. }
  108453. fitToScreen (factor = 1, animationDuration = 0) {
  108454. let box = this.getBoundingBox(this.scene.pointclouds);
  108455. let node = new Object3D();
  108456. node.boundingBox = box;
  108457. this.zoomTo(node, factor, animationDuration);
  108458. this.controls.stop();
  108459. };
  108460. toggleNavigationCube() {
  108461. this.navigationCube.visible = !this.navigationCube.visible;
  108462. /* this.viewports.push({
  108463. name:'navigationCube',
  108464. left:0, bottom:0, width:0.2,
  108465. }) */
  108466. }
  108467. /* setView(pos, view) {
  108468. if(!pos) return;
  108469. switch(pos) {
  108470. case "F":
  108471. this.setFrontView(view);
  108472. break;
  108473. case "B":
  108474. this.setBackView(view);
  108475. break;
  108476. case "L":
  108477. this.setLeftView(view);
  108478. break;
  108479. case "R":
  108480. this.setRightView(view);
  108481. break;
  108482. case "U":
  108483. this.setTopView(view);
  108484. break;
  108485. case "D":
  108486. this.setBottomView(view);
  108487. break;
  108488. }
  108489. } */
  108490. setTopView(view){
  108491. view = view || this.scene.view;
  108492. view.setCubeView("top");
  108493. this.fitToScreen();
  108494. };
  108495. setBottomView(){
  108496. this.scene.view.yaw = -Math.PI;
  108497. this.scene.view.pitch = Math.PI / 2;
  108498. this.fitToScreen();
  108499. };
  108500. setFrontView(view){
  108501. view = view || this.scene.view;
  108502. view.yaw = 0;
  108503. view.pitch = 0;
  108504. this.fitToScreen();
  108505. };
  108506. setBackView(view){
  108507. view = view || this.scene.view;
  108508. view.yaw = Math.PI;
  108509. view.pitch = 0;
  108510. this.fitToScreen();
  108511. };
  108512. setLeftView(){
  108513. this.scene.view.yaw = -Math.PI / 2;
  108514. this.scene.view.pitch = 0;
  108515. this.fitToScreen();
  108516. };
  108517. setRightView () {
  108518. this.scene.view.yaw = Math.PI / 2;
  108519. this.scene.view.pitch = 0;
  108520. this.fitToScreen();
  108521. };
  108522. flipYZ () {
  108523. this.isFlipYZ = !this.isFlipYZ;
  108524. // TODO flipyz
  108525. console.log('TODO');
  108526. }
  108527. setCameraMode(mode){
  108528. this.scene.cameraMode = mode;
  108529. for(let pointcloud of this.scene.pointclouds) {
  108530. pointcloud.material.useOrthographicCamera = mode == CameraMode.ORTHOGRAPHIC;
  108531. }
  108532. }
  108533. getProjection(){
  108534. const pointcloud = this.scene.pointclouds[0];
  108535. if(pointcloud){
  108536. return pointcloud.projection;
  108537. }else {
  108538. return null;
  108539. }
  108540. }
  108541. async loadProject(url,done){
  108542. const response = await fetch(url);
  108543. if(response.ok){
  108544. const text = await response.text();
  108545. const json = JSON5.parse(text);
  108546. // const json = JSON.parse(text);
  108547. if(json.type === "Potree"){
  108548. Potree.loadProject(viewer, json, done);
  108549. }
  108550. }else {
  108551. console.warn("未能加载:"+url );
  108552. }
  108553. }
  108554. saveProject(){
  108555. return Potree.saveProject(this);
  108556. }
  108557. loadSettingsFromURL(){
  108558. if(Utils.getParameterByName("pointSize")){
  108559. this.setPointSize(parseFloat(Utils.getParameterByName("pointSize")));
  108560. }
  108561. if(Utils.getParameterByName("FOV")){
  108562. this.setFOV(parseFloat(Utils.getParameterByName("FOV")));
  108563. }
  108564. if(Utils.getParameterByName("opacity")){
  108565. this.setOpacity(parseFloat(Utils.getParameterByName("opacity")));
  108566. }
  108567. if(Utils.getParameterByName("edlEnabled")){
  108568. let enabled = Utils.getParameterByName("edlEnabled") === "true";
  108569. this.setEDLEnabled(enabled);
  108570. }
  108571. if (Utils.getParameterByName('edlRadius')) {
  108572. this.setEDLRadius(parseFloat(Utils.getParameterByName('edlRadius')));
  108573. }
  108574. if (Utils.getParameterByName('edlStrength')) {
  108575. this.setEDLStrength(parseFloat(Utils.getParameterByName('edlStrength')));
  108576. }
  108577. if (Utils.getParameterByName('pointBudget')) {
  108578. this.setPointBudget(parseFloat(Utils.getParameterByName('pointBudget')));
  108579. }
  108580. if (Utils.getParameterByName('showBoundingBox')) {
  108581. let enabled = Utils.getParameterByName('showBoundingBox') === 'true';
  108582. if (enabled) {
  108583. this.setShowBoundingBox(true);
  108584. } else {
  108585. this.setShowBoundingBox(false);
  108586. }
  108587. }
  108588. if (Utils.getParameterByName('material')) {
  108589. let material = Utils.getParameterByName('material');
  108590. this.setMaterial(material);
  108591. }
  108592. if (Utils.getParameterByName('pointSizing')) {
  108593. let sizing = Utils.getParameterByName('pointSizing');
  108594. this.setPointSizing(sizing);
  108595. }
  108596. if (Utils.getParameterByName('quality')) {
  108597. let quality = Utils.getParameterByName('quality');
  108598. this.setQuality(quality);
  108599. }
  108600. if (Utils.getParameterByName('position')) {
  108601. let value = Utils.getParameterByName('position');
  108602. value = value.replace('[', '').replace(']', '');
  108603. let tokens = value.split(';');
  108604. let x = parseFloat(tokens[0]);
  108605. let y = parseFloat(tokens[1]);
  108606. let z = parseFloat(tokens[2]);
  108607. this.scene.view.position.set(x, y, z);
  108608. }
  108609. if (Utils.getParameterByName('target')) {
  108610. let value = Utils.getParameterByName('target');
  108611. value = value.replace('[', '').replace(']', '');
  108612. let tokens = value.split(';');
  108613. let x = parseFloat(tokens[0]);
  108614. let y = parseFloat(tokens[1]);
  108615. let z = parseFloat(tokens[2]);
  108616. this.scene.view.lookAt(new Vector3(x, y, z));
  108617. }
  108618. if (Utils.getParameterByName('background')) {
  108619. let value = Utils.getParameterByName('background');
  108620. this.setBackground(value);
  108621. }
  108622. // if(Utils.getParameterByName("elevationRange")){
  108623. // let value = Utils.getParameterByName("elevationRange");
  108624. // value = value.replace("[", "").replace("]", "");
  108625. // let tokens = value.split(";");
  108626. // let x = parseFloat(tokens[0]);
  108627. // let y = parseFloat(tokens[1]);
  108628. //
  108629. // this.setElevationRange(x, y);
  108630. // //this.scene.view.target.set(x, y, z);
  108631. // }
  108632. };
  108633. // ------------------------------------------------------------------------------------
  108634. // Viewer Internals
  108635. // ------------------------------------------------------------------------------------
  108636. createControls () {
  108637. { // create FIRST PERSON CONTROLS
  108638. this.fpControls = new FirstPersonControls(this, this.mainViewport);
  108639. this.fpControls.enabled = false;
  108640. this.fpControls.addEventListener('start', this.disableAnnotations.bind(this));
  108641. this.fpControls.addEventListener('end', this.enableAnnotations.bind(this));
  108642. /* this.addEventListener("loadPointCloudDone", ()=>{
  108643. let boundPlane = new THREE.Box3()
  108644. boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低
  108645. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度
  108646. FirstPersonControls.boundPlane = boundPlane
  108647. FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  108648. }) */
  108649. }
  108650. // { // create GEO CONTROLS
  108651. // this.geoControls = new GeoControls(this.scene.camera, this.renderer.domElement);
  108652. // this.geoControls.enabled = false;
  108653. // this.geoControls.addEventListener("start", this.disableAnnotations.bind(this));
  108654. // this.geoControls.addEventListener("end", this.enableAnnotations.bind(this));
  108655. // this.geoControls.addEventListener("move_speed_changed", (event) => {
  108656. // this.setMoveSpeed(this.geoControls.moveSpeed);
  108657. // });
  108658. // }
  108659. { // create ORBIT CONTROLS
  108660. this.orbitControls = new OrbitControls(this);
  108661. this.orbitControls.enabled = false;
  108662. this.orbitControls.addEventListener('start', this.disableAnnotations.bind(this));
  108663. this.orbitControls.addEventListener('end', this.enableAnnotations.bind(this));
  108664. }
  108665. /* { // create EARTH CONTROLS
  108666. this.earthControls = new EarthControls(this);
  108667. this.earthControls.enabled = false;
  108668. this.earthControls.addEventListener('start', this.disableAnnotations.bind(this));
  108669. this.earthControls.addEventListener('end', this.enableAnnotations.bind(this));
  108670. }
  108671. { // create DEVICE ORIENTATION CONTROLS
  108672. this.deviceControls = new DeviceOrientationControls(this);
  108673. this.deviceControls.enabled = false;
  108674. this.deviceControls.addEventListener('start', this.disableAnnotations.bind(this));
  108675. this.deviceControls.addEventListener('end', this.enableAnnotations.bind(this));
  108676. } */
  108677. /* { // create VR CONTROLS
  108678. this.vrControls = new VRControls(this);
  108679. this.vrControls.enabled = false;
  108680. this.vrControls.addEventListener('start', this.disableAnnotations.bind(this));
  108681. this.vrControls.addEventListener('end', this.enableAnnotations.bind(this));
  108682. } */
  108683. };
  108684. toggleSidebar () {
  108685. let renderArea = $('#potree_render_area');
  108686. let isVisible = renderArea.css('left') !== '0px';
  108687. if (isVisible) {
  108688. renderArea.css('left', '0px');
  108689. } else {
  108690. renderArea.css('left', '300px');
  108691. }
  108692. };
  108693. toggleMap () {
  108694. // let map = $('#potree_map');
  108695. // map.toggle(100);
  108696. if (this.mapView) {
  108697. this.mapView.toggle();
  108698. }
  108699. };
  108700. onGUILoaded(callback){
  108701. if(this.guiLoaded){
  108702. callback();
  108703. }else {
  108704. this.guiLoadTasks.push(callback);
  108705. }
  108706. }
  108707. promiseGuiLoaded(){
  108708. return new Promise( resolve => {
  108709. if(this.guiLoaded){
  108710. resolve();
  108711. }else {
  108712. this.guiLoadTasks.push(resolve);
  108713. }
  108714. });
  108715. }
  108716. loadGUI(callback){
  108717. if(callback){
  108718. this.onGUILoaded(callback);
  108719. }
  108720. let viewer = this;
  108721. let sidebarContainer = $('#potree_sidebar_container');
  108722. sidebarContainer.load(new URL(Potree.scriptPath + '/' + (Potree.settings.sidebar || 'sidebar1.html')).href, () => {
  108723. sidebarContainer.css('width', '300px');
  108724. sidebarContainer.css('height', '100%');
  108725. let imgMenuToggle = document.createElement('img');
  108726. imgMenuToggle.src = new URL(Potree.resourcePath + '/icons/menu_button.svg').href;
  108727. imgMenuToggle.onclick = this.toggleSidebar;
  108728. imgMenuToggle.classList.add('potree_menu_toggle');
  108729. let imgMapToggle = document.createElement('img');
  108730. imgMapToggle.src = new URL(Potree.resourcePath + '/icons/map_icon.png').href;
  108731. imgMapToggle.style.display = 'none';
  108732. imgMapToggle.onclick = e => { this.toggleMap(); };
  108733. imgMapToggle.id = 'potree_map_toggle';
  108734. let elButtons = $("#potree_quick_buttons").get(0);
  108735. elButtons.append(imgMenuToggle);
  108736. elButtons.append(imgMapToggle);
  108737. VRButton.createButton(this.renderer).then(vrButton => {
  108738. if(vrButton == null){
  108739. console.log("VR not supported or active.");
  108740. return;
  108741. }
  108742. this.renderer.xr.enabled = true;
  108743. let element = vrButton.element;
  108744. element.style.position = "";
  108745. element.style.bottom = "";
  108746. element.style.left = "";
  108747. element.style.margin = "4px";
  108748. element.style.fontSize = "100%";
  108749. element.style.width = "2.5em";
  108750. element.style.height = "2.5em";
  108751. element.style.padding = "0";
  108752. element.style.textShadow = "black 2px 2px 2px";
  108753. element.style.display = "block";
  108754. elButtons.append(element);
  108755. vrButton.onStart(() => {
  108756. this.dispatchEvent({type: "vr_start"});
  108757. });
  108758. vrButton.onEnd(() => {
  108759. this.dispatchEvent({type: "vr_end"});
  108760. });
  108761. });
  108762. /* this.mapView = new MapView(this);
  108763. this.mapView.init(); */
  108764. i18n.init({
  108765. lng: 'en',
  108766. resGetPath: Potree.resourcePath + '/lang/__lng__/__ns__.json',
  108767. preload: ['en', 'fr', 'de', 'jp', 'se', 'es', 'zh'],
  108768. getAsync: true,
  108769. debug: false
  108770. }, function (t) {
  108771. // Start translation once everything is loaded
  108772. $('body').i18n();
  108773. });
  108774. $(() => {
  108775. //initSidebar(this);
  108776. let sidebar = new Sidebar(this);
  108777. sidebar.init();
  108778. this.sidebar = sidebar;
  108779. //if (callback) {
  108780. // $(callback);
  108781. //}
  108782. let elProfile = $('<div>').load(new URL(Potree.scriptPath + '/profile.html').href, () => {
  108783. $(document.body).append(elProfile.children());
  108784. this.profileWindow = new ProfileWindow(this);
  108785. this.profileWindowController = new ProfileWindowController(this);
  108786. $('#profile_window').draggable({
  108787. handle: $('#profile_titlebar'),
  108788. containment: $(document.body)
  108789. });
  108790. $('#profile_window').resizable({
  108791. containment: $(document.body),
  108792. handles: 'n, e, s, w'
  108793. });
  108794. $(() => {
  108795. this.guiLoaded = true;
  108796. for(let task of this.guiLoadTasks){
  108797. task();
  108798. }
  108799. });
  108800. });
  108801. });
  108802. });
  108803. return this.promiseGuiLoaded();
  108804. }
  108805. setLanguage (lang) {
  108806. i18n.setLng(lang);
  108807. $('body').i18n();
  108808. }
  108809. setServer (server) {
  108810. this.server = server;
  108811. }
  108812. initDragAndDrop(){
  108813. function allowDrag(e) {
  108814. e.dataTransfer.dropEffect = 'copy';
  108815. e.preventDefault();
  108816. }
  108817. let dropHandler = async (event) => {
  108818. console.log(event);
  108819. event.preventDefault();
  108820. for(const item of event.dataTransfer.items){
  108821. console.log(item);
  108822. if(item.kind !== "file"){
  108823. continue;
  108824. }
  108825. const file = item.getAsFile();
  108826. const isJson = file.name.toLowerCase().endsWith(".json");
  108827. const isGeoPackage = file.name.toLowerCase().endsWith(".gpkg");
  108828. if(isJson){
  108829. try{
  108830. const text = await file.text();
  108831. const json = JSON.parse(text);
  108832. if(json.type === "Potree"){
  108833. Potree.loadProject(viewer, json);
  108834. }
  108835. }catch(e){
  108836. console.error("failed to parse the dropped file as JSON");
  108837. console.error(e);
  108838. }
  108839. }else if(isGeoPackage){
  108840. const hasPointcloud = viewer.scene.pointclouds.length > 0;
  108841. if(!hasPointcloud){
  108842. let msg = "At least one point cloud is needed that specifies the ";
  108843. msg += "coordinate reference system before loading vector data.";
  108844. console.error(msg);
  108845. }else {
  108846. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  108847. proj4.defs("pointcloud", this.getProjection());
  108848. let transform = proj4("WGS84", "pointcloud");
  108849. const buffer = await file.arrayBuffer();
  108850. const params = {
  108851. transform: transform,
  108852. source: file.name,
  108853. };
  108854. const geo = await Potree.GeoPackageLoader.loadBuffer(buffer, params);
  108855. viewer.scene.addGeopackage(geo);
  108856. }
  108857. }
  108858. }
  108859. };
  108860. $("body")[0].addEventListener("dragenter", allowDrag);
  108861. $("body")[0].addEventListener("dragover", allowDrag);
  108862. $("body")[0].addEventListener("drop", dropHandler);
  108863. }
  108864. updateAnnotations () {
  108865. if(!this.visibleAnnotations){
  108866. this.visibleAnnotations = new Set();
  108867. }
  108868. this.scene.annotations.updateBounds();
  108869. this.scene.cameraP.updateMatrixWorld();
  108870. this.scene.cameraO.updateMatrixWorld();
  108871. let distances = [];
  108872. let renderAreaSize = this.renderer.getSize(new Vector2());
  108873. let viewer = this;
  108874. let visibleNow = [];
  108875. this.scene.annotations.traverse(annotation => {
  108876. if (annotation === this.scene.annotations) {
  108877. return true;
  108878. }
  108879. if (!annotation.visible) {
  108880. return false;
  108881. }
  108882. annotation.scene = this.scene;
  108883. let element = annotation.domElement;
  108884. let position = annotation.position.clone();
  108885. position.add(annotation.offset);
  108886. if (!position) {
  108887. position = annotation.boundingBox.getCenter(new Vector3());
  108888. }
  108889. let distance = viewer.scene.cameraP.position.distanceTo(position);
  108890. let radius = annotation.boundingBox.getBoundingSphere(new Sphere()).radius;
  108891. let screenPos = new Vector3();
  108892. let screenSize = 0;
  108893. {
  108894. // SCREEN POS
  108895. screenPos.copy(position).project(this.scene.getActiveCamera());
  108896. screenPos.x = renderAreaSize.x * (screenPos.x + 1) / 2;
  108897. screenPos.y = renderAreaSize.y * (1 - (screenPos.y + 1) / 2);
  108898. // SCREEN SIZE
  108899. if(viewer.scene.cameraMode == CameraMode.PERSPECTIVE) {
  108900. let fov = Math.PI * viewer.scene.cameraP.fov / 180;
  108901. let slope = Math.tan(fov / 2.0);
  108902. let projFactor = 0.5 * renderAreaSize.y / (slope * distance);
  108903. screenSize = radius * projFactor;
  108904. } else {
  108905. screenSize = Utils.projectedRadiusOrtho(radius, viewer.scene.cameraO.projectionMatrix, renderAreaSize.x, renderAreaSize.y);
  108906. }
  108907. }
  108908. element.css("left", screenPos.x + "px");
  108909. element.css("top", screenPos.y + "px");
  108910. //element.css("display", "block");
  108911. let zIndex = 10000000 - distance * (10000000 / this.scene.cameraP.far);
  108912. if(annotation.descriptionVisible){
  108913. zIndex += 10000000;
  108914. }
  108915. element.css("z-index", parseInt(zIndex));
  108916. if(annotation.children.length > 0){
  108917. let expand = screenSize > annotation.collapseThreshold || annotation.boundingBox.containsPoint(this.scene.getActiveCamera().position);
  108918. annotation.expand = expand;
  108919. if (!expand) {
  108920. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  108921. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  108922. if(inFrustum){
  108923. visibleNow.push(annotation);
  108924. }
  108925. }
  108926. return expand;
  108927. } else {
  108928. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  108929. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  108930. if(inFrustum){
  108931. visibleNow.push(annotation);
  108932. }
  108933. }
  108934. });
  108935. let notVisibleAnymore = new Set(this.visibleAnnotations);
  108936. for(let annotation of visibleNow){
  108937. annotation.display = true;
  108938. notVisibleAnymore.delete(annotation);
  108939. }
  108940. this.visibleAnnotations = visibleNow;
  108941. for(let annotation of notVisibleAnymore){
  108942. annotation.display = false;
  108943. }
  108944. }
  108945. updateMaterialDefaults(pointcloud){
  108946. // PROBLEM STATEMENT:
  108947. // * [min, max] of intensity, source id, etc. are computed as point clouds are loaded
  108948. // * the point cloud material won't know the range it should use until some data is loaded
  108949. // * users can modify the range at runtime, but sensible default ranges should be
  108950. // applied even if no GUI is present
  108951. // * display ranges shouldn't suddenly change even if the actual range changes over time.
  108952. // e.g. the root node has intensity range [1, 478]. One of the descendants increases range to
  108953. // [0, 2047]. We should not automatically change to the new range because that would result
  108954. // in sudden and drastic changes of brightness. We should adjust the min/max of the sidebar slider.
  108955. const material = pointcloud.material;
  108956. const attIntensity = pointcloud.getAttribute("intensity");
  108957. if(attIntensity != null && material.intensityRange[0] === Infinity){
  108958. material.intensityRange = [...attIntensity.range];
  108959. }
  108960. // const attIntensity = pointcloud.getAttribute("intensity");
  108961. // if(attIntensity && material.intensityRange[0] === Infinity){
  108962. // material.intensityRange = [...attIntensity.range];
  108963. // }
  108964. // let attributes = pointcloud.getAttributes();
  108965. // for(let attribute of attributes.attributes){
  108966. // if(attribute.range){
  108967. // let range = [...attribute.range];
  108968. // material.computedRange.set(attribute.name, range);
  108969. // //material.setRange(attribute.name, range);
  108970. // }
  108971. // }
  108972. }
  108973. update(delta, timestamp){
  108974. viewer.addTimeMark('update','start');
  108975. TWEEN.update(timestamp);
  108976. transitions.update(delta);//写在开头,因为这时候最为固定,计时准确
  108977. this.dispatchEvent({
  108978. type: 'update_start',
  108979. delta: delta,
  108980. timestamp: timestamp});
  108981. this.updateScreenSize(); //判断是否改变canvas大小
  108982. const scene = this.scene;
  108983. const camera = scene.getActiveCamera();
  108984. const visiblePointClouds = this.scene.pointclouds.filter(pc => pc.visible);
  108985. Potree.pointLoadLimit = Potree.pointBudget * 2;
  108986. /* const lTarget = camera.position.clone().add(camera.getWorldDirection(new THREE.Vector3()).multiplyScalar(1000));
  108987. this.scene.directionalLight.position.copy(camera.position);
  108988. this.scene.directionalLight.lookAt(lTarget); */
  108989. for (let pointcloud of visiblePointClouds) {
  108990. pointcloud.showBoundingBox = this.showBoundingBox;
  108991. pointcloud.generateDEM = this.generateDEM;
  108992. pointcloud.minimumNodePixelSize = this.minNodeSize;
  108993. let material = pointcloud.material;
  108994. material.uniforms.uFilterReturnNumberRange.value = this.filterReturnNumberRange;
  108995. material.uniforms.uFilterNumberOfReturnsRange.value = this.filterNumberOfReturnsRange;
  108996. material.uniforms.uFilterGPSTimeClipRange.value = this.filterGPSTimeRange;
  108997. material.uniforms.uFilterPointSourceIDClipRange.value = this.filterPointSourceIDRange;
  108998. material.classification = this.classifications;
  108999. material.recomputeClassification();
  109000. this.updateMaterialDefaults(pointcloud);
  109001. }
  109002. {
  109003. if(this.showBoundingBox){
  109004. let bbRoot = this.scene.scene.getObjectByName("potree_bounding_box_root");
  109005. if(!bbRoot){
  109006. let node = new Object3D();
  109007. node.name = "potree_bounding_box_root";
  109008. this.scene.scene.add(node);
  109009. bbRoot = node;
  109010. }
  109011. let visibleBoxes = [];
  109012. for(let pointcloud of this.scene.pointclouds){
  109013. for(let node of pointcloud.visibleNodes.filter(vn => vn.boundingBoxNode !== undefined)){
  109014. let box = node.boundingBoxNode;
  109015. visibleBoxes.push(box);
  109016. }
  109017. }
  109018. bbRoot.children = visibleBoxes;
  109019. }
  109020. }
  109021. if(this.boundNeedUpdate)this.updateModelBound(); //add
  109022. this.scene.cameraP.fov = this.fov;
  109023. let controls = this.getControls();
  109024. if (controls === this.deviceControls) {
  109025. this.controls.setScene(scene);
  109026. this.controls.update(delta);
  109027. this.scene.cameraP.position.copy(scene.view.position);
  109028. this.scene.cameraO.position.copy(scene.view.position);
  109029. } else if (controls !== null) {
  109030. controls.setScene(scene);
  109031. controls.update(delta);
  109032. //更新camera
  109033. this.viewports.forEach(viewport=>{
  109034. if(!viewport.active)return
  109035. viewport.view.applyToCamera(viewport.camera);
  109036. });
  109037. }
  109038. this.lastFrameChanged = this.cameraChanged();//判断camera画面是否改变
  109039. { // update clip boxes
  109040. let boxes = [];
  109041. // volumes with clipping enabled
  109042. boxes.push(...this.scene.volumes.filter(v => (v.clip && v instanceof BoxVolume$1)));
  109043. // profile segments
  109044. for(let profile of this.scene.profiles){
  109045. boxes.push(...profile.boxes);
  109046. }
  109047. // Needed for .getInverse(), pre-empt a determinant of 0, see #815 / #816
  109048. let degenerate = (box) => box.matrixWorld.determinant() !== 0;
  109049. let clipBoxes = boxes.filter(degenerate).map( box => {
  109050. box.updateMatrixWorld();
  109051. let boxInverse = box.matrixWorld.clone().invert();
  109052. //let boxPosition = box.getWorldPosition(new THREE.Vector3());
  109053. return {box: box, inverse: boxInverse/* , position: boxPosition */};
  109054. });
  109055. //改
  109056. let bigClipInBox = clipBoxes.find(e=>e.box.clipTask == ClipTask.SHOW_INSIDE_Big && !e.box.highlight);//裁剪下载 when this.modules.Clip.editing
  109057. let clipBoxes_in = clipBoxes.filter(e=>e.box.clipTask == ClipTask.SHOW_INSIDE && !e.box.highlight);
  109058. let clipBoxes_out = clipBoxes.filter(e=>e.box.clipTask == ClipTask.SHOW_OUTSIDE && !e.box.highlight);
  109059. let highlightBoxes = clipBoxes.filter(e=>e.box.highlight );
  109060. // set clip volumes in material
  109061. for(let pointcloud of visiblePointClouds){
  109062. let clipBoxes_in2 = [], clipBoxes_out2 = [], highlightBoxes2 = [];
  109063. if(pointcloud.dataset_id == Potree.settings.originDatasetId){ //实时裁剪只对初始数据集有效
  109064. clipBoxes_in2 = clipBoxes_in, clipBoxes_out2 = clipBoxes_out, highlightBoxes2 = highlightBoxes;
  109065. }
  109066. pointcloud.material.setClipBoxes(bigClipInBox, clipBoxes_in2, clipBoxes_out2, highlightBoxes2);
  109067. }
  109068. }
  109069. {
  109070. for(let pointcloud of visiblePointClouds){
  109071. pointcloud.material.elevationGradientRepeat = this.elevationGradientRepeat;
  109072. }
  109073. }
  109074. { // update navigation cube
  109075. this.navigationCube.update(camera.rotation);
  109076. }
  109077. this.updateAnnotations();
  109078. if(this.mapView){
  109079. this.mapView.update(delta);
  109080. if(this.mapView.sceneProjection){
  109081. $( "#potree_map_toggle" ).css("display", "block");
  109082. }
  109083. }
  109084. this.transformationTool.update();
  109085. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  109086. this.modules.ParticleEditor.update(delta);
  109087. this.mapViewer.update(delta); //地图更新
  109088. }
  109089. this.dispatchEvent({ type: 'update', delta: delta, timestamp: timestamp}); //在有sidebar时耗高cpu,占本update函数80%
  109090. viewer.addTimeMark('update','end');
  109091. //add ------
  109092. this.reticule.updateVisible();
  109093. }
  109094. updateViewPointcloud(camera, areaSize, isViewport){
  109095. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, areaSize );
  109096. //if(isViewport)return
  109097. const tStart = performance.now();
  109098. const campos = camera.position;
  109099. let closestImage = Infinity;
  109100. for(const images of this.scene.orientedImages){
  109101. for(const image of images.images){
  109102. const distance = image.mesh.position.distanceTo(campos);
  109103. closestImage = Math.min(closestImage, distance);
  109104. }
  109105. }
  109106. //const tEnd = performance.now();
  109107. //改:不根据点云修改视野near far
  109108. var near = camera.near, far = camera.far;
  109109. if(!camera.limitFar && result.lowestSpacing !== Infinity){
  109110. //let near = result.lowestSpacing * 10.0;
  109111. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  109112. far = Math.max(far * 1.5, 10000);
  109113. //near = Math.min(100.0, Math.max(0.01, near));
  109114. //near = Math.min(near, closestImage);
  109115. far = Math.max(far, near + 10000);
  109116. /* if(near === Infinity){
  109117. near = 0.1;
  109118. } */
  109119. //camera.near = near; //为了其他物体的显示,不修改near
  109120. camera.far = far;
  109121. }
  109122. /* if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {//???
  109123. camera.near = -camera.far;
  109124. } */
  109125. if(/* near != camera.near || */far != camera.far){
  109126. camera.updateProjectionMatrix();
  109127. }
  109128. //注:pointcloud.visibleNodes会随着near far自动更新
  109129. }
  109130. getPRenderer(){
  109131. if(this.useHQ){
  109132. if (!this.hqRenderer) {
  109133. this.hqRenderer = new HQSplatRenderer(this);
  109134. }
  109135. this.hqRenderer.useEDL = this.useEDL;
  109136. return this.hqRenderer;
  109137. }else {
  109138. /* if (this.useEDL && Features.SHADER_EDL.isSupported()) {
  109139. if (!this.edlRenderer) {
  109140. this.edlRenderer = new EDLRenderer(this);
  109141. }
  109142. return this.edlRenderer;
  109143. } else {
  109144. if (!this.potreeRenderer) {
  109145. this.potreeRenderer = new PotreeRenderer(this);
  109146. }
  109147. return this.potreeRenderer;
  109148. } */
  109149. if (!this.edlRenderer) {
  109150. this.edlRenderer = new EDLRenderer(this);
  109151. }
  109152. return this.edlRenderer;
  109153. }
  109154. }
  109155. renderVR(){//渲染部分没改完
  109156. let renderer = this.renderer;
  109157. renderer.setClearColor(0x550000, 0);
  109158. renderer.clear();
  109159. let xr = renderer.xr;
  109160. let dbg = new PerspectiveCamera();
  109161. let xrCameras = xr.getCamera(dbg);
  109162. if(xrCameras.cameras.length !== 2){
  109163. return;
  109164. }
  109165. let makeCam = this.vrControls.getCamera.bind(this.vrControls);
  109166. { // clear framebuffer
  109167. if(viewer.background === "skybox"){
  109168. renderer.setClearColor(0xff0000, 1);
  109169. }else if(viewer.background === "gradient"){
  109170. renderer.setClearColor(0x112233, 1);
  109171. }else if(viewer.background === "black"){
  109172. renderer.setClearColor(0x000000, 1);
  109173. }else if(viewer.background === "white"){
  109174. renderer.setClearColor(0xFFFFFF, 1);
  109175. }else {
  109176. renderer.setClearColor(0x000000, 0);
  109177. }
  109178. renderer.clear();
  109179. }
  109180. // render background
  109181. if(this.background === "skybox"){
  109182. let {skybox} = this;
  109183. let cam = makeCam();
  109184. skybox.camera.rotation.copy(cam.rotation);
  109185. skybox.camera.fov = cam.fov;
  109186. skybox.camera.aspect = cam.aspect;
  109187. // let dbg = new THREE.Object3D();
  109188. let dbg = skybox.parent;
  109189. // dbg.up.set(0, 0, 1);
  109190. dbg.rotation.x = Math.PI / 2;
  109191. // skybox.camera.parent = dbg;
  109192. // dbg.children.push(skybox.camera);
  109193. dbg.updateMatrix();
  109194. dbg.updateMatrixWorld();
  109195. skybox.camera.updateMatrix();
  109196. skybox.camera.updateMatrixWorld();
  109197. skybox.camera.updateProjectionMatrix();
  109198. renderer.render(skybox.scene, skybox.camera);
  109199. // renderer.render(skybox.scene, cam);
  109200. }else if(this.background === "gradient"){
  109201. // renderer.render(this.scene.sceneBG, this.scene.cameraBG);
  109202. }
  109203. this.renderer.xr.getSession().updateRenderState({
  109204. depthNear: 0.1,
  109205. depthFar: 10000
  109206. });
  109207. let cam = null;
  109208. let view = null;
  109209. { // render world scene
  109210. cam = makeCam();
  109211. cam.position.z -= 0.8 * cam.scale.x;
  109212. cam.parent = null;
  109213. // cam.near = 0.05;
  109214. cam.near = viewer.scene.getActiveCamera().near;
  109215. cam.far = viewer.scene.getActiveCamera().far;
  109216. cam.updateMatrix();
  109217. cam.updateMatrixWorld();
  109218. this.scene.scene.updateMatrix();
  109219. this.scene.scene.updateMatrixWorld();
  109220. this.scene.scene.matrixAutoUpdate = false;
  109221. let camWorld = cam.matrixWorld.clone();
  109222. view = camWorld.clone().invert();
  109223. this.scene.scene.matrix.copy(view);
  109224. this.scene.scene.matrixWorld.copy(view);
  109225. cam.matrix.identity();
  109226. cam.matrixWorld.identity();
  109227. cam.matrixWorldInverse.identity();
  109228. renderer.render(this.scene.scene, cam);
  109229. this.scene.scene.matrixWorld.identity();
  109230. }
  109231. for(let pointcloud of this.scene.pointclouds){
  109232. let viewport = xrCameras.cameras[0].viewport;
  109233. pointcloud.material.useEDL = false;
  109234. pointcloud.screenHeight = viewport.height;
  109235. pointcloud.screenWidth = viewport.width;
  109236. // automatically switch to paraboloids because they cause far less flickering in VR,
  109237. // when point sizes are larger than around 2 pixels
  109238. // if(Features.SHADER_INTERPOLATION.isSupported()){
  109239. // pointcloud.material.shape = Potree.PointShape.PARABOLOID;
  109240. // }
  109241. }
  109242. // render point clouds
  109243. for(let xrCamera of xrCameras.cameras){
  109244. let v = xrCamera.viewport;
  109245. renderer.setViewport(v.x, v.y, v.width, v.height);
  109246. // xrCamera.fov = 90;
  109247. { // estimate VR fov
  109248. let proj = xrCamera.projectionMatrix;
  109249. let inv = proj.clone().invert();
  109250. let p1 = new Vector4(0, 1, -1, 1).applyMatrix4(inv);
  109251. let rad = p1.y;
  109252. let fov = 180 * (rad / Math.PI);
  109253. xrCamera.fov = fov;
  109254. }
  109255. for(let pointcloud of this.scene.pointclouds){
  109256. const {material} = pointcloud;
  109257. material.useEDL = false;
  109258. }
  109259. let vrWorld = view.clone().invert();
  109260. vrWorld.multiply(xrCamera.matrixWorld);
  109261. let vrView = vrWorld.clone().invert();
  109262. this.pRenderer.render(this.scene.scenePointCloud, xrCamera, null, {
  109263. viewOverride: vrView,
  109264. });
  109265. }
  109266. { // render VR scene
  109267. let cam = makeCam();
  109268. cam.parent = null;
  109269. renderer.render(this.sceneVR, cam);
  109270. }
  109271. renderer.resetState();
  109272. }
  109273. clear(params={}){
  109274. let background = params.background || this.background;
  109275. let backgroundOpacity = params.backgroundOpacity == void 0 ? this.backgroundOpacity : params.backgroundOpacity;//如果想完全透明,只需要backgroundOpacity为0
  109276. let renderer = this.renderer;
  109277. //let gl = renderer.getContext()
  109278. if(background instanceof Color){ //add
  109279. renderer.setClearColor(background, backgroundOpacity);
  109280. }else if(background === "skybox"){
  109281. renderer.setClearColor(0x000000, 0 );
  109282. } else if (background === 'gradient') {
  109283. renderer.setClearColor(0x000000, 0);
  109284. } else if (background === 'black') {
  109285. renderer.setClearColor(0x000000, 1);
  109286. } else if (background === 'white') {
  109287. renderer.setClearColor(0xFFFFFF, 1);
  109288. } else {
  109289. renderer.setClearColor(background, backgroundOpacity);
  109290. }
  109291. params.target || renderer.clear();
  109292. }
  109293. getBuffer(viewport){//根据不同viewport返回rtEDL的texture
  109294. var buffer = this.buffers.get(viewport);
  109295. if(!buffer){
  109296. buffer = new WebGLRenderTarget(viewport.resolution.x, viewport.resolution.y, {
  109297. minFilter: NearestFilter,
  109298. magFilter: NearestFilter,
  109299. format: RGBAFormat,
  109300. type: FloatType
  109301. });
  109302. this.buffers.set(viewport, rtEDL);
  109303. }
  109304. return buffer
  109305. }
  109306. renderDefault(params_={}){
  109307. if(!this.visible )return
  109308. let pRenderer = this.getPRenderer();
  109309. let viewports = params_.viewports || this.viewports;
  109310. viewer.addTimeMark('renderDefault','start');
  109311. //console.log('render', viewports.map(e=>e.name).join(','))
  109312. let renderSize;
  109313. if(params_.target){
  109314. renderSize = new Vector2(params_.target.width, params_.target.height); //是画布大小
  109315. //可能需要viewer.setSize
  109316. }else {
  109317. renderSize = this.renderer.getSize(new Vector2()); //是client大小
  109318. }
  109319. ///let needsResize = viewports.length > 1 || params_.resize //去掉原因:因为不需要渲染的viewport不在此中所以无法判断几个viewport
  109320. viewports.forEach(view=>{
  109321. let params = $.extend({},params_);
  109322. params.viewport = view;
  109323. //if(!params.target){
  109324. params.camera = params.camera || view.camera;
  109325. params.extraEnableLayers = view.extraEnableLayers;
  109326. params.cameraLayers = view.cameraLayers;
  109327. //}
  109328. var left,bottom,width,height;
  109329. {
  109330. left = Math.ceil(renderSize.x * view.left);
  109331. bottom = Math.ceil(renderSize.y * view.bottom);
  109332. if(params_.target){//有target时最好viewport是专门建出来的
  109333. width = Math.ceil(renderSize.x * view.width); //target的大小可能和viewport不同,比如截图,这时会更改viewport大小
  109334. height = Math.ceil(renderSize.y * view.height);
  109335. }else {
  109336. width = view.resolution.x; // 用的是client的width和height
  109337. height = view.resolution.y;
  109338. }
  109339. if(width == 0 || height == 0)return
  109340. let scissorTest = view.width<1 || view.height<1;
  109341. if(params_.target){
  109342. params_.target.viewport.set(left, bottom, width, height);
  109343. scissorTest && params_.target.scissor.set(left, bottom, width, height);
  109344. params_.target.scissorTest = scissorTest;
  109345. this.renderer.setRenderTarget(params_.target);
  109346. }else {
  109347. /* if(viewports.length == 1 && left == 0 && bottom == 0){
  109348. left = 1 , width-=1 //这种情况下渲染也会有问题,只有鼠标的地方刷新
  109349. } */
  109350. if(scissorTest && left == 0 && bottom == 0){
  109351. left = 1 , width-=1;
  109352. }
  109353. this.renderer.setViewport(left, bottom, width, height); //规定视口,影响图形变换(画布的使用范围)
  109354. scissorTest && this.renderer.setScissor( left, bottom, width, height );//规定渲染范围
  109355. this.renderer.setScissorTest( scissorTest );//开启WebGL剪裁测试功能,如果不开启,.setScissor方法设置的范围不起作用 | width==1且height==1时开启会只有鼠标的地方刷新,很奇怪
  109356. }
  109357. }
  109358. //if(needsResize){
  109359. this.ifEmitResize( { viewport:view} );
  109360. //}
  109361. viewer.dispatchEvent({type: "render.begin", viewer: viewer, viewport:view, params });
  109362. view.beforeRender && view.beforeRender();
  109363. if(view.render){
  109364. if(!view.render($.extend({}, params, {
  109365. renderer:this.renderer, clear:this.clear.bind(this), resize:null,
  109366. renderBG:this.renderBG.bind(this), force:true //viewer content_change时map也直接渲染吧 //!view.noPointcloud //如果要渲染点云,必须也一直渲染地图,否则地图会被覆盖(点云目前未能获取是否改变,也可能有其他动态物体,所以还是一直渲染的好)
  109367. })))return
  109368. }else {
  109369. this.clear(params);
  109370. pRenderer.clearTargets(params);
  109371. this.renderBG(view);
  109372. if(Potree.settings.notAdditiveBlending){
  109373. params.renderBeforeCloud = true;
  109374. this.renderOverlay1(params); //先渲染不透明的model。 但drawedModelOnRT时这里提前多渲染了一遍
  109375. }
  109376. }
  109377. if(!view.noPointcloud ){
  109378. this.updateViewPointcloud(params.camera, view.resolution, true);
  109379. pRenderer.render(params); //渲染点云 skybox
  109380. }
  109381. if(Potree.settings.notAdditiveBlending){ // 融合页面才用到
  109382. params.renderBeforeCloud = false;
  109383. this.renderOverlay1(params);
  109384. this.renderOverlay2(params);
  109385. }else {
  109386. this.renderOverlay(params);
  109387. }
  109388. view.afterRender && view.afterRender();
  109389. this.dispatchEvent({type: "render.end", viewer: this, viewport:view });
  109390. view.needRender = false;
  109391. view.lastRenderTime = Date.now();
  109392. });
  109393. /* if(params_.screenshot){ //抗锯齿
  109394. this.composer.render();
  109395. } */
  109396. this.renderer.setRenderTarget(null);
  109397. viewer.scene.pointclouds[0] && this.addFakeMeasure('visibleNodes', viewer.scene.pointclouds[0].visibleNodes.length );//
  109398. this.addFakeMeasure('numVisiblePoints', Potree.numVisiblePoints/100000);//十万 numVisiblePoints和帧率成反比(若每一帧都render的话),和render用时成正比 (y=kn+b)。但visibleNodes个数也影响,多的话也更卡。visibleNodes和numVisiblePoints不成正比,少的visibleNodes可能numVisiblePoints多
  109399. viewer.addTimeMark('renderDefault','end');
  109400. }
  109401. renderBG(view){
  109402. let background = view.background || viewer.background;
  109403. let backgroundOpacity = view.backgroundOpacity == void 0 ? viewer.backgroundOpacity : view.backgroundOpacity;//如果想完全透明,只需要backgroundOpacity为0
  109404. if(backgroundOpacity != 0){//绘制背景
  109405. if(background === "skybox"){
  109406. //限制相机到原点的距离。
  109407. let skyCamera = view.camera.type == "OrthographicCamera" ? viewer.skybox.cameraOrtho : viewer.skybox.camera;
  109408. let safeRatio = 0.02;
  109409. let safeWidth = Potree.config.skyboxBgWidth * safeRatio / 2; //相机只能在这个范围内移动
  109410. if(!view.skyboxFixPos){ //允许不在全景图中心,允许位移造成一定程度畸变
  109411. let dir = new Vector3().subVectors(view.camera.position, viewer.bound.center);
  109412. let length = dir.length();
  109413. const moveMax = 100;
  109414. let aimRadius = easing.easeOutQuart(Math.min(length, moveMax) , 0, safeWidth, moveMax); //(x, startY, wholeY, maxX) 当自变量为0-moveMax时,相机位移量为0-safeWidth
  109415. dir.multiplyScalar(aimRadius/length);
  109416. skyCamera.position.copy(dir);
  109417. }else {
  109418. skyCamera.position.set(0,0,0);
  109419. }
  109420. skyCamera.rotation.copy(view.camera.rotation);
  109421. skyCamera.aspect = view.camera.aspect;
  109422. if(view.camera.type == "OrthographicCamera"){ //调节zoom
  109423. skyCamera.left = view.camera.left; skyCamera.right = view.camera.right; skyCamera.top = view.camera.top; skyCamera.bottom = view.camera.bottom;
  109424. let a = Potree.config.skyboxBgWidth / 2 - safeWidth;
  109425. let minY = Math.max(skyCamera.right / a, skyCamera.top / a, view.skyboxMinZoom||0); //能够使skybox铺满画布的最小zoom. 提示:越远zoom越小
  109426. let maxY = Math.max(20, minY) ;//自定义一个 不会超过的最大实际zoom
  109427. //view.camera.zoom自变量的变化范围:
  109428. let minX = 1;
  109429. let maxX = 80;
  109430. let x = MathUtils.clamp(view.camera.zoom - minX, minX, maxX);
  109431. skyCamera.zoom = easing.easeOutCubic(x-minX, minY, maxY-minY, maxX-minX); //自变量范围从0开始,所以减去minX
  109432. //pos的范围先不管了 其实aimRadius是有误的,但效果还行
  109433. }else {
  109434. skyCamera.fov = view.camera.fov;
  109435. skyCamera.zoom = 1;
  109436. }
  109437. view.skyboxRenderFun && view.skyboxRenderFun();
  109438. skyCamera.updateProjectionMatrix();
  109439. skyCamera.updateMatrixWorld();
  109440. viewer.renderer.render(viewer.skybox.scene, skyCamera);
  109441. }else if(background === 'gradient'){
  109442. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  109443. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  109444. }else if(background === 'overlayColor'){//在不clear的前提下加一层背景色
  109445. viewer.scene.bg2.material.color.copy(view.backgroundColor);
  109446. viewer.scene.bg2.material.opacity = view.backgroundOpacity;
  109447. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg2);
  109448. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  109449. }
  109450. }
  109451. //全景图的部分和点云有点相关就不移动到这了。但是如果是showPanos模式,就不要渲染背景了。
  109452. }
  109453. /*
  109454. 关于透明度:
  109455. 由于点云和mesh是分开渲染的,且材质很不一样,所以透明和blend有冲突
  109456. 1 如果点云的blend是AdditiveBlending,也就是普通的叠加模式。
  109457. 则半透明点云的depthTest和depthWrite都为false
  109458. 这时候mesh要后渲染,且depthWrite不能为false(除非depthTest也为false),否则将被点云遮住。
  109459. 2 如果点云的blend是普通型
  109460. 则半透明点云的depthTest和depthWrite都为true。(为何depthWrite不能像mesh一样为false, 否则点云自身透明会错乱,可能因为太多points了)
  109461. 这时候若mesh全部先渲染,则 透过depthWrite为false的半透明mesh看不透明点云,mesh会完全被点云遮住。但是透明的物体就是depthWrite要为false,否则也会完全遮住点云
  109462. 即使是后渲染半透明的mesh,若透过点云看mesh,mesh会完全被点云遮住(为什么之前遇到过 透过点云看mesh,点云会显示不出)
  109463. 最终选择是先渲染不透明的mesh,然后点云,然后透明的mesh。虽然点云对mesh透明会失效。
  109464. */
  109465. renderOverlay(params){
  109466. viewer.addTimeMark('renderOverlay','start');
  109467. this.renderOverlay1(params);
  109468. this.renderOverlay2(params);
  109469. viewer.addTimeMark('renderOverlay','end');
  109470. }
  109471. renderOverlay1(params){
  109472. let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  109473. this.reticule.updateAtViewports(params.viewport);
  109474. this.renderer.setRenderTarget(params.target||null);
  109475. //为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖
  109476. let cameraLayers;
  109477. if(params.cameraLayers) cameraLayers = params.cameraLayers;
  109478. else {
  109479. if(params.viewport.name == "mapViewport" )cameraLayers = ['bothMapAndScene', 'light'];
  109480. else {
  109481. cameraLayers = ['sceneObjects', 'light', 'bothMapAndScene' ];
  109482. if(!params.drawedModelOnRT){
  109483. cameraLayers.push('model');
  109484. }
  109485. }
  109486. }
  109487. if(cameraLayers.length){
  109488. Potree.Utils.setCameraLayers(camera, cameraLayers, params.extraEnableLayers); //透明贴图层 skybox 、reticule marker 不能遮住测量线
  109489. if('renderBeforeCloud' in params){
  109490. this.scene.scene.traverse((object)=>{
  109491. if(object.material){
  109492. Potree.Utils.updateVisible(object, 'renderOpa',
  109493. (params.renderBeforeCloud && (object.material.opacity<1 || !object.material.depthTest) || (!params.renderBeforeCloud) && (object.material.opacity==1 && object.material.depthTest))? false:true);
  109494. //点云之前渲染的话隐藏半透明的, 点云之后渲染的话隐藏不透明的。 depthTest==false的也最后渲染
  109495. }
  109496. });//ground的材质中opacity为1,所以被当做不透明了
  109497. }
  109498. viewer.dispatchEvent({type: "render.begin2" , name:'scene', viewport:params.viewport });
  109499. this.renderer.render(this.scene.scene, camera);
  109500. if('renderBeforeCloud' in params){
  109501. this.scene.scene.traverse((object)=>{
  109502. if(object.material){
  109503. Potree.Utils.updateVisible(object, 'renderOpa', true); //恢复
  109504. }
  109505. });
  109506. }
  109507. }
  109508. this.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  109509. }
  109510. renderOverlay2(params){
  109511. let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  109512. //清除深度 !!!!
  109513. this.renderer.clearDepth();
  109514. if(!params.magnifier){
  109515. //测量线
  109516. this.dispatchEvent({type: "render.pass.perspective_overlay", camera, screenshot:params.screenshot,viewport:params.viewport});
  109517. if(!params.screenshot && params.viewport.name != "mapViewport" ){
  109518. Potree.Utils.setCameraLayers(camera, ['magnifier']); //magnifier 遮住测量线
  109519. this.renderer.render(this.scene.scene, camera);
  109520. }
  109521. }
  109522. if(params.viewport.name != "mapViewport" ) {
  109523. Potree.Utils.setCameraLayers(camera, ['volume','transformationTool']);
  109524. //viewer.dispatchEvent({type: "render.begin2" , name:'clip&trans',viewport:params.viewport })
  109525. this.renderer.render(this.clippingTool.sceneVolume, camera); //official 可以删
  109526. this.renderer.render(this.transformationTool.scene, camera);
  109527. }
  109528. }
  109529. setLimitFar(state){//切换是否limitFar
  109530. viewer.mainViewport.camera.limitFar = !!state;
  109531. if(state){
  109532. viewer.mainViewport.camera.near = 0.02;
  109533. viewer.mainViewport.camera.far = Potree.settings.displayMode == 'showPanos' ? viewer.farWhenShowPano : Potree.settings.cameraFar;
  109534. viewer.mainViewport.camera.updateProjectionMatrix();
  109535. }
  109536. }
  109537. setClipState(state){//有时候需要暂时关闭下clip
  109538. state = !!state;
  109539. if(this.clipUnabled == !state)return
  109540. this.scene.volumes.filter(v=>/* v.clip && */ v instanceof Potree.BoxVolume).map(volume=>{
  109541. volume.clip = state;
  109542. Potree.Utils.updateVisible(volume, 'setClipState', state);
  109543. });
  109544. this.clipUnabled = !state;
  109545. }
  109546. /* 大规模WebGL应用引发浏览器崩溃的几种情况及解决办法
  109547. https://blog.csdn.net/weixin_30378311/article/details/94846947 */
  109548. render(params={}){//add params
  109549. viewer.addTimeMark('render','start');
  109550. const vrActive = this.renderer.xr.isPresenting;
  109551. let SiteModel = viewer.modules.SiteModel;
  109552. let s = SiteModel.editing && SiteModel.selected && (SiteModel.selected.buildType == 'room' || SiteModel.selected.buildType == 'floor'); //空间模型的房间选中材质是需要depth的,这时候需要绘制两次点云
  109553. Potree.settings.pointEnableRT = !this.screenshoting && (this.scene.measurements.length > 0 || s );
  109554. if(vrActive){
  109555. this.renderVR();
  109556. }else {
  109557. let specialRender = !!params.viewports;
  109558. let viewports = params.viewports || this.viewports;
  109559. if(!this.needRender){
  109560. viewports = viewports.filter(v=>v.needRender); //可以渲染的条件是viewer或viewport的needRender为true
  109561. }
  109562. viewports = viewports.filter(v=>v.active);
  109563. if(viewports.length > 0){
  109564. params.viewports = viewports;
  109565. if(this.outlinePass.selectedObjects.length && this.outlinePass.edgeStrength > 0 && !params.screenshot){
  109566. let scenes = this.inputHandler.interactiveScenes.concat(this.scene.scene).concat(viewer.scene.scenePointCloud);
  109567. this.composer.render(scenes, null, this.viewports, this.renderDefault.bind(this));
  109568. }else {
  109569. this.renderDefault(params);
  109570. }
  109571. }
  109572. if(!specialRender) this.needRender = false;
  109573. }
  109574. viewer.addTimeMark('render','end');
  109575. }
  109576. startScreenshot(info={}, width=800, height=400, compressRatio ){//add
  109577. //let deferred = info.deferred || $.Deferred();
  109578. let getImageDeferred = info.getImageDeferred || $.Deferred();
  109579. let finishDeferred = info.finishDeferred || $.Deferred();
  109580. let viewerMaster = info.map ? this.mapViewer : this; //截图主体
  109581. let useMap = info.type == 'measure' || info.map;
  109582. if(Potree.settings.displayMode == 'showPanos' && viewer.scene.view.isFlying('pos')){//如果在飞,飞完再截图
  109583. info.getImageDeferred = getImageDeferred , info.finishDeferred = finishDeferred;
  109584. let f = ()=>{
  109585. this.startScreenshot(info, width, height, compressRatio);
  109586. };
  109587. viewer.scene.view.addEventListener('flyingDone', f, {once:true});
  109588. return {getImagePromise:getImageDeferred.promise(), finishPromise:finishDeferred.promise()}
  109589. }
  109590. var sid = Date.now();
  109591. //抗锯齿待加 1 post处理 2截图大张再抗锯齿缩小
  109592. console.log('startScreenshot: '+sid);
  109593. let updateCamera = ()=>{
  109594. this.viewports.forEach(e=>{
  109595. e.view.applyToCamera(e.camera); //因为fly时只更新了view所以要强制更新下camera
  109596. this.dispatchEvent({ //update map and sprite
  109597. type: "camera_changed",
  109598. camera: e.camera,
  109599. viewport : e,
  109600. changeInfo:{positionChanged:true,changed:true}
  109601. });
  109602. });
  109603. };
  109604. let screenshot = ()=>{
  109605. let pose;
  109606. //console.log('screenshot',sid, Date.now())
  109607. useMap && (viewer.mapViewer.needRender = true);
  109608. this.needRender = true;
  109609. if(info.useRenderTarget){
  109610. //离屏渲染 有抗锯齿问题、在手机上速度慢
  109611. var { dataUrl } = viewerMaster.makeScreenshot( new Vector2(width,height), null, compressRatio );
  109612. }else {
  109613. //直接渲染 会改变canvas大小
  109614. let canvas = this.renderArea.getElementsByTagName('canvas')[0];
  109615. //canvas.width = width, canvas.height = height //不需要改canvas大小, 只需要 this.renderer.setSize(width, height ); 前面updateScreenSize已经执行
  109616. this.render({ screenshot : true, width , height, resize :true }); //需要resize
  109617. var dataUrl = canvas.toDataURL('image/jpeg',compressRatio);
  109618. }
  109619. if(!Potree.settings.isOfficial){
  109620. Common$1.downloadFile(dataUrl, 'screenshot.jpg');
  109621. }
  109622. var finish = ()=>{
  109623. oldStates.viewports.forEach(old=>{//恢复相机
  109624. var viewport = viewports.find(v=>v.name == old.name);
  109625. viewport.left = old.left; viewport.bottom = old.bottom;
  109626. viewport.width = old.width; viewport.height = old.height;
  109627. viewport.view.copy(old.view);
  109628. viewport.view.applyToCamera(viewport.camera);
  109629. });
  109630. viewer.updateScreenSize({forceUpdateSize:true});//更新像素
  109631. /* oldStates.viewports.forEach(old=>{//恢复相机
  109632. var viewport = [mapViewport, mainViewport].find(v=>v.name == old.name);
  109633. this.dispatchEvent({ //update map
  109634. type: "camera_changed",
  109635. camera: viewport.camera,
  109636. viewport : viewport
  109637. })
  109638. }) */
  109639. updateCamera();
  109640. finishDeferred.resolve({dataUrl, pose});
  109641. setTimeout(()=>{
  109642. if(!this.screenshoting){
  109643. //Potree.settings.pointNoLimit = false
  109644. Potree.settings.pointDensity = 'high';
  109645. //console.warn('恢复pointDensity')
  109646. /* if(viewer.scene.pointclouds[0].material.oldSize_ ){
  109647. viewer.scene.pointclouds[0].material.size = viewer.scene.pointclouds[0].material.oldSize_
  109648. viewer.scene.pointclouds[0].material.oldSize_ = null
  109649. } */
  109650. }
  109651. },500); //延迟:避免连续多次截图时释放点云
  109652. this.screenshoting = false;
  109653. console.log('screenshot done: '+sid);
  109654. };
  109655. {//恢复:
  109656. if(info.type == 'measure'){
  109657. this.modules.SiteModel.pauseUpdateEntity = false;
  109658. this.focusDatasets = null;
  109659. this.scene.measurements.forEach(e=>Potree.Utils.updateVisible(e, 'screenshot',true));
  109660. info.measurement.setSelected(false, 'screenshot');
  109661. }
  109662. this.images360.panos.forEach(pano=>{
  109663. Potree.Utils.updateVisible(pano, 'screenshot', true);
  109664. });
  109665. Potree.Utils.updateVisible(this.reticule, 'screenshot', true);
  109666. if(useMap){
  109667. Potree.Utils.updateVisible(this.mapViewer.cursor, 'screenshot', true);
  109668. if(oldStates.attachedToViewer != this.mapViewer.attachedToViewer){
  109669. if(info.type == 'measure'){
  109670. this.mapViewer.attachToMainViewer(false );
  109671. }
  109672. }
  109673. if(this.mapViewer.splitDir != oldStates.oldSplitDir){
  109674. this.mapViewer.changeSplitScreenDir(oldStates.oldSplitDir);
  109675. }
  109676. mapViewport.camera.zoom = oldStates.mapZoom;
  109677. mapViewport.camera.updateProjectionMatrix();
  109678. }
  109679. let recover = ()=>{
  109680. if(Potree.settings.displayMode == 'showPanos') {
  109681. viewer.images360.flyToPano({pano:oldStates.pano, duration:0, callback:()=>{
  109682. finish();
  109683. }});
  109684. }else {
  109685. finish();
  109686. }
  109687. };
  109688. if(info.ifGetPose){
  109689. Potree.sdk.scene.getPose().done(pose_ =>{
  109690. pose = pose_;
  109691. getImageDeferred.resolve({dataUrl, pose});
  109692. recover();
  109693. });
  109694. }else {
  109695. recover();
  109696. }
  109697. }
  109698. };// screenshot end
  109699. let mapViewport;
  109700. let mainViewport = this.mainViewport;
  109701. let viewports = [mainViewport];
  109702. let oldStates = {
  109703. viewports : [mainViewport.clone()],
  109704. pano: Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : null,
  109705. };
  109706. if(useMap){
  109707. mapViewport = this.mapViewer.viewports[0];
  109708. viewports.push(mapViewport);
  109709. oldStates.viewports.push(mapViewport.clone());
  109710. oldStates.attachedToViewer = this.mapViewer.attachedToViewer;
  109711. oldStates.mapZoom = mapViewport.camera.zoom;
  109712. Potree.Utils.updateVisible(this.mapViewer.cursor, 'screenshot', false);//令mapCursor不可见
  109713. }
  109714. if(info.hideMarkers){
  109715. this.images360.panos.forEach(pano=>{//令漫游点不可见
  109716. Potree.Utils.updateVisible(pano, 'screenshot', false);
  109717. });
  109718. }
  109719. Potree.Utils.updateVisible(this.reticule, 'screenshot', false);//令reticule不可见
  109720. Potree.settings.pointDensity = 'screenshot';
  109721. let waitPointLoad = (done)=>{
  109722. let finish;
  109723. done = done || screenshot;
  109724. let dealDone = ()=>{
  109725. //viewer.removeEventListener('overPointBudget',decreaseLevel)
  109726. finish || done();
  109727. finish = true;
  109728. };
  109729. let decreaseLevel = ()=>{ //降点云level
  109730. let levels = viewer.scene.pointclouds[0].visibleNodes.map(e=>e.getLevel());
  109731. //console.log(levels)
  109732. let actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level
  109733. //console.warn('decreaseLevel, 新maxLevel', actMaxLevel - 1, '原maxlevel', viewer.scene.pointclouds[0].maxLevel, 'numVisiblePoints', Potree.numVisiblePoints)
  109734. /* viewer.scene.pointclouds[0].maxLevel = actMaxLevel - 1
  109735. viewer.scene.pointclouds[0].material.oldSize_ = viewer.scene.pointclouds[0].material.size
  109736. viewer.scene.pointclouds[0].material.size *= 1.5 */
  109737. };
  109738. if(Potree.settings.displayMode == 'showPointCloud'){
  109739. viewer.updateScreenSize({forceUpdateSize:true, width, height, forTarget:info.useRenderTarget});//需要先setSize才能加载范围内的点云
  109740. }
  109741. let maxTime = document.hidden ? 6000 : 1000; //离开页面后会变成1秒1帧
  109742. setTimeout(()=>{
  109743. if(Potree.pointsLoading && Potree.settings.displayMode == 'showPointCloud'){//如果还在加载
  109744. viewer.addEventListener('pointsLoaded',()=>{ //点云加载完时(不一定准确)
  109745. if(!finish)console.warn('加载完毕', ' numVisiblePoints', Potree.numVisiblePoints);
  109746. dealDone();
  109747. },{once:true});
  109748. let overTime = ()=>{//超时不候(其实之后等待地图还会再加载几秒)
  109749. if(document.hidden){
  109750. return setTimeout(overTime, maxTime)
  109751. }
  109752. if(!finish)console.warn('超时, numVisiblePoints', Potree.numVisiblePoints);
  109753. dealDone();
  109754. };
  109755. setTimeout(overTime, maxTime);
  109756. }else {
  109757. dealDone();
  109758. }
  109759. },200);//先加载一段时间
  109760. };
  109761. if(info.type == 'measure'){//要截图双屏
  109762. this.scene.measurements.forEach(e=>Potree.Utils.updateVisible(e,'screenshot',e == info.measurement) );
  109763. info.measurement.setSelected(true, 'screenshot');
  109764. //因为分屏后位置才最终确定,才能确定是否显示出floorplan所以先分屏
  109765. if(Potree.settings.floorplanEnable){
  109766. oldStates.oldSplitDir = this.mapViewer.splitDir;
  109767. this.mapViewer.attachToMainViewer(true, 'measure', 0.5 , {dir:'leftRight'} );
  109768. }
  109769. viewer.updateScreenSize({forceUpdateSize:true, width, height, forTarget:info.useRenderTarget}); //更新viewports相机透视 使focusOnObject在此窗口大小下
  109770. let begin = ()=>{
  109771. useMap = this.mapViewer.attachedToViewer;
  109772. updateCamera();
  109773. if(useMap){
  109774. let waitMap = ()=>{
  109775. console.log('waitMap: '+sid, Date.now(), this.mapViewer.mapLayer.loadingInProgress );
  109776. this.mapViewer.waitLoadDone(screenshot.bind(this));//等待地图所有加载完
  109777. };
  109778. waitPointLoad(waitMap);
  109779. }else {
  109780. waitPointLoad();
  109781. }
  109782. };
  109783. let {promise} = this.focusOnObject(info.measurement, 'measure', 0, {
  109784. basePanoSize:1024, gotoBestView:true,
  109785. minMapWidth: this.mapViewer.mapLayer.maps.find(e=>e.name == 'map').disabled ? 10 : 20 //有地图的话为了显示出名字需要更大范围
  109786. });//注意:不同角度截图 得到三维的会不一样,因为focusOnObject是根据方向的
  109787. promise.done(()=>{
  109788. //console.log('promise.done')
  109789. //根据当前位置更新floorplan显示
  109790. //console.log('view Pos ', this.mainViewport.view.position.toArray())
  109791. this.updateDatasetAt(true);
  109792. this.modules.SiteModel.updateEntityAt(true, {measure:info.measurement}); //更新测量线所在楼层,展示俯视图
  109793. if(!this.modules.SiteModel.inEntity){
  109794. this.focusDatasets = [];
  109795. info.measurement.points_datasets.forEach(e=>{
  109796. let p = viewer.scene.pointclouds.find(a=>a.dataset_id == e);
  109797. if(p && !this.focusDatasets.includes(p)){
  109798. this.focusDatasets.push(p);
  109799. }
  109800. });
  109801. this.updateFpVisiDatasets();
  109802. }
  109803. this.modules.SiteModel.pauseUpdateEntity = true;
  109804. //console.log('currentFloor', this.modules.SiteModel.currentFloor, 'currentDataset', this.atDatasets )
  109805. let floorplanShowed = this.mapViewer.mapLayer.maps.some(e => e.name.includes('floorplan') && e.objectGroup.visible);//如果没有floorplan展示就不分屏(如果focus时飞出数据集从而不展示怎么办。尤其是俯瞰比较长的线时容易这样,或许要根据其所在数据集强制显示)
  109806. if(!floorplanShowed && this.mapViewer.attachedToViewer){
  109807. this.mapViewer.attachToMainViewer(false); //取消分屏
  109808. viewer.updateScreenSize({forceUpdateSize:true, width, height, forTarget:info.useRenderTarget}); //更新viewports相机透视
  109809. let {promise} = this.focusOnObject(info.measurement, 'measure', 0, {basePanoSize:1024,gotoBestView:true,} );//因画面比例更改,重新focus
  109810. promise.done(()=>{
  109811. begin();
  109812. });
  109813. }else {
  109814. begin();
  109815. }
  109816. });
  109817. }else {
  109818. waitPointLoad();
  109819. }
  109820. /*
  109821. 测量线的截图因为要调用分屏的,会改变画面
  109822. 但是普通截图的话,不会改变画面
  109823. */
  109824. this.screenshoting = true;
  109825. return {getImagePromise:getImageDeferred.promise(), finishPromise:finishDeferred.promise()}
  109826. }
  109827. focusOnObject(object, type, duration, o={} ) {
  109828. //飞向热点、测量线等 。
  109829. //console.log('focusOnObject: ', object, type)
  109830. let deferred = o.deferred || $.Deferred();
  109831. let target = new Vector3, //相机focus的位置
  109832. position = new Vector3, //相机最终位置
  109833. dis; //相机距离目标
  109834. duration = duration == void 0 ? 1200 : duration;
  109835. let camera = o.endCamera || viewer.scene.getActiveCamera();
  109836. let cameraPos = camera.position.clone();
  109837. let boundSize;
  109838. /* if(camera.type == 'OrthographicCamera'){
  109839. return console.error('focusOnObject暂不支持OrthographicCamera。因情况复杂,请视情况使用splitScreenTool.viewportFitBound')
  109840. } */
  109841. let getPosWithFullBound = (points, boundingBox, target, cameraPos )=>{//使boundingBox差不多占满屏幕时的相机到target的距离
  109842. // points 和 boundingBox 至少有一个
  109843. let scale;
  109844. if(o.dontChangeCamDir){
  109845. var inv = camera.matrixWorldInverse;
  109846. }else {
  109847. var cameraTemp = camera.clone();
  109848. let view = viewer.mainViewport.view.clone();
  109849. view.position.copy(cameraPos);
  109850. view.lookAt(target);
  109851. if(o.endPitch != void 0){
  109852. view.pitch = o.endPitch;
  109853. view.yaw = o.endYaw;
  109854. }
  109855. view.applyToCamera(cameraTemp);
  109856. //对镜头的bound
  109857. var inv = cameraTemp.matrixWorldInverse;
  109858. }
  109859. var bound = new Box3();
  109860. if(points){//使用points得到的bound更小 //如果points和boundingbox的差别较大,尤其使target和points中心不一致,那么points不一定会刚好在boundingbox内
  109861. points.forEach(e=>{
  109862. var p = e.clone().applyMatrix4(inv);
  109863. bound.expandByPoint(p);
  109864. });
  109865. scale = 1.3;
  109866. }else {
  109867. bound = boundingBox.applyMatrix4(inv);
  109868. scale = 0.9;
  109869. }
  109870. boundSize = bound.getSize(new Vector3);
  109871. {
  109872. boundSize.x *= scale; //稍微放大一些,不然会靠到屏幕边缘
  109873. boundSize.y *= scale;
  109874. let min = 0.0001;
  109875. boundSize.x = Math.max(min, boundSize.x);
  109876. boundSize.y = Math.max(min, boundSize.y);
  109877. }
  109878. if(camera.type == 'OrthographicCamera'){
  109879. dis = boundSize.length() / 2;
  109880. }else {
  109881. let aspect = boundSize.x / boundSize.y;
  109882. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  109883. dis = boundSize.y/2/ Math.tan(MathUtils.degToRad(camera.fov / 2)) + boundSize.z/2;
  109884. }else {
  109885. let hfov = cameraLight.getHFOVForCamera(camera, true);
  109886. dis = boundSize.x/2 / Math.tan(hfov / 2) + boundSize.z/2;
  109887. }
  109888. }
  109889. dis = Math.max(0.1,dis);
  109890. //三个顶点以上的由于measure的中心不等于bound的中心,所以点会超出bound外。 且由于视椎近大远小,即使是两个点的,bound居中后线看上去仍旧不居中.
  109891. //获得相机最佳位置
  109892. let dir;
  109893. if(o.dontChangeCamDir){
  109894. dir = viewer.mainViewport.view.direction.negate();
  109895. }else {
  109896. dir = new Vector3().subVectors(cameraPos, target).normalize();
  109897. }
  109898. if(o.dontLookUp && dir.z < 0){
  109899. dir.negate();
  109900. }
  109901. position.copy(target).add(dir.multiplyScalar(dis));
  109902. if(false){//打开以检查box
  109903. if(!this.boundBox){//调试
  109904. this.boundBox = new Mesh(new BoxGeometry(1,1,1,1));
  109905. this.boundBox.material.wireframe = true;
  109906. this.boundBox.up.set(0,0,1);
  109907. Potree.Utils.setObjectLayers(this.boundBox,'sceneObjects');
  109908. this.scene.scene.add(this.boundBox);
  109909. }
  109910. this.boundBox.position.copy(target);
  109911. this.boundBox.scale.copy(boundSize);
  109912. this.boundBox.lookAt(position);
  109913. }
  109914. return position
  109915. };
  109916. if(this.images360.flying){
  109917. let f = ()=>{
  109918. this.focusOnObject(object, type, duration, $.extend(o,{deferred}));
  109919. this.images360.removeEventListener('cameraMoveDone',f);
  109920. };
  109921. this.images360.addEventListener('cameraMoveDone',f);
  109922. return {promise: deferred.promise() }
  109923. }
  109924. if (type == 'measure') {
  109925. target.copy(object.getCenter());
  109926. //试试改变位置(方向),直视测量线。能避免倾斜角度造成的非常不居中、以及看不到面的情况
  109927. if(o.gotoBestView){//直接沿着法线方向看
  109928. if(object.points.length>2){
  109929. let facePlane = object.getFacePlane(target);
  109930. let normal = facePlane.normal.clone();
  109931. if(normal.dot(this.mainViewport.view.direction) > 0){
  109932. normal.negate(); //顺着视线
  109933. }
  109934. //normal.z = Math.max(0.2, normal.z)//尽量不要仰视
  109935. cameraPos.copy(target).add(normal);
  109936. }else {
  109937. let lineDir = new Vector3().subVectors(object.points[0],object.points[1]).normalize();
  109938. let facePlane = new Plane().setFromNormalAndCoplanarPoint(lineDir, target);
  109939. //if(cameraPos.z < target.z + 1)cameraPos.z = target.z + 1//尽量不要仰视
  109940. let dir = new Vector3().subVectors(cameraPos,target).normalize();
  109941. dir.z = Math.max(dir.z, 0.4);
  109942. cameraPos.copy(target).add(dir);//尽量不要仰视
  109943. let dis = cameraPos.distanceTo(target);
  109944. dir = lineDir.clone().multiplyScalar(dis);
  109945. let line = new Line3().set(cameraPos.clone().add(dir), cameraPos.clone().add(dir.negate())); //过相机位置作到面的垂线
  109946. facePlane.intersectLine(line, cameraPos ); //得垂足,作为新的相机位置。就能在测量线中间看测量线
  109947. }
  109948. }else {
  109949. if(object.points.length>2){
  109950. let facePlane = object.getFacePlane(target);
  109951. let normal = facePlane.normal.clone();
  109952. let angle = this.scene.view.direction.angleTo(normal);
  109953. let minDiff = MathUtils.degToRad(60);
  109954. //console.log('angle',angle)
  109955. if(angle>minDiff && angle<Math.PI-minDiff){//当几乎正对时就不执行
  109956. if(angle<Math.PI/2){ //在背面
  109957. normal.negate();
  109958. }
  109959. let dir = new Vector3().subVectors(camera.position, target).normalize();
  109960. let newDir = new Vector3().addVectors(dir,normal);//两个角度的中间
  109961. cameraPos.copy(target.clone().add(newDir));
  109962. }
  109963. }else if(object.points.length == 2){ //线段
  109964. let lineDir = new Vector3().subVectors(object.points[0],object.points[1]).normalize();
  109965. let angle = this.scene.view.direction.angleTo(lineDir);
  109966. let maxDiff = Math.PI*0.25;// 45度
  109967. if(angle<maxDiff || angle>Math.PI-maxDiff){//当几乎正对时就不执行
  109968. if(angle>Math.PI/2){ //令dir和lineDir成钝角
  109969. lineDir.negate();
  109970. }
  109971. let dir = new Vector3().subVectors(camera.position, target).normalize();
  109972. let mid = new Vector3().addVectors(lineDir, dir).normalize(); //中间法向量(如果刚好dir和lineDir反向,那得到的为零向量,就不移动了,但一般不会酱紫吧)
  109973. let newDir = new Vector3().addVectors(dir, mid);
  109974. cameraPos.copy(target.clone().add(newDir));
  109975. }
  109976. }else {
  109977. console.error('measure 没有facePlane points点数还不为2?');
  109978. }
  109979. }
  109980. //截图时直接飞到最佳视角,也就是平视它所在面。其余时候为了避免镜头旋转过大就算了。
  109981. position = getPosWithFullBound(object.points, null, target, cameraPos );
  109982. if(this.mapViewer/* .attachedToViewer */){
  109983. //console.log('mapFocusOn: '+target.toArray())
  109984. const minMapWidth = o.minMapWidth || 2; //截图的时候要显示的地图范围较大,为了显示出地区名字
  109985. const minBound = new Vector2(minMapWidth,minMapWidth);//针对垂直线,在地图上只有一个点
  109986. //原始的bound
  109987. let boundOri = new Box3();
  109988. object.points.forEach(e=>{
  109989. boundOri.expandByPoint(e);
  109990. });
  109991. let boundSizeOri = boundOri.getSize(new Vector3);
  109992. let boundSizeMap = boundSizeOri.clone().multiplyScalar(2);
  109993. boundSizeMap.x = Math.max(minBound.x, boundSizeMap.x );
  109994. boundSizeMap.y = Math.max(minBound.y, boundSizeMap.y );
  109995. this.mapViewer.moveTo(target.clone(), boundSizeMap, duration);
  109996. }
  109997. if(Potree.settings.displayMode == 'showPointCloud'){ //点云
  109998. let minDis = 0.3;
  109999. if(0 ){//如果没有被选中,会被遮挡。 2023.11.15 最好展示全局(尤其截图时),虽然被遮挡,但focus的过程是选中状态全显示的,可以看出所在范围。
  110000. let checkIntersect = ( )=>{
  110001. let intersect = this.inputHandler.ifBlockedByIntersect({point:position, cameraPos: target});// 不一定准确
  110002. if(intersect){
  110003. let blockCount = 0, unblockCount = 0, visi;
  110004. for(let i=0;i<object.points.length;i++){ //如果顶点超过一半不可见,就要更改位置
  110005. let p = object.points[i];
  110006. let blocked = this.inputHandler.ifBlockedByIntersect({point:p, margin:0.3 , cameraPos:position, pickWindowSize:4});
  110007. if(blocked){
  110008. blockCount ++;
  110009. if(blockCount / object.points.length >= 0.5){
  110010. visi = false;
  110011. break
  110012. }
  110013. }else {
  110014. unblockCount ++;
  110015. if(unblockCount / object.points.length > 0.5){
  110016. visi = true;
  110017. break
  110018. }
  110019. }
  110020. }
  110021. if(visi == void 0){
  110022. visi = unblockCount / object.points.length > 0.5;
  110023. }
  110024. let shrink = ()=>{
  110025. let dir = new Vector3().subVectors(position, target).normalize().multiplyScalar(intersect.distance);
  110026. position.copy(target).add(dir);
  110027. console.log('checkIntersect newPos', position.clone() );
  110028. };
  110029. if(!visi){//更改位置距离target如果小于最小距离,需要反向。 否则直接缩短距离。
  110030. if(intersect.distance < minDis ){
  110031. console.log('检测到intersect 反向', intersect.distance );
  110032. let position1 = position.clone();
  110033. let dir = new Vector3().subVectors(position, target);
  110034. position.copy(target).sub(dir);
  110035. let intersect2 = this.inputHandler.ifBlockedByIntersect({point: position, cameraPos:target});// 不一定准确
  110036. if(intersect2){
  110037. if(intersect2.distance < intersect.distance ){
  110038. position.copy(position1);//恢复
  110039. }
  110040. shrink();
  110041. }
  110042. }else {
  110043. shrink();
  110044. }
  110045. }
  110046. }
  110047. };
  110048. checkIntersect();
  110049. //多折线没有areaPlane 有时候会看向空白区域 - -
  110050. }
  110051. }else if(Potree.settings.displayMode == 'showPanos'){//全景 (比较难校准)
  110052. let target2, dir;
  110053. if( object.measureType.includes('MulDistance')){//因为该线不闭合,可能看向target的方向会没有线,所以换一个target
  110054. target2 = object.points[Math.round(object.points.length / 2) ];//直接看向中间点
  110055. dir = new Vector3().subVectors(target2, position).normalize();
  110056. }
  110057. let pano = viewer.images360.fitPanoTowardPoint({
  110058. /*point : target, //不使用目标点来判断是因为缺少measure角度的信息。比如虽然可以靠近线的中心,但是线朝向屏幕,那几乎就是一个点了。
  110059. //bestDistance : dis * 0.5, //乘以小数是为了尽量靠近
  110060. boundSphere: boundOri.getBoundingSphere(new THREE.Sphere), */
  110061. target,
  110062. dir,
  110063. point : position,
  110064. bestDistance : 0 ,
  110065. checkIntersect: o.checkIntersect, gotoBestView: o.gotoBestView
  110066. });
  110067. let result = {promise:deferred.promise() };
  110068. if(pano && pano.msg){
  110069. pano = pano.pano;
  110070. result.msg = pano.msg;
  110071. }
  110072. if(pano){
  110073. viewer.images360.flyToPano({pano, target : target2 || target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize});//dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  110074. if(viewer.images360.currentPano == pano){
  110075. let dis1 = viewer.images360.currentPano.position.distanceTo(target);
  110076. let dis2 = position.distanceTo(target);
  110077. //console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2)
  110078. return {msg: (dis1 / dis2 > 1.5 && dis1-dis2>10)? 'tooFar' : 'posNoChange', promise : deferred.promise() }
  110079. }
  110080. }
  110081. return result
  110082. /* if(viewer.images360.currentPano == pano){
  110083. let dis1 = viewer.images360.currentPano.position.distanceTo(target)
  110084. let dis2 = position.distanceTo(target)
  110085. //console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2)
  110086. return {msg: (dis1 / dis2 > 1.5 && dis1-dis2>10)? 'tooFar' : 'posNoChange', promise : deferred.promise() }
  110087. }else{
  110088. return {promise : deferred.promise()}
  110089. } */
  110090. //出现过到达位置后测量线标签闪烁的情况
  110091. // 测量线截图 全景 最好能放大. 但要确保该位置放大后图片加载完有点困难
  110092. }
  110093. } else if (type == 'tag' || type == 'point') {
  110094. //dimension = 1
  110095. target.copy(object.position);
  110096. let bestDistance = o.distance || 3;
  110097. if(!o.dontMoveMap && this.mapViewer){
  110098. //console.log('mapFocusOn: '+target.toArray())
  110099. this.mapViewer.moveTo(target.clone(), null, duration);
  110100. }
  110101. if(Potree.settings.displayMode == 'showPointCloud'){
  110102. if(o.dontChangePos){
  110103. position.copy(cameraPos);
  110104. }else {
  110105. dis = bestDistance;
  110106. let dir = o.direction ? o.direction.clone().negate() : this.mainViewport.view.direction.negate();// */new THREE.Vector3().subVectors(camera.position, target).normalize()
  110107. if(o.dontLookUp && dir.z<0) dir.z *= -1;
  110108. position.copy(target).add(dir.multiplyScalar(dis));
  110109. }
  110110. if(o.sameFloor){//需要在同一楼层
  110111. let atFloor = this.modules.SiteModel.pointInWhichEntity(target, 'floor');
  110112. if(atFloor){
  110113. let camFloor = this.modules.SiteModel.pointInWhichEntity(position, 'floor');
  110114. if(camFloor != atFloor){
  110115. let raycaster = new Raycaster();
  110116. let origin = target;
  110117. let dir = new Vector3().subVectors( position, target ).normalize();
  110118. raycaster.set(origin, dir);
  110119. let intersect = Potree.Utils.getIntersect(null, [atFloor.box], null, raycaster);
  110120. if(intersect){
  110121. let dis = MathUtils.clamp(intersect.distance - 0.2, camera.near, intersect.distance);
  110122. position.addVectors(origin, dir.multiplyScalar(dis));
  110123. console.log('移动到楼层');
  110124. }else {
  110125. console.error('?no intersect?');
  110126. }
  110127. }
  110128. }
  110129. }
  110130. if(o.checkIntersect){//识别被点云遮住的话
  110131. let intersect; //反向查找从target到相机的第一个intersect
  110132. intersect = this.inputHandler.ifBlockedByIntersect({point:position, margin:0, cameraPos:target} /* {point:target, margin: 0.2, cameraPos:position} */);
  110133. if(intersect){
  110134. position.copy(intersect.location);
  110135. console.log('移近');
  110136. }
  110137. }
  110138. }else if(Potree.settings.displayMode == 'showPanos'){
  110139. let pano = viewer.images360.fitPanoTowardPoint({
  110140. point : target,
  110141. dir : this.scene.view.direction, //尽量不改相机方向,避免镜头晃动
  110142. checkIntersect: o.checkIntersect, sameFloor:o.sameFloor,
  110143. bestDistance, maxDis: o.maxDis //越近越好,但不要太近,bestDistance左右差不多
  110144. });
  110145. let result = {promise:deferred.promise() };
  110146. if(pano && pano.msg){
  110147. pano = pano.pano;
  110148. result.msg = pano.msg;
  110149. }
  110150. pano && viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize });
  110151. return result
  110152. }
  110153. }else if(object.boundingBox && type == 'boundingBox'){//使屏幕刚好看全boundingBox
  110154. target = object.boundingBox.getCenter(new Vector3);
  110155. if(o.dir){ //指定方向
  110156. cameraPos.copy(target).sub(o.dir);
  110157. }
  110158. position = getPosWithFullBound(object.points, object.boundingBox.clone(), target, cameraPos );
  110159. if(Potree.settings.displayMode == 'showPanos'){//全景 (比较难校准)
  110160. let pano = viewer.images360.fitPanoTowardPoint({
  110161. point : position,
  110162. bestDistance : 0 ,
  110163. });
  110164. let result = {promise:deferred.promise() };
  110165. if(pano && pano.msg){
  110166. pano = pano.pano;
  110167. result.msg = pano.msg;
  110168. }
  110169. pano && viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize});//dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  110170. if(!pano){
  110171. console.error('no pano');
  110172. }
  110173. return result
  110174. //出现过到达位置后测量线标签闪烁的情况
  110175. }else {
  110176. /* if(o.dontChangeCamDir){
  110177. target = null
  110178. } */
  110179. }
  110180. }
  110181. if(o.startCamera && o.endCamera){
  110182. viewer.scene.view.tranCamera(this.mainViewport, { endPosition:position, target ,
  110183. boundSize,
  110184. callback:()=>{
  110185. //console.log('focusOnObjectSuccess: '+object.name, type)
  110186. deferred.resolve();
  110187. }, startCamera:o.startCamera, endCamera:o.endCamera, midCamera:this.scene.cameraBasic,
  110188. endYaw:o.endYaw, endPitch:o.endPitch
  110189. }, duration);
  110190. }else if(camera.type == "OrthographicCamera"){
  110191. viewer.scene.view.moveOrthoCamera(this.mainViewport, { endPosition:position, target ,
  110192. boundSize,
  110193. endYaw:o.endYaw, endPitch:o.endPitch,
  110194. callback:()=>{
  110195. //console.log('focusOnObjectSuccess: '+object.name, type)
  110196. deferred.resolve();
  110197. },
  110198. }, duration);
  110199. }else {
  110200. viewer.scene.view.setView({position, target, duration,
  110201. endYaw:o.endYaw, endPitch:o.endPitch,
  110202. callback:()=>{
  110203. //console.log('focusOnObjectSuccess: '+object.name, type)
  110204. deferred.resolve();
  110205. }
  110206. }
  110207. );}
  110208. this.dispatchEvent({type:'focusOnObject', CamTarget:target, position}); //给controls发送信息
  110209. return {promise:deferred.promise()}
  110210. }
  110211. flyToDataset(o={}){
  110212. var pointcloud;
  110213. if(o instanceof Object3D) pointcloud = o;
  110214. else if(o.pointcloud) pointcloud = o.pointcloud;
  110215. else pointcloud = this.scene.pointclouds.find(p => p.dataset_id == o.id);
  110216. let duration = o.duration == void 0 ? 1000 : o.duration;
  110217. if(o.focusOnPoint){//focus点云上一点,避免center区域刚好没有点
  110218. if(pointcloud.root.geometryNode){
  110219. let posArr = pointcloud.root.geometryNode.geometry.attributes.position.array;
  110220. let count = pointcloud.root.geometryNode.geometry.attributes.position.count;
  110221. let index = Math.ceil(count / 2); //随便取一个点
  110222. let point = new Vector3(posArr[index*3+0],posArr[index*3+1],posArr[index*3+2]);
  110223. //point.applyMatrix4(pointcloud.root.pointcloud.matrixWorld)
  110224. point.applyMatrix4(pointcloud.root.sceneNode.matrixWorld);
  110225. viewer.focusOnObject({position:point},'point',duration,{dontChangeCamDir:true, distance:15});
  110226. o.dontMoveMap || viewer.mapViewer.fitToPointcloud(pointcloud, duration);
  110227. console.log('flyToDataset focusOnPoint done');
  110228. return
  110229. }
  110230. }
  110231. var center = pointcloud.bound.getCenter(new Vector3);
  110232. let position;
  110233. let getPano = ()=>{//获取离中心最近的pano
  110234. let request = [];
  110235. let rank = [
  110236. Images360.scoreFunctions.distanceSquared({position: center})
  110237. ];
  110238. let r = Common$1.sortByScore(pointcloud.panos, request, rank);
  110239. if(r.length){
  110240. return r[0].item
  110241. }
  110242. };
  110243. if(Potree.settings.displayMode == 'showPanos'){
  110244. let pano = getPano();
  110245. if(pano){
  110246. if(pano == this.images360.currentPano) return 'posNoChange'
  110247. this.images360.flyToPano({
  110248. pano
  110249. });
  110250. }else return false
  110251. }else {
  110252. let target;
  110253. position = center;
  110254. if(pointcloud.panosBound){
  110255. let panosCenter = pointcloud.panosBound.center; //pano集中的地方,也就是真正有点云的地方
  110256. position = panosCenter.clone();
  110257. /* let ratio = 0.2
  110258. position.z = center.z * ratio + panosCenter.z * (1-ratio) //因为panos一般比较低,为了不让相机朝下时看不到点云,加一丢丢中心高度
  110259. */
  110260. let pano = getPano();
  110261. if(pano){
  110262. target = pano.position; //针对像隧道一样的场景, 中心点还是panosCenter都在没有点云的地方,所以还是看向其中一个漫游点好。
  110263. position.z = target.z; //水平, 避免朝上或朝下
  110264. }
  110265. }
  110266. if(this.modules.Clip.editing){
  110267. position.z = center.z; //剪裁时在中心高度,因为以点云为重点
  110268. this.modules.Clip.bus.dispatchEvent({type:'flyToPos', position, duration });
  110269. }else {
  110270. if(math.closeTo(position, this.images360.position)) return 'posNoChange'
  110271. viewer.scene.view.setView({position, target, duration });
  110272. }
  110273. o.dontMoveMap || viewer.mapViewer.fitToPointcloud(pointcloud, duration);
  110274. }
  110275. return true
  110276. }
  110277. addTimeMark(name, type){
  110278. let record = Potree.timeCollect[name];
  110279. let needRecord = record && record.start && record.measures.length < record.minCount;
  110280. if(needRecord || Potree.measureTimings){
  110281. performance.mark(name+"-"+type);
  110282. if(type == 'end'){
  110283. let measure = performance.measure(name,name+"-start",name+"-end");
  110284. if(needRecord){
  110285. record.measures.push( measure.duration );
  110286. record.sum += measure.duration;
  110287. record.ave = record.sum / record.measures.length;
  110288. record.measures.sort( (a, b) => a - b );
  110289. record.median = record.measures[parseInt(record.measures.length / 2)];
  110290. }
  110291. }
  110292. }
  110293. }
  110294. addFakeMeasure(name,duration){//把一些count当做duration来统计
  110295. if(!Potree.measureTimings)return
  110296. if(!this.fakeMeasure[name]){
  110297. this.fakeMeasure[name] = [];
  110298. }
  110299. let object = {
  110300. name, duration
  110301. };
  110302. this.fakeMeasure[name].push(object);
  110303. }
  110304. resolveTimings(timestamp,log){//打印用时。 注:performance手机的精度只到整数位 。 sidebar中监听update时有高cpu的函数所以不要用demo测
  110305. if(!this.toggle){
  110306. this.toggle = timestamp;
  110307. }
  110308. let duration = timestamp - this.toggle;
  110309. if(duration > 1000.0){
  110310. if(log){
  110311. let measures = performance.getEntriesByType("measure");
  110312. for(let i in this.fakeMeasure){
  110313. measures.push(...this.fakeMeasure[i]);
  110314. }
  110315. let names = new Set();
  110316. for(let measure of measures){
  110317. names.add(measure.name);
  110318. }
  110319. let groups = new Map();
  110320. for(let name of names){
  110321. groups.set(name, {
  110322. measures: [],
  110323. sum: 0,
  110324. n: 0,
  110325. min: Infinity,
  110326. max: -Infinity
  110327. });
  110328. }
  110329. for(let measure of measures){
  110330. let group = groups.get(measure.name);
  110331. group.measures.push(measure);
  110332. group.sum += measure.duration;
  110333. group.n++;
  110334. group.min = Math.min(group.min, measure.duration);
  110335. group.max = Math.max(group.max, measure.duration);
  110336. }
  110337. /* let glQueries = Potree.resolveQueries(this.renderer.getContext()); // resolveQueries 无
  110338. for(let [key, value] of glQueries){
  110339. let group = {
  110340. measures: value.map(v => {return {duration: v}}),
  110341. sum: value.reduce( (a, i) => a + i, 0),
  110342. n: value.length,
  110343. min: Math.min(...value),
  110344. max: Math.max(...value)
  110345. };
  110346. let groupname = `[tq] ${key}`;
  110347. groups.set(groupname, group);
  110348. names.add(groupname);
  110349. } */
  110350. for(let [name, group] of groups){
  110351. group.mean = group.sum / group.n;
  110352. /* group.measures.sort( (a, b) => a.duration - b.duration );
  110353. if(group.n === 1){
  110354. group.median = group.measures[0].duration;
  110355. }else if(group.n > 1){
  110356. group.median = group.measures[parseInt(group.n / 2)].duration;
  110357. }
  110358. */
  110359. let measures = group.measures.slice();
  110360. measures.sort( (a, b) => a.duration - b.duration );
  110361. if(group.n === 1){
  110362. group.median = measures[0].duration;
  110363. }else if(group.n > 1){
  110364. group.median = measures[parseInt(group.n / 2)].duration;
  110365. }
  110366. }
  110367. let cn = Array.from(names).reduce( (a, i) => Math.max(a, i.length), 0) + 5;
  110368. let cmin = 6;
  110369. let cmed = 6;
  110370. let cmax = 6;
  110371. let csam = 4;
  110372. let message = ` ${"NAME".padEnd(cn)} |`
  110373. + ` ${"MIN".padStart(cmin)} |`
  110374. + ` ${"MEDIAN".padStart(cmed)} |`
  110375. + ` ${"MAX".padStart(cmax)} |`
  110376. + ` ${"AVE".padStart(cmax)} |`
  110377. + ` ${"SAMPLES".padStart(csam)} \n`;
  110378. message += ` ${"-".repeat(message.length) }\n`;
  110379. names = Array.from(names).sort();
  110380. for(let name of names){
  110381. let group = groups.get(name);
  110382. let min = group.min.toFixed(3);
  110383. let median = group.median.toFixed(3);
  110384. let max = group.max.toFixed(3);
  110385. let ave = group.mean.toFixed(3); //add
  110386. let n = group.n;
  110387. message += ` ${name.padEnd(cn)} |`
  110388. + ` ${min.padStart(cmin)} |`
  110389. + ` ${median.padStart(cmed)} |`
  110390. + ` ${max.padStart(cmax)} |`
  110391. + ` ${ave.padStart(cmax)} |`
  110392. + ` ${n.toString().padStart(csam)}\n`;
  110393. }
  110394. message += `\n`;
  110395. console.log(message);
  110396. }
  110397. this.fakeMeasure = {}; //clear
  110398. performance.clearMarks();
  110399. performance.clearMeasures();
  110400. this.toggle = timestamp;
  110401. }
  110402. //注意,console.log本身用时挺高,降4倍时可能占用0.5毫秒,所以不能每帧都打印
  110403. }
  110404. loop(timestamp){
  110405. //let startTime = performance.now()
  110406. //console.log('间隔:' /*, parseInt((startTime - this.lastEndTime)*100 )/100 */)
  110407. if(this.paused)return
  110408. if(performance.getEntriesByName("loopWaitNext-start").length)viewer.addTimeMark('loopWaitNext','end');
  110409. if(this.stats){
  110410. this.stats.begin();
  110411. }
  110412. performance.mark('loop-start') ;// 无论有没有reportTimings都要获取,因为getBestCound需要
  110413. this.dispatchEvent('loopStart');
  110414. this.interacted = false;
  110415. this.shelterCount = {byTex:0, byCloud:0, maxByTex: 100, maxByCloud:0 }; //清空 因ifPointBlockedByIntersect可能在任何时候触发,所以需要一开始就定义这个,且每次计算最大可计算次数太麻烦了就定义一个吧。
  110416. let deltaTime = this.clock.getDelta();
  110417. this.update(deltaTime, timestamp);
  110418. this.magnifier.render();
  110419. this.render();
  110420. this.objs.children.forEach(e=>{
  110421. if(e.fileType == '3dTiles'){
  110422. e.runtime.update(deltaTime, this.renderer, this.mainViewport.camera);
  110423. }
  110424. });
  110425. // let vrActive = viewer.renderer.xr.isPresenting;
  110426. // if(vrActive){
  110427. // this.update(this.clock.getDelta(), timestamp);
  110428. // this.render();
  110429. // }else{
  110430. // this.update(this.clock.getDelta(), timestamp);
  110431. // this.render();
  110432. // }
  110433. Potree.framenumber++;
  110434. //-------------
  110435. this.images360.tileDownloader.update();
  110436. this.images360.panoRenderer.update();
  110437. this.images360.getNeighbours(this.interacted);
  110438. this.computeShelter();
  110439. //-------------
  110440. if(this.stats){
  110441. this.stats.end();
  110442. }
  110443. viewer.addTimeMark('loop','end');
  110444. viewer.addTimeMark('loopWaitNext','start');
  110445. this.resolveTimings(timestamp, Potree.measureTimings);
  110446. //Potree.measureTimings = 1
  110447. }
  110448. postError(content, params = {}){
  110449. let message = this.postMessage(content, params);
  110450. message.element.addClass("potree_message_error");
  110451. return message;
  110452. }
  110453. postMessage(content, params = {}){
  110454. let message = new Message(content);
  110455. let animationDuration = 100;
  110456. message.element.css("display", "none");
  110457. message.elClose.click( () => {
  110458. message.element.slideToggle(animationDuration);
  110459. let index = this.messages.indexOf(message);
  110460. if(index >= 0){
  110461. this.messages.splice(index, 1);
  110462. }
  110463. });
  110464. this.elMessages.prepend(message.element);
  110465. message.element.slideToggle(animationDuration);
  110466. this.messages.push(message);
  110467. if(params.duration !== undefined){
  110468. let fadeDuration = 500;
  110469. let slideOutDuration = 200;
  110470. setTimeout(() => {
  110471. message.element.animate({
  110472. opacity: 0
  110473. }, fadeDuration);
  110474. message.element.slideToggle(slideOutDuration);
  110475. }, params.duration);
  110476. }
  110477. return message;
  110478. }
  110479. getBoundingBox (pointclouds) {
  110480. //可以直接返回viewer.bound
  110481. if(!this.bound){
  110482. this.updateModelBound();
  110483. }
  110484. return this.bound.boundingBox.clone()//this.scene.getBoundingBox(pointclouds);
  110485. };
  110486. updateModelBound(reason){
  110487. this.boundNeedUpdate = false;
  110488. this.bound = Utils.computePointcloudsBound(this.scene.pointclouds.filter(pointcloud=> //只求可见
  110489. pointcloud.visible || pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode'
  110490. ));
  110491. if(Potree.settings.boundAddObjs){//加上obj的bound
  110492. this.objs.children.forEach(e=>{
  110493. this.bound.boundingBox.union(e.boundingBox.clone().applyMatrix4(e.matrixWorld));
  110494. });
  110495. this.bound.boundingBox.getSize(this.bound.boundSize);
  110496. this.bound.boundingBox.getCenter(this.bound.center);
  110497. }
  110498. viewer.farWhenShowPano = this.bound.boundSize.length() * 10;//全景漫游时要能看到整个skybox 原本*2的但对于距离特远的数据集需要乘大一些否则会黑面
  110499. /* let boundPlane = new THREE.Box3()
  110500. boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低
  110501. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度
  110502. FirstPersonControls.boundPlane = boundPlane */
  110503. //FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  110504. viewer.scene.pointclouds.forEach(e=>{//海拔范围
  110505. e.material.heightMin = this.bound.boundingBox.min.z;
  110506. e.material.heightMax = this.bound.boundingBox.max.z;
  110507. });
  110508. this.dispatchEvent({type:'updateModelBound'});
  110509. }
  110510. waitForLoad(object, isLoadedCallback){//等待加载时显示loading。主要是贴图
  110511. this.waitQueue.push({
  110512. object,
  110513. isLoadedCallback,
  110514. });
  110515. 1 === this.waitQueue.length && this.dispatchEvent({type:"loading", show:true});
  110516. }
  110517. ifAllLoaded( ){
  110518. if(this.waitQueue.length>0){
  110519. this.waitQueue = this.waitQueue.filter(function(e) {
  110520. return !e.isLoadedCallback()
  110521. });
  110522. }
  110523. 0 === this.waitQueue.length && this.dispatchEvent({type:"loading", show:false});
  110524. }
  110525. cancelLoad(object){//add 突然出现还没加载完就被deactivateTiledPano但还在loading的情况,所以加了这个
  110526. this.waitQueue = this.waitQueue.filter(function(e) {
  110527. return e.object != object
  110528. });
  110529. this.ifAllLoaded();
  110530. }
  110531. setView(o={}){
  110532. let callback = ()=>{
  110533. if(o.displayMode){
  110534. Potree.settings.displayMode = o.displayMode;
  110535. }
  110536. if(!o.pano && o.currentPano )this.images360.currentPano = o.currentPano;
  110537. o.callback && o.callback();
  110538. };
  110539. if(o.pano != void 0){//pano 权重高于 position
  110540. this.images360.flyToPano(o);
  110541. }else {
  110542. this.scene.view.setView($.extend({},o, {callback}));
  110543. }
  110544. }
  110545. //设置点云为标准模式
  110546. setPointStandardMat(state, pointDensity, fitPointsize){
  110547. console.log('setPointStandardMat',state);
  110548. if(state){
  110549. if(this.pointStatesBefore){
  110550. return console.error('已设置过pointStatesBefore!')
  110551. }
  110552. this.pointStatesBefore = {
  110553. opacity : new Map(),
  110554. size: new Map(),
  110555. density:Potree.settings.pointDensity,
  110556. useEDL:this.getEDLEnabled(),
  110557. shape: viewer.scene.pointclouds[0].material.shape
  110558. };
  110559. viewer.scene.pointclouds.forEach(e=>{
  110560. this.pointStatesBefore.opacity.set(e, e.temp.pointOpacity); //因为更改pointDensity时会自动变opacity,所以这项最先获取
  110561. this.pointStatesBefore.colorType = e.material.activeAttributeName;
  110562. fitPointsize && this.pointStatesBefore.size.set(e,e.temp.pointSize); //这项不一定有用,因为会被后期覆盖
  110563. });
  110564. if(pointDensity)Potree.settings.pointDensity = pointDensity; //万一之后切换到全景模式怎么办
  110565. if(fitPointsize)Potree.settings.sizeFitToLevel = true;
  110566. viewer.scene.pointclouds.forEach(e=>{
  110567. e.material.activeAttributeName = 'rgba';
  110568. e.material.shape = Potree.PointShape['SQUARE'];
  110569. fitPointsize && e.changePointSize(Potree.config.material.realPointSize, true);
  110570. e.changePointOpacity(1);
  110571. });
  110572. viewer.setEDLEnabled(false);
  110573. }else {
  110574. if(!this.pointStatesBefore){
  110575. return console.error('未设置过pointStatesBefore!')
  110576. }
  110577. Potree.settings.sizeFitToLevel = false;
  110578. if(pointDensity)Potree.settings.pointDensity = this.pointStatesBefore.pointDensity;
  110579. viewer.scene.pointclouds.forEach(e=>{
  110580. e.material.activeAttributeName = this.pointStatesBefore.colorType;
  110581. e.changePointOpacity(this.pointStatesBefore.opacity.get(e));
  110582. e.material.shape = this.pointStatesBefore.shape;
  110583. let size = this.pointStatesBefore.size.get(e);
  110584. if(size) e.changePointSize(size);
  110585. });
  110586. viewer.setEDLEnabled(this.pointStatesBefore.useEDL);
  110587. this.pointStatesBefore = null;
  110588. }
  110589. }
  110590. //调试时显示transformControl来调节object
  110591. transformObject(object){
  110592. let seleted = viewer.inputHandler.selection[0];
  110593. if(!object){//取消
  110594. seleted && viewer.inputHandler.toggleSelection(seleted);
  110595. return
  110596. }
  110597. if(seleted && seleted != object){//要更换,先取消
  110598. this.transformObject(null);
  110599. }
  110600. if(!object.boundingBox){
  110601. object.boundingBox = new Box3(); //任意大小 只是为了显示黄色外框
  110602. //??? computeBoundingBox
  110603. }
  110604. if(!viewer.inputHandler.selection.includes(object)){
  110605. viewer.inputHandler.toggleSelection(object);
  110606. }
  110607. }
  110608. pointInWhichPointcloud(pos){//选择最接近中心的那个 使用boundSphere
  110609. let result = Common$1.sortByScore(this.scene.pointclouds,[],[
  110610. (pointcloud)=>{
  110611. var size = pointcloud.pcoGeometry.tightBoundingBox.getSize(new Vector3);
  110612. var center = pointcloud.bound.getCenter(new Vector3);
  110613. var length = size.length() / 2;
  110614. var dis = pos.distanceTo(center);
  110615. return length / dis //到数据集中心的距离占数据集大小越小越好
  110616. }
  110617. ]);
  110618. //若要求更准确的话,可以使用ifContainsPoint判断一下是否在bound中
  110619. let r = result[0];
  110620. return r && r.score > 1 ? result[0].item : null
  110621. }
  110622. /* addObjectTest1(){//加水管
  110623. if(Potree.settings.number == 't-8KbK1JjubE'){
  110624. let boundingBox = new THREE.Box3()
  110625. boundingBox.min.set(-1,-1,-1); boundingBox.max.set(1,1,1)
  110626. let radius = 0.08;
  110627. let radialSegments = 5
  110628. let radSegments = Math.PI*2 / radialSegments
  110629. var circlePts = [];//横截面
  110630. for(let i=0;i<radialSegments;i++){
  110631. let angle = radSegments * i;
  110632. circlePts.push(new THREE.Vector2(radius * Math.cos(angle), radius * Math.sin(angle) ))
  110633. }
  110634. var count = 0
  110635. var addMesh = (color, path, height)=>{//height:在path之上的高度,负数代表在path之下
  110636. var name = 'cylinder'+count
  110637. var mat = new THREE.MeshStandardMaterial({color, depthTest:false, roughness:0.4,metalness:0.5}) 
  110638. let linePath = path.map(e=>new THREE.Vector3().copy(e).setZ(e.z+height))
  110639. let geo = MeshDraw.getExtrudeGeo( circlePts, null,{ extrudePath:linePath, tension:0.2} )
  110640. var mesh = new THREE.Mesh(geo,mat);
  110641. mesh.name = name
  110642. window[name] = mesh
  110643. mesh.boundingBox = boundingBox
  110644. mesh.matrixAutoUpdate = false
  110645. mesh.matrix.copy(viewer.scene.pointclouds[0].transformMatrix)
  110646. mesh.matrixWorldNeedsUpdate = true
  110647. this.scene.scene.add(mesh);
  110648. count ++
  110649. }
  110650. let linePath, height
  110651. //地上管子 黄色
  110652. 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}
  110653. ,{"x":43.58,"y":27.7,"z":-0.97},{"x":40.22,"y":35.37,"z":-0.67}// 拐弯向右
  110654. , {"x":39.18,"y":36.71,"z":0.35},{"x":38.69,"y":36.04,"z":18.04} // 拐弯向上
  110655. ]
  110656. height = radius + 0.05;
  110657. addMesh('#b86', linePath, height)
  110658. //地下管子 藍色
  110659. 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}
  110660. ]
  110661. height = -0.5;
  110662. addMesh('#48a', linePath, height)
  110663. }
  110664. }
  110665. */
  110666. /* createRoomEv(){
  110667. const environment = new RoomEnvironment();
  110668. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  110669. }
  110670. */
  110671. async loadModel(fileInfo, done, onProgress_, onError){
  110672. console.log('开始加载', Common$1.getNameFromURL(fileInfo.url) );
  110673. let boundingBox = new Box3();
  110674. /* if(!Potree.settings.boundAddObjs){
  110675. boundingBox.min.set(-0.5,-0.5,-0.5); boundingBox.max.set(0.5,0.5,0.5)
  110676. } */
  110677. if(fileInfo.objurl){
  110678. fileInfo.url = fileInfo.objurl, fileInfo.fileType = 'obj'; //兼容最早的
  110679. }
  110680. if(fileInfo.url instanceof Array){
  110681. if(fileInfo.url.length == 1){
  110682. fileInfo.url = fileInfo.url[0];
  110683. }else {
  110684. fileInfo.loadedCount = 0;
  110685. fileInfo.modelGroup = new Object3D; //parentGroup.name = fileInfo.title
  110686. fileInfo.url.forEach((url,i)=>{
  110687. let fileInfoS = Common$1.CloneObject(fileInfo);
  110688. fileInfoS.url = url;
  110689. fileInfoS.name = 'child-'+i;
  110690. fileInfoS.parentInfo = fileInfo;
  110691. this.loadModel(fileInfoS, done, onProgress_, onError);
  110692. });
  110693. return
  110694. }
  110695. }
  110696. fileInfo.url = Common$1.dealURL(fileInfo.url); //去除'+'
  110697. fileInfo.loadStartTime = Date.now();
  110698. //let fileType = fileInfo.tilesUrl ? '3dTiles' : fileInfo.objurl ? 'obj' : 'glb'
  110699. let loadDone = (object, fileInfo_ /* , total, url */)=>{
  110700. fileInfo_ = fileInfo_ || fileInfo;
  110701. if(fileInfo_.parentInfo){
  110702. object.name = fileInfo_.name;
  110703. fileInfo_.parentInfo.loadedCount ++;
  110704. fileInfo_.parentInfo.modelGroup.add(object);
  110705. if(fileInfo_.parentInfo.loadedCount == fileInfo_.parentInfo.url.length){
  110706. return loadDone(fileInfo_.parentInfo.modelGroup, fileInfo_.parentInfo)
  110707. }else {
  110708. return
  110709. }
  110710. }
  110711. object.name = fileInfo_.name != void 0 ? fileInfo_.name : fileInfo_.type;
  110712. object.fileType = fileInfo_.fileType;
  110713. object.boundingBox = boundingBox; //未乘上matrixWorld的本地boundingBox
  110714. //object.scale.set(1,1,1);//先获取原始的大小时的boundingBox
  110715. object.opacity = 1; //初始化 记录
  110716. object.updateMatrixWorld();
  110717. if(fileInfo_.id != void 0)object.dataset_id = fileInfo_.id;
  110718. fileInfo_.loadCostTime = Date.now() - fileInfo_.loadStartTime;
  110719. /* let weight = Math.round((total / 1024 / 1024) * 100) / 100;*/
  110720. console.log( '加载完毕:', Common$1.getNameFromURL(fileInfo_.url), '耗时(ms)', fileInfo_.loadCostTime, /* 模型数据量:' + weight + 'M' */);
  110721. if(fileInfo_.fileType == '3dTiles'){
  110722. let tileset = object.runtime.getTileset();
  110723. //TileHeader: tileset.root
  110724. //参见另一个工程 TileRenderer.js preprocessNode //这个坐标位置几万…… let data = boundingVolume.halfAxes //但这个似乎是premultiply( transform );过后的,可能需还原下
  110725. let json = tileset.tileset;
  110726. let box = json.root.boundingVolume.box;
  110727. if(box){
  110728. let center = new Vector3(box[0],box[1],box[2]);
  110729. let boundSize = new Vector3( );
  110730. // get the extents of the bounds in each axis
  110731. let vecX = new Vector3( box[ 3 ], box[ 4 ], box[ 5 ] );
  110732. let vecY = new Vector3( box[ 6 ], box[ 7 ], box[ 8 ] );
  110733. let vecZ = new Vector3( box[ 9 ], box[ 10 ], box[ 11 ] );
  110734. const scaleX = vecX.length();
  110735. const scaleY = vecY.length();
  110736. const scaleZ = vecZ.length();
  110737. /* boundingBox.expandByPoint(center);
  110738. boundingBox.expandByVector(new THREE.Vector3(scaleX,scaleY,scaleZ)) */
  110739. boundingBox.min.set( - scaleX, - scaleY, - scaleZ );
  110740. boundingBox.max.set( scaleX, scaleY, scaleZ );
  110741. }else if(json.root.boundingVolume.sphere){
  110742. let sphereData = json.root.boundingVolume.sphere;
  110743. let center = new Vector3(...sphereData);
  110744. let radius = sphereData[3] / 2;
  110745. /* let sphere = new THREE.Sphere(center, radius)
  110746. let box = sphere.getBoundingBox()
  110747. boundingBox.copy(box) */
  110748. boundingBox.min.set( - radius, - radius, - radius );
  110749. boundingBox.max.set( radius, radius, radius );
  110750. }else {
  110751. return console.error('json boundingVolume 缺少信息')
  110752. }
  110753. //中心点居然没用。可能是漏用了什么信息,也许这和LVBADUI_qp是散的有关。
  110754. console.log('3d tiles json',json);
  110755. json.root.refine = 'ADD';
  110756. json.refine = 'ADD';
  110757. }else {
  110758. Potree.Utils.setObjectLayers(object,'model');
  110759. object.traverse( ( child )=>{
  110760. if ( child instanceof Mesh || child instanceof Points ) {
  110761. child.renderOrder = Potree.config.renderOrders.model;
  110762. if(Potree.settings.boundAddObjs){
  110763. child.geometry.computeBoundingBox();
  110764. //console.log(child.matrixWorld.clone())
  110765. boundingBox.union(child.geometry.boundingBox.clone().applyMatrix4(child.matrixWorld)); //但感觉如果最外层object大小不为1,要还原下scale再乘
  110766. }//获取在scale为1时,表现出的大小
  110767. //Potree.Utils.makeTexDontResize(child.material.map)
  110768. //console.log(child.name, 'roughness',child.material.roughness,'metalness',child.material.metalness)
  110769. /* //暂时用这种材质:
  110770. if(fileInfo.unlit && (!(child.material instanceof THREE.MeshBasicMaterial) || fileType == 'glb')){
  110771. //let material = new THREE.MeshBasicMaterial({map:child.material.map})
  110772. let material = new BasicMaterial({map : child.material.map}) //很奇怪glb的图会使原本的MeshBasicMaterial 会偏暗,所以自己重新写
  110773. //child.material.dispose()
  110774. child.material = material
  110775. } */
  110776. if(child.material instanceof MeshStandardMaterial){
  110777. child.material.roughness = 0.6;
  110778. child.material.metalness = 0.3;
  110779. }
  110780. }
  110781. } );
  110782. }
  110783. this.objs.add(object);
  110784. if(fileInfo_.transform){
  110785. let setTransfrom = (name)=>{
  110786. let value = fileInfo_.transform[name];
  110787. if(!value)return
  110788. if(value instanceof Array){
  110789. object[name].fromArray(value);
  110790. }else {
  110791. object[name].copy(value);
  110792. }
  110793. };
  110794. setTransfrom('position');
  110795. setTransfrom('rotation');
  110796. setTransfrom('scale');
  110797. }
  110798. if(fileInfo_.moveWithPointcloud){
  110799. object.updateMatrix();
  110800. object.matrixAutoUpdate = false;
  110801. object.matrix.premultiply(viewer.scene.pointclouds[0].transformMatrix); //默认跟随第一个数据集
  110802. object.matrixWorldNeedsUpdate = true;
  110803. }
  110804. done && done(object);
  110805. };
  110806. let onProgress = function ( xhr ) {
  110807. if ( xhr.lengthComputable ) {
  110808. let percentComplete = xhr.loaded / xhr.total * 100;
  110809. //console.log( Math.round(percentComplete, 2) + '% downloaded' );
  110810. onProgress_ && onProgress_(percentComplete);
  110811. }
  110812. };
  110813. if(fileInfo.fileType == 'obj'){ //暂时不支持数组
  110814. loaders.mtlLoader.load( fileInfo.mtlurl , (materials)=>{
  110815. materials.preload();
  110816. loaders.objLoader.setMaterials( materials ).load(fileInfo.objurl, (object, total)=>{
  110817. loadDone(object/* , total, fileInfo.objurl */);
  110818. });
  110819. } , onProgress, onError );
  110820. }else if(fileInfo.fileType == 'glb'){
  110821. loaders.glbLoader.unlitMat = true;//!!fileInfo.unlit
  110822. loaders.glbLoader.load(fileInfo.url, ( gltf, total )=>{
  110823. //console.log('loadGLTF', gltf)
  110824. loadDone(gltf.scene/* , total, fileInfo.url */);
  110825. }, onProgress, onError);
  110826. }else if(fileInfo.fileType == 'ply'){
  110827. loaders.plyLoader.load( fileInfo.url, (geometry) => {
  110828. let object;
  110829. console.log('ply加载完毕', geometry);
  110830. if(!geometry.index){//点云
  110831. object = new Points(geometry, new PointsMaterial({vertexColors:true, size:0.02}));
  110832. //141M的点云,intersect费时300ms以上
  110833. }else {//mesh
  110834. object = new Mesh(geometry);
  110835. }
  110836. loadDone(object);
  110837. });
  110838. }else if(fileInfo.fileType == '3dTiles'){
  110839. let result = await Loader3DTiles.load({
  110840. url: fileInfo.url,
  110841. gltfLoader : loaders.glbLoader,
  110842. //renderer: SceneRenderer.renderer
  110843. options: {
  110844. //dracoDecoderPath: '../utils/loaders/DRACOLoader/draco',
  110845. //basisTranscoderPath: '../utils/loaders/KTX2Loader/basis',
  110846. maximumScreenSpaceError: 30, //如果本身tiles很密很小这个值就不能很大。
  110847. maxDepth: 100,
  110848. maximumMemoryUsage: 200, //缓存大小。单位M(但实际结果是 2.5*maximumMemoryUsage + 750 。超过2G会崩, 所以应该小于540) 若太小,密集的tile反复加载很卡. (任务管理器刷新网页后若内存不掉就要结束进程否则虚高)
  110849. //debug:true,
  110850. parent: this.scene.scene
  110851. },
  110852. });
  110853. console.log(result);
  110854. result.model.runtime = result.runtime;
  110855. loadDone(result.model/* , null, fileInfo.url */);
  110856. let loaded = false;
  110857. let tileset = result.runtime.getTileset();
  110858. tileset.addEventListener('endTileLoading', function (data) {//Tileset3D
  110859. if (data.loadingCount == 0 && !loaded) {
  110860. loaded = true;
  110861. console.log('loaded!!!!!!!!!!!!!');
  110862. }
  110863. });
  110864. tileset.addEventListener('tileLoaded',(e)=>{ //每一个tile加载完要更改透明度
  110865. let opacity = result.model.opacity;
  110866. MergeEditor.changeOpacity(e.tileContent,opacity);
  110867. });
  110868. {
  110869. let vi = true;
  110870. Object.defineProperty( result.model, "visible", {
  110871. get: function() {
  110872. return vi
  110873. },
  110874. set: function(v) {
  110875. vi = v;
  110876. tileset.visible = v; //同步,使不加载
  110877. tileset.nextForceUpdate = true;
  110878. }
  110879. });
  110880. }
  110881. }
  110882. }
  110883. removeObj(object){
  110884. this.objs.remove(object);
  110885. if(Potree.settings.boundAddObjs){
  110886. this.updateModelBound();
  110887. }
  110888. }
  110889. setDisplay(state, cause='setDisplay'){//如果创建了iframe,主页的需要隐藏的话需要释放一些内存出来。iframe关闭前也释放下比较保险
  110890. state = !!state;
  110891. this.objs.children.forEach(e=>{
  110892. if(e.fileType == '3dTiles'){
  110893. let tileset = e.runtime.getTileset();
  110894. Potree.Utils.updateVisible(e, cause, state);
  110895. if(!state) tileset._cache.trim(); //使下一次update时dispose所有不可见的tiles
  110896. e.runtime.update(16, this.renderer, this.mainViewport.camera, true);
  110897. if(state) this.dispatchEvent('content_changed');
  110898. }
  110899. });
  110900. if(state){
  110901. Potree.pointBudget = 6*1000*1000; //先随便写一个, 随后mergeEditor.updateMemoryUsage
  110902. }else {
  110903. Potree.pointBudget = 0;
  110904. Potree.updatePointClouds(this.scene.pointclouds, this.mainViewport.camera, this.mainViewport.resolution );
  110905. }
  110906. this.dispatchEvent({type:'setDisplay',state});
  110907. this.paused = !state;
  110908. }
  110909. addFire(){
  110910. if(Potree.settings.number == 't-CwfhfqJ'){
  110911. let position = Potree.Utils.datasetPosTransform({
  110912. pointcloud:viewer.scene.pointclouds[0],
  110913. position: new Vector3(4.4318,-0.580291847759, -0.78),
  110914. fromDataset:true
  110915. });
  110916. viewer.modules.ParticleEditor.addParticle( {
  110917. type:'fire',
  110918. positions:[position],
  110919. radius:0.42,
  110920. height:10,
  110921. });
  110922. viewer.modules.ParticleEditor.addParticle( {
  110923. type:'smoke',
  110924. positions: [ new Vector3().addVectors(position,new Vector3(0,0,0.3))],
  110925. positionStyle : 'sphere' ,
  110926. positionRadius : 0.3,
  110927. sizeTween: [[0, 0.3, 0.9, 1], [0.05, 0.1, 1, 0.8]],
  110928. opacityBase : 0.2,
  110929. opacityTween :[ [0, 0.3, 0.7, 0.95, 1], [0, 0.2, 1 , 0.1, 0] ],
  110930. velocityBase : new Vector3( 0, 0, 1),
  110931. velocitySpread : new Vector3( 0.2, 0.2, -0.3),
  110932. accelerationBase : 0.2,
  110933. accelerationSpread : 0.7,
  110934. radius:0,
  110935. //particlesPerSecond : 30,
  110936. particleDeathAge : 3.0,
  110937. });
  110938. viewer.modules.ParticleEditor.addParticle( {
  110939. type:'explode',
  110940. name:'fire splash',
  110941. position: new Vector3().addVectors(position,new Vector3(0,0,0.3)),
  110942. size: 0.1,
  110943. sizeRange: 0.3,
  110944. sizeTween:[[0, 0.05, 0.3, 0.45], [0, 0.02, 0.1, 0.05] ],
  110945. opacityTween: [[0, 0.05, 0.3, 0.45], [1, 1, 0.5, 0]] ,
  110946. speed : 1, //sphere
  110947. speedRange : 4,
  110948. radius: 0.1,
  110949. acceleration : 0.3,
  110950. accelerationRange : 1,
  110951. particleSpaceTime:0,
  110952. strength:4,
  110953. });
  110954. }
  110955. }
  110956. addVideo(){
  110957. if(Potree.settings.number != 'SS-t-P6zBR73Gke')return
  110958. var geo = new PlaneGeometry(1, 1, 1, 1);
  110959. var videoInfo = this.videoInfo = [
  110960. {
  110961. id: '40-2',
  110962. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/10/0aabafee-36b8-455d-9c11-0780bf694786.mp4',
  110963. rotation:[-1.494468618954883, -1.4987317433158989, -3.061254983446741],
  110964. position:[ 19.801820617361624, 2.884673619844108, -0.03362305858221648],
  110965. scale:[3.5741423153151763, 2.8738725275578703, 1],
  110966. },
  110967. {
  110968. id: 40,
  110969. /* rotation:[-1.534692822378723, 0.01083403560862361, 3.141535283661569],
  110970. position:[17.2934294239949861, 2.413510747928117, -0.008057029580231356], */
  110971. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/7896d6ef-a2d6-4fd7-949c-768782a5b484.mp4',
  110972. rotation:[-1.5487684197910518, 0.021848470169552752, -3.1387534893955236],
  110973. position:[17.277316608096, 2.0840432922115846, -0.0931149415437065],
  110974. scale:[2.0821757723834047, 0.6129478480765236, 1],
  110975. visibles: [40]
  110976. },
  110977. ];
  110978. let add = (info)=>{
  110979. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0];
  110980. video.setAttribute("crossOrigin", 'Anonymous');
  110981. video.src = info.url || Potree.resourcePath+`/video/${Potree.settings.number}/${info.id}.mp4`;
  110982. var map = new VideoTexture(video);
  110983. var plane = this.videoPlane = new Mesh(geo, new MeshBasicMaterial({
  110984. color:"#ffffff",
  110985. transparent: !0,
  110986. depthTest:false,
  110987. opacity:0 ,
  110988. //side:2,
  110989. map
  110990. }));
  110991. plane.position.fromArray(info.position);
  110992. plane.rotation.fromArray(info.rotation);
  110993. info.scale && plane.scale.fromArray(info.scale);
  110994. this.scene.scene.add(plane);
  110995. info.plane = plane;
  110996. plane.boundingBox = new Box3(new Vector3(0,-0.5,0),new Vector3(1,-0.4,0.2));
  110997. video.addEventListener('loadeddata', function(e) {
  110998. video.play();
  110999. if(!info.visibles/* ||!viewer.images360.currentPano || info.visibles.includes(viewer.images360.currentPano.id) */){
  111000. plane.material.opacity = 1;
  111001. }
  111002. info.scale || plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1); // 1080 * 1920
  111003. console.log('video loadeddata', info.id);
  111004. });
  111005. if(info.visibles){
  111006. this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  111007. if(info.visibles.includes(e.toPano.pano.id)){ //出现
  111008. setTimeout(()=>{
  111009. plane.visible = true;
  111010. video.currentTime = 0;
  111011. video.play();
  111012. if(video.paused){
  111013. var startPlay = ()=>{
  111014. plane.visible && video.play();
  111015. this.removeEventListener('global_mousedown', startPlay);
  111016. };
  111017. this.addEventListener('global_mousedown', startPlay);
  111018. }
  111019. Potree.settings.zoom.enabled = false;
  111020. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  111021. }, 0, easing['easeInOutQuad']);
  111022. }, e.toPano.duration*0.6); //时间上不能和消失的重叠 延迟
  111023. }else {
  111024. //消失
  111025. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  111026. if(!info){
  111027. plane.visible = false;
  111028. video.pause();
  111029. Potree.settings.zoom.enabled = true;
  111030. }
  111031. }, 0, easing['easeInOutQuad']);
  111032. }
  111033. });
  111034. }
  111035. var startPlay = ()=>{
  111036. video.play();
  111037. //video.pause()
  111038. //video.currentTime = 0.1;
  111039. this.removeEventListener('global_mousedown', startPlay);
  111040. };
  111041. this.addEventListener('global_mousedown', startPlay);
  111042. Potree.settings.isTest && plane.addEventListener('select',(e)=>{console.log(e);});
  111043. };
  111044. videoInfo.forEach(info=>{
  111045. add(info);
  111046. });
  111047. /* this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  111048. if(Potree.settings.displayMode != 'showPanos') return
  111049. let info = videoInfo[e.toPano.pano.id]
  111050. if(info ){ //出现
  111051. setTimeout(()=>{
  111052. plane.visible = true;
  111053. plane.position.fromArray(info.position)
  111054. plane.rotation.fromArray(info.rotation)
  111055. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4`
  111056. video.play();
  111057. video.currentTime = 0
  111058. Potree.settings.zoom.enabled = false
  111059. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  111060. }, 0, easing['easeInOutQuad'])
  111061. }, e.toPano.duration*0.6) //时间上不能和消失的重叠 延迟
  111062. }
  111063. //消失
  111064. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  111065. if(!info){
  111066. plane.visible = false
  111067. video.pause()
  111068. Potree.settings.zoom.enabled = true
  111069. }
  111070. }, 0, easing['easeInOutQuad'])
  111071. })
  111072. this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况
  111073. if(e.mode == 'showPanos'){
  111074. let info = videoInfo[this.images360.currentPano.id]
  111075. if(info ){ //出现
  111076. plane.visible = true;
  111077. plane.position.fromArray(info.position)
  111078. plane.rotation.fromArray(info.rotation)
  111079. plane.material.opacity = 0
  111080. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4`
  111081. video.play();
  111082. video.currentTime = 0
  111083. Potree.settings.zoom.enabled = false
  111084. transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e)}) , 300 , ()=>{
  111085. }, 0, easing['easeInOutQuad'])
  111086. }
  111087. }else{
  111088. plane.visible = false;
  111089. Potree.settings.zoom.enabled = true
  111090. }
  111091. })
  111092. */
  111093. }
  111094. addSprite(e){//api
  111095. let sprite;
  111096. if(e.text != void 0){
  111097. sprite = new TextSprite(e );
  111098. }else {
  111099. let map = texLoader.load(src);
  111100. e.map = map;
  111101. sprite = new Sprite(e );
  111102. }
  111103. return sprite
  111104. }
  111105. };
  111106. //------ CLIP 默认clipTask都是clipInside ----------------------
  111107. /*
  111108. 并集相当于加法,交集相当于乘法。 所有结果都能展开成多个乘积相加。
  111109. 假设有4个clipBoxes,ABCD, 如果是 A*B + C*D ,那么这是最终结果。 如果是 (A+B)*(C+D) = A*C+A*D+B*C+B*D
  111110. */
  111111. /*
  111112. let Clips = {
  111113. boxes : [],
  111114. unionGroups : [], //二维数组。最外层要求并集,里层要求交集(如果只有一个元素就是本身)。总结起来就是要求一堆交集的并集
  111115. shaderParams:{},
  111116. needsUpdate : true,
  111117. addClip(box, clipMethod){
  111118. //不允许重复
  111119. if(this.boxes.includes(box)){
  111120. return console.warn('addClip重复添加了box',box)
  111121. }
  111122. boxes.push(box)
  111123. if(clipMethod == 'any'){//并
  111124. this.unionGroups.push([box])
  111125. }else if(clipMethod == 'all'){//交
  111126. this.unionGroups.forEach(mixGroup=>mixGroup.push(box))
  111127. }
  111128. this.needsUpdate = true
  111129. },
  111130. removeClip(box){
  111131. if(!this.boxes.includes(box)){
  111132. return console.warn('removeClip没有找到该box',box)
  111133. }
  111134. var newGroups = [];
  111135. this.unionGroups.forEach(mixGroup=>{
  111136. if(mixGroup.length == 1 && mixGroup[0] == box)return;//直接删除
  111137. newGroups.push(mixGroup.filter(e=>e!=box));
  111138. })
  111139. this.unionGroups = newGroups;
  111140. this.needsUpdate = true
  111141. }
  111142. ,
  111143. clearClip(){
  111144. this.boxes = [];
  111145. this.unionGroups = []
  111146. this.needsUpdate = true
  111147. }
  111148. ,
  111149. updateShaderParams(){//没写完 - - 见 pointcloud clip.vs
  111150. //uniform mat4 clipBoxes[num_clipboxes];
  111151. //uniform int clipBoxGroupCount;
  111152. //uniform int mixClipIndices[clipboxGroupItemCount]; //把所有的要求都直接放到数组内
  111153. //这里需要转为Float32Array..? 参考material.setClipBoxes
  111154. let everyClipGroupCount = this.unionGroups.map(e=>e.length)
  111155. let mixClipIndices = []
  111156. this.unionGroups.forEach(e=>{
  111157. mixClipIndices.push(...e)
  111158. })
  111159. this.shaderParams = {
  111160. num_clipboxes : this.boxes.length,
  111161. clipBoxGroupCount : this.unionGroups.length,
  111162. everyClipGroupCount,
  111163. clipBoxIndexCount: mixClipIndices.length,
  111164. mixClipIndices
  111165. }
  111166. }
  111167. ,
  111168. getShaderParams(){//每次要传递参数到shader中,执行这个就好
  111169. if(this.needsUpdate){
  111170. this.updateShaderParams()
  111171. }
  111172. return this.shaderParams
  111173. }
  111174. }
  111175. */
  111176. /**
  111177. * @author mschuetz / http://mschuetz.at
  111178. *
  111179. * adapted from THREE.OrbitControls by
  111180. *
  111181. * @author qiao / https://github.com/qiao
  111182. * @author mrdoob / http://mrdoob.com
  111183. * @author alteredq / http://alteredqualia.com/
  111184. * @author WestLangley / http://github.com/WestLangley
  111185. * @author erich666 / http://erichaines.com
  111186. *
  111187. *
  111188. *
  111189. */
  111190. class OrbitControls$1 extends EventDispatcher$1{
  111191. constructor(viewer){
  111192. super();
  111193. this.viewer = viewer;
  111194. this.renderer = viewer.renderer;
  111195. this.scene = null;
  111196. this.sceneControls = new Scene();
  111197. this.rotationSpeed = 5;
  111198. this.fadeFactor = 20;
  111199. this.yawDelta = 0;
  111200. this.pitchDelta = 0;
  111201. this.panDelta = new Vector2(0, 0);
  111202. this.radiusDelta = 0;
  111203. this.doubleClockZoomEnabled = true;
  111204. this.tweens = [];
  111205. let drag = (e) => {
  111206. if (e.drag.object !== null) {
  111207. return;
  111208. }
  111209. if (e.drag.startHandled === undefined) {
  111210. e.drag.startHandled = true;
  111211. this.dispatchEvent({type: 'start'});
  111212. }
  111213. let ndrag = {
  111214. x: e.drag.lastDrag.x / this.renderer.domElement.clientWidth,
  111215. y: e.drag.lastDrag.y / this.renderer.domElement.clientHeight
  111216. };
  111217. if (e.drag.mouse === MOUSE$1.LEFT) {
  111218. this.yawDelta += ndrag.x * this.rotationSpeed;
  111219. this.pitchDelta += ndrag.y * this.rotationSpeed;
  111220. this.stopTweens();
  111221. } else if (e.drag.mouse === MOUSE$1.RIGHT) {
  111222. this.panDelta.x += ndrag.x;
  111223. this.panDelta.y += ndrag.y;
  111224. this.stopTweens();
  111225. }
  111226. };
  111227. let drop = e => {
  111228. this.dispatchEvent({type: 'end'});
  111229. };
  111230. let scroll = (e) => {
  111231. let resolvedRadius = this.scene.view.radius + this.radiusDelta;
  111232. this.radiusDelta += -e.delta * resolvedRadius * 0.1;
  111233. this.stopTweens();
  111234. };
  111235. let dblclick = (e) => {
  111236. if(this.doubleClockZoomEnabled){
  111237. this.zoomToLocation(e.mouse);
  111238. }
  111239. };
  111240. let previousTouch = null;
  111241. let touchStart = e => {
  111242. previousTouch = e;
  111243. };
  111244. let touchEnd = e => {
  111245. previousTouch = e;
  111246. };
  111247. let touchMove = e => {
  111248. if (e.touches.length === 2 && previousTouch.touches.length === 2){
  111249. let prev = previousTouch;
  111250. let curr = e;
  111251. let prevDX = prev.touches[0].pageX - prev.touches[1].pageX;
  111252. let prevDY = prev.touches[0].pageY - prev.touches[1].pageY;
  111253. let prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY);
  111254. let currDX = curr.touches[0].pageX - curr.touches[1].pageX;
  111255. let currDY = curr.touches[0].pageY - curr.touches[1].pageY;
  111256. let currDist = Math.sqrt(currDX * currDX + currDY * currDY);
  111257. let delta = currDist / prevDist;
  111258. let resolvedRadius = this.scene.view.radius + this.radiusDelta;
  111259. let newRadius = resolvedRadius / delta;
  111260. this.radiusDelta = newRadius - resolvedRadius;
  111261. this.stopTweens();
  111262. }else if(e.touches.length === 3 && previousTouch.touches.length === 3){
  111263. let prev = previousTouch;
  111264. let curr = e;
  111265. let prevMeanX = (prev.touches[0].pageX + prev.touches[1].pageX + prev.touches[2].pageX) / 3;
  111266. let prevMeanY = (prev.touches[0].pageY + prev.touches[1].pageY + prev.touches[2].pageY) / 3;
  111267. let currMeanX = (curr.touches[0].pageX + curr.touches[1].pageX + curr.touches[2].pageX) / 3;
  111268. let currMeanY = (curr.touches[0].pageY + curr.touches[1].pageY + curr.touches[2].pageY) / 3;
  111269. let delta = {
  111270. x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth,
  111271. y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight
  111272. };
  111273. this.panDelta.x += delta.x;
  111274. this.panDelta.y += delta.y;
  111275. this.stopTweens();
  111276. }
  111277. previousTouch = e;
  111278. };
  111279. this.addEventListener('touchstart', touchStart);
  111280. this.addEventListener('touchend', touchEnd);
  111281. this.addEventListener('touchmove', touchMove);
  111282. this.addEventListener('drag', drag);
  111283. this.addEventListener('drop', drop);
  111284. this.addEventListener('mousewheel', scroll);
  111285. this.addEventListener('dblclick', dblclick);
  111286. }
  111287. setScene (scene) {
  111288. this.scene = scene;
  111289. }
  111290. stop(){
  111291. this.yawDelta = 0;
  111292. this.pitchDelta = 0;
  111293. this.radiusDelta = 0;
  111294. this.panDelta.set(0, 0);
  111295. }
  111296. zoomToLocation(mouse){
  111297. let camera = this.scene.getActiveCamera();
  111298. let I = Utils.getMousePointCloudIntersection(
  111299. mouse,
  111300. camera,
  111301. this.viewer,
  111302. this.scene.pointclouds,
  111303. {pickClipped: true});
  111304. if (I === null) {
  111305. return;
  111306. }
  111307. let targetRadius = 0;
  111308. {
  111309. let minimumJumpDistance = 0.2;
  111310. let domElement = this.renderer.domElement;
  111311. let ray = Utils.mouseToRay(mouse, camera, domElement.clientWidth, domElement.clientHeight);
  111312. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  111313. let lastNode = nodes[nodes.length - 1];
  111314. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  111315. targetRadius = Math.min(this.scene.view.radius, radius);
  111316. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  111317. }
  111318. let d = this.scene.view.direction.multiplyScalar(-1);
  111319. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  111320. // TODO Unused: let controlsTargetPosition = I.location;
  111321. let animationDuration = 600;
  111322. let easing = TWEEN.Easing.Quartic.Out;
  111323. { // animate
  111324. let value = {x: 0};
  111325. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  111326. tween.easing(easing);
  111327. this.tweens.push(tween);
  111328. let startPos = this.scene.view.position.clone();
  111329. let targetPos = cameraTargetPosition.clone();
  111330. let startRadius = this.scene.view.radius;
  111331. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  111332. tween.onUpdate(() => {
  111333. let t = value.x;
  111334. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  111335. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  111336. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  111337. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  111338. this.viewer.setMoveSpeed(this.scene.view.radius);
  111339. });
  111340. tween.onComplete(() => {
  111341. this.tweens = this.tweens.filter(e => e !== tween);
  111342. });
  111343. tween.start();
  111344. }
  111345. }
  111346. stopTweens () {
  111347. this.tweens.forEach(e => e.stop());
  111348. this.tweens = [];
  111349. }
  111350. update (delta) {
  111351. let view = this.scene.view;
  111352. { // apply rotation
  111353. let progression = Math.min(1, this.fadeFactor * delta);
  111354. let yaw = view.yaw;
  111355. let pitch = view.pitch;
  111356. let pivot = view.getPivot();
  111357. yaw -= progression * this.yawDelta;
  111358. pitch -= progression * this.pitchDelta;
  111359. view.yaw = yaw;
  111360. view.pitch = pitch;
  111361. let V = this.scene.view.direction.multiplyScalar(-view.radius);
  111362. let position = new Vector3().addVectors(pivot, V);
  111363. view.position.copy(position);
  111364. }
  111365. { // apply pan
  111366. let progression = Math.min(1, this.fadeFactor * delta);
  111367. let panDistance = progression * view.radius * 3;
  111368. let px = -this.panDelta.x * panDistance;
  111369. let py = this.panDelta.y * panDistance;
  111370. view.pan(px, py);
  111371. }
  111372. { // apply zoom
  111373. let progression = Math.min(1, this.fadeFactor * delta);
  111374. // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1;
  111375. let radius = view.radius + progression * this.radiusDelta;
  111376. let V = view.direction.multiplyScalar(-radius);
  111377. let position = new Vector3().addVectors(view.getPivot(), V);
  111378. view.radius = radius;
  111379. view.position.copy(position);
  111380. }
  111381. {
  111382. let speed = view.radius;
  111383. this.viewer.setMoveSpeed(speed);
  111384. }
  111385. { // decelerate over time
  111386. let progression = Math.min(1, this.fadeFactor * delta);
  111387. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  111388. this.yawDelta *= attenuation;
  111389. this.pitchDelta *= attenuation;
  111390. this.panDelta.multiplyScalar(attenuation);
  111391. // this.radiusDelta *= attenuation;
  111392. this.radiusDelta -= progression * this.radiusDelta;
  111393. }
  111394. }
  111395. };
  111396. /**
  111397. * @author mschuetz / http://mschuetz.at
  111398. *
  111399. * adapted from THREE.OrbitControls by
  111400. *
  111401. * @author qiao / https://github.com/qiao
  111402. * @author mrdoob / http://mrdoob.com
  111403. * @author alteredq / http://alteredqualia.com/
  111404. * @author WestLangley / http://github.com/WestLangley
  111405. * @author erich666 / http://erichaines.com
  111406. *
  111407. *
  111408. *
  111409. */
  111410. class FirstPersonControls$1 extends EventDispatcher$1 {//old
  111411. constructor (viewer) {
  111412. super();
  111413. this.viewer = viewer;
  111414. this.renderer = viewer.renderer;
  111415. this.scene = null;
  111416. this.sceneControls = new Scene();
  111417. this.rotationSpeed = 200;
  111418. this.moveSpeed = 10;
  111419. this.lockElevation = false;
  111420. this.keys = {
  111421. FORWARD: ['W'.charCodeAt(0), 38],
  111422. BACKWARD: ['S'.charCodeAt(0), 40],
  111423. LEFT: ['A'.charCodeAt(0), 37],
  111424. RIGHT: ['D'.charCodeAt(0), 39],
  111425. UP: ['R'.charCodeAt(0), 33],
  111426. DOWN: ['F'.charCodeAt(0), 34]
  111427. };
  111428. this.fadeFactor = 50;
  111429. this.yawDelta = 0;
  111430. this.pitchDelta = 0;
  111431. this.translationDelta = new Vector3(0, 0, 0);
  111432. this.translationWorldDelta = new Vector3(0, 0, 0);
  111433. this.tweens = [];
  111434. let drag = (e) => {
  111435. if (e.drag.object !== null) {
  111436. return;
  111437. }
  111438. if (e.drag.startHandled === undefined) {
  111439. e.drag.startHandled = true;
  111440. this.dispatchEvent({type: 'start'});
  111441. }
  111442. let moveSpeed = this.viewer.getMoveSpeed();
  111443. let ndrag = {
  111444. x: e.drag.lastDrag.x / this.renderer.domElement.clientWidth,
  111445. y: e.drag.lastDrag.y / this.renderer.domElement.clientHeight
  111446. };
  111447. if (e.drag.mouse === MOUSE$1.LEFT) {
  111448. this.yawDelta += ndrag.x * this.rotationSpeed;
  111449. this.pitchDelta += ndrag.y * this.rotationSpeed;
  111450. } else if (e.drag.mouse === MOUSE$1.RIGHT) {
  111451. this.translationDelta.x -= ndrag.x * moveSpeed * 100;
  111452. this.translationDelta.z += ndrag.y * moveSpeed * 100;
  111453. }
  111454. };
  111455. let drop = e => {
  111456. this.dispatchEvent({type: 'end'});
  111457. };
  111458. let scroll = (e) => {
  111459. let speed = this.viewer.getMoveSpeed();
  111460. if (e.delta < 0) {
  111461. speed = speed * 0.9;
  111462. } else if (e.delta > 0) {
  111463. speed = speed / 0.9;
  111464. }
  111465. speed = Math.max(speed, 0.1);
  111466. this.viewer.setMoveSpeed(speed);
  111467. };
  111468. let dblclick = (e) => {
  111469. this.zoomToLocation(e.mouse);
  111470. };
  111471. this.addEventListener('drag', drag);
  111472. this.addEventListener('drop', drop);
  111473. this.addEventListener('mousewheel', scroll);
  111474. this.addEventListener('dblclick', dblclick);
  111475. }
  111476. setScene (scene) {
  111477. this.scene = scene;
  111478. }
  111479. stop(){
  111480. this.yawDelta = 0;
  111481. this.pitchDelta = 0;
  111482. this.translationDelta.set(0, 0, 0);
  111483. }
  111484. zoomToLocation(mouse){
  111485. let camera = this.scene.getActiveCamera();
  111486. let I = Utils.getMousePointCloudIntersection(
  111487. mouse,
  111488. camera,
  111489. this.viewer,
  111490. this.scene.pointclouds);
  111491. if (I === null) {
  111492. return;
  111493. }
  111494. let targetRadius = 0;
  111495. {
  111496. let minimumJumpDistance = 0.2;
  111497. let domElement = this.renderer.domElement;
  111498. let ray = Utils.mouseToRay(mouse, camera, domElement.clientWidth, domElement.clientHeight);
  111499. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  111500. let lastNode = nodes[nodes.length - 1];
  111501. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  111502. targetRadius = Math.min(this.scene.view.radius, radius);
  111503. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  111504. }
  111505. let d = this.scene.view.direction.multiplyScalar(-1);
  111506. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  111507. // TODO Unused: let controlsTargetPosition = I.location;
  111508. let animationDuration = 600;
  111509. let easing = TWEEN.Easing.Quartic.Out;
  111510. { // animate
  111511. let value = {x: 0};
  111512. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  111513. tween.easing(easing);
  111514. this.tweens.push(tween);
  111515. let startPos = this.scene.view.position.clone();
  111516. let targetPos = cameraTargetPosition.clone();
  111517. let startRadius = this.scene.view.radius;
  111518. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  111519. tween.onUpdate(() => {
  111520. let t = value.x;
  111521. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  111522. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  111523. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  111524. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  111525. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  111526. });
  111527. tween.onComplete(() => {
  111528. this.tweens = this.tweens.filter(e => e !== tween);
  111529. });
  111530. tween.start();
  111531. }
  111532. }
  111533. update (delta) {
  111534. let view = this.scene.view;
  111535. { // cancel move animations on user input
  111536. let changes = [ this.yawDelta,
  111537. this.pitchDelta,
  111538. this.translationDelta.length(),
  111539. this.translationWorldDelta.length() ];
  111540. let changeHappens = changes.some(e => Math.abs(e) > 0.001);
  111541. if (changeHappens && this.tweens.length > 0) {
  111542. this.tweens.forEach(e => e.stop());
  111543. this.tweens = [];
  111544. }
  111545. }
  111546. { // accelerate while input is given
  111547. let ih = this.viewer.inputHandler;
  111548. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  111549. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  111550. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  111551. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  111552. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  111553. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  111554. if(this.lockElevation){
  111555. let dir = view.direction;
  111556. dir.z = 0;
  111557. dir.normalize();
  111558. if (moveForward && moveBackward) {
  111559. this.translationWorldDelta.set(0, 0, 0);
  111560. } else if (moveForward) {
  111561. this.translationWorldDelta.copy(dir.multiplyScalar(this.viewer.getMoveSpeed()));
  111562. } else if (moveBackward) {
  111563. this.translationWorldDelta.copy(dir.multiplyScalar(-this.viewer.getMoveSpeed()));
  111564. }
  111565. }else {
  111566. if (moveForward && moveBackward) {
  111567. this.translationDelta.y = 0;
  111568. } else if (moveForward) {
  111569. this.translationDelta.y = this.viewer.getMoveSpeed();
  111570. } else if (moveBackward) {
  111571. this.translationDelta.y = -this.viewer.getMoveSpeed();
  111572. }
  111573. }
  111574. if (moveLeft && moveRight) {
  111575. this.translationDelta.x = 0;
  111576. } else if (moveLeft) {
  111577. this.translationDelta.x = -this.viewer.getMoveSpeed();
  111578. } else if (moveRight) {
  111579. this.translationDelta.x = this.viewer.getMoveSpeed();
  111580. }
  111581. if (moveUp && moveDown) {
  111582. this.translationWorldDelta.z = 0;
  111583. } else if (moveUp) {
  111584. this.translationWorldDelta.z = this.viewer.getMoveSpeed();
  111585. } else if (moveDown) {
  111586. this.translationWorldDelta.z = -this.viewer.getMoveSpeed();
  111587. }
  111588. }
  111589. { // apply rotation
  111590. let yaw = view.yaw;
  111591. let pitch = view.pitch;
  111592. yaw -= this.yawDelta * delta;
  111593. pitch -= this.pitchDelta * delta;
  111594. view.yaw = yaw;
  111595. view.pitch = pitch;
  111596. }
  111597. { // apply translation
  111598. view.translate(
  111599. this.translationDelta.x * delta,
  111600. this.translationDelta.y * delta,
  111601. this.translationDelta.z * delta
  111602. );
  111603. view.translateWorld(
  111604. this.translationWorldDelta.x * delta,
  111605. this.translationWorldDelta.y * delta,
  111606. this.translationWorldDelta.z * delta
  111607. );
  111608. }
  111609. { // set view target according to speed
  111610. view.radius = 3 * this.viewer.getMoveSpeed();
  111611. }
  111612. { // decelerate over time
  111613. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  111614. this.yawDelta *= attenuation;
  111615. this.pitchDelta *= attenuation;
  111616. this.translationDelta.multiplyScalar(attenuation);
  111617. this.translationWorldDelta.multiplyScalar(attenuation);
  111618. }
  111619. }
  111620. };
  111621. OrthographicCamera.prototype.zoomTo = function( node, factor = 1){
  111622. if ( !node.geometry && !node.boundingBox) {
  111623. return;
  111624. }
  111625. // TODO
  111626. //let minWS = new THREE.Vector4(node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z, 1);
  111627. //let minVS = minWS.applyMatrix4(this.matrixWorldInverse);
  111628. //let right = node.boundingBox.max.x;
  111629. //let bottom = node.boundingBox.min.y;
  111630. //let top = node.boundingBox.max.y;
  111631. this.updateProjectionMatrix();
  111632. };
  111633. PerspectiveCamera.prototype.zoomTo = function (node, factor) {
  111634. if (!node.geometry && !node.boundingSphere && !node.boundingBox) {
  111635. return;
  111636. }
  111637. if (node.geometry && node.geometry.boundingSphere === null) {
  111638. node.geometry.computeBoundingSphere();
  111639. }
  111640. node.updateMatrixWorld();
  111641. let bs;
  111642. if (node.boundingSphere) {
  111643. bs = node.boundingSphere;
  111644. } else if (node.geometry && node.geometry.boundingSphere) {
  111645. bs = node.geometry.boundingSphere;
  111646. } else {
  111647. bs = node.boundingBox.getBoundingSphere(new Sphere());
  111648. }
  111649. let _factor = factor || 1;
  111650. bs = bs.clone().applyMatrix4(node.matrixWorld);
  111651. let radius = bs.radius;
  111652. let fovr = this.fov * Math.PI / 180;
  111653. if (this.aspect < 1) {
  111654. fovr = fovr * this.aspect;
  111655. }
  111656. let distanceFactor = Math.abs(radius / Math.sin(fovr / 2)) * _factor;
  111657. let offset = this.getWorldDirection(new Vector3()).multiplyScalar(-distanceFactor);
  111658. this.position.copy(bs.center.clone().add(offset));
  111659. };
  111660. Ray.prototype.distanceToPlaneWithNegative = function (plane) {
  111661. let denominator = plane.normal.dot(this.direction);
  111662. if (denominator === 0) {
  111663. // line is coplanar, return origin
  111664. if (plane.distanceToPoint(this.origin) === 0) {
  111665. return 0;
  111666. }
  111667. // Null is preferable to undefined since undefined means.... it is undefined
  111668. return null;
  111669. }
  111670. let t = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
  111671. return t;
  111672. };
  111673. const workerPool = new WorkerPool();
  111674. const version = {
  111675. major: 1,
  111676. minor: 8,
  111677. suffix: '.0'
  111678. };
  111679. let lru = new LRU();
  111680. console.log('Potree ' + version.major + '.' + version.minor + version.suffix);
  111681. let pointBudget = 1 * 1000 * 1000;
  111682. let framenumber = 0;
  111683. let numNodesLoading = 0;
  111684. let maxNodesLoading = 6;//4;
  111685. const debug = {};
  111686. exports.scriptPath = "";
  111687. if (document.currentScript && document.currentScript.src) {
  111688. exports.scriptPath = new URL(document.currentScript.src + '/..').href;
  111689. if (exports.scriptPath.slice(-1) === '/') {
  111690. exports.scriptPath = exports.scriptPath.slice(0, -1);
  111691. }
  111692. } 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)) })){
  111693. 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;
  111694. if (exports.scriptPath.slice(-1) === '/') {
  111695. exports.scriptPath = exports.scriptPath.slice(0, -1);
  111696. }
  111697. }else {
  111698. 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?');
  111699. }
  111700. let resourcePath = exports.scriptPath + '/resources';
  111701. //add:
  111702. async function loadFile(path, params , callback, onError){
  111703. params = params || {};
  111704. let fetchMethod = params.fetchMethod || 'get';
  111705. delete params.fetchMethod;
  111706. if(Potree.fileServer){
  111707. Potree.fileServer[fetchMethod](path, { params }).then(data=>{
  111708. if(data.data)data = data.data;
  111709. if(data.data)data = data.data; //融合页面getdataset需要查找两次data
  111710. callback && callback(data);
  111711. }).catch(onError);
  111712. }else {
  111713. try{
  111714. if(Object.keys(params).length > 0){
  111715. path+='?';
  111716. let index = 0;
  111717. for(let i in params){
  111718. if(index>0) path += '&';
  111719. path+=i; path+='='; path+=params[i];
  111720. index ++;
  111721. }
  111722. }
  111723. let info={};
  111724. if(fetchMethod == 'post')info.method = 'POST';
  111725. let response = await fetch(path, info);
  111726. let text = await response.text();
  111727. var data = JSON.parse(text);
  111728. if(data.data) data = data.data;
  111729. callback && callback(data);
  111730. return data
  111731. }catch(e){
  111732. console.log('loadFile出错', e);
  111733. onError && onError(e);
  111734. }
  111735. }
  111736. //查询: http://192.168.0.26:8080/doc.html#/default/filter-%E6%BC%AB%E6%B8%B8%E7%82%B9/filterUsingGET
  111737. }
  111738. async function loadDatasets(callback,sceneCode,onError){//之后直接把path写进来
  111739. let path;
  111740. sceneCode = sceneCode || Potree.settings.number;
  111741. if(Potree.fileServer){
  111742. path = `/laser/dataset/${sceneCode}/getDataSet`;
  111743. }else {
  111744. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/datasets`
  111745. //现在只能加载得了本地的了
  111746. path = `${Potree.settings.urls.prefix}/laser/dataset/${sceneCode}/getDataSet`;
  111747. //path = `${Potree.scriptPath}/data/${sceneCode}/getDataSet.json`
  111748. }
  111749. return loadFile(path, null, callback,onError)
  111750. }
  111751. //目前上传平面图后如果不点击保存按钮,数据还是旧的不生效
  111752. async function loadMapEntity(datasetId, force){
  111753. if(!Potree.settings.floorplanEnable && !force && Potree.fileServer )return /* 等待平面图类型定义好会加载 */
  111754. let loaded = 0;
  111755. let needLoads = datasetId == 'all' ? viewer.scene.pointclouds.map(e=>e.dataset_id) : [datasetId];
  111756. let callback = (dataset_id, floorplanType, data )=>{
  111757. if(!data || data.length == 0)return console.log('平面图没有数据', dataset_id, floorplanType )
  111758. //要防止旧的比新的先获取到导致覆盖新的,因为两种type随时可能切换
  111759. if(floorplanType != Potree.settings.floorplanType[dataset_id]) return //如果请求的floorplanType不是当前最新的floorplanType就返回
  111760. var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'floorplan_'+ dataset_id);
  111761. if(map){
  111762. viewer.mapViewer.mapLayer.removeMap(map);
  111763. }
  111764. var mapNew = viewer.mapViewer.mapLayer.addMapEntity(data.data || data, dataset_id);
  111765. if(map){
  111766. mapNew.visibleReasons = map.visibleReasons;
  111767. mapNew.unvisibleReasons = map.unvisibleReasons;
  111768. }
  111769. loaded ++;
  111770. };
  111771. needLoads.forEach(dataset_id=>{
  111772. let floorplanType = Potree.settings.floorplanType[dataset_id], prefix = '';
  111773. if(!Potree.fileServer){
  111774. prefix = Potree.settings.urls.prefix;
  111775. }
  111776. if(!floorplanType)return
  111777. var path;
  111778. /* if(Potree.fileServer){
  111779. path = `/laser/tiledMap/${Potree.settings.number}/tiledMap/${floorplanType}/${dataset_id}`
  111780. }else{
  111781. path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/tiled_maps`
  111782. } */
  111783. path = `${prefix}/laser/tiledMap/${Potree.settings.number}/tiledMap/${floorplanType}/${dataset_id}`;
  111784. Potree.settings.floorplanRequests[dataset_id] = true; //开始加载了
  111785. return loadFile(path, null, callback.bind(this, dataset_id, floorplanType) )
  111786. });
  111787. }
  111788. async function loadPanos(datasetId, callback){
  111789. var path;
  111790. //let query = `?datasetId=${datasetId}` //`?lat=${center.lat}&lon=${center.lon}&radius=200000`
  111791. if(Potree.fileServer){
  111792. path = `/laser/filter/${Potree.settings.number}/query`;
  111793. }else {
  111794. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/images/filter` + query
  111795. //path = `${Potree.scriptPath}/data/${Potree.settings.number}/panos-${datasetId}.json`
  111796. path = `${Potree.settings.urls.prefix}/laser/filter/${Potree.settings.number}/query`;
  111797. }
  111798. return loadFile(path, {datasetId:datasetId}, callback)
  111799. }
  111800. async function loadPanosInfo(callback){
  111801. var path;
  111802. if(Potree.fileServer){
  111803. }else {
  111804. path = `${Potree.scriptPath}/data/panoEdit/vision_edit.txt`;
  111805. }
  111806. return loadFile(path, null, callback)
  111807. }
  111808. async function loadImgVersion( callback){
  111809. var path;
  111810. //let query = `?datasetId=${datasetId}` //`?lat=${center.lat}&lon=${center.lon}&radius=200000`
  111811. /* if(Potree.fileServer){
  111812. path = `/laser/filter/${Potree.settings.number}/query`
  111813. }else{ */
  111814. path = `/laser/init/getSceneNumVersion/${Potree.settings.number}`;
  111815. //api/laser/init
  111816. //}
  111817. return loadFile(path, {fetchMethod:'post'}, callback, callback)
  111818. }
  111819. //site_model
  111820. /* {
  111821. "area": 2503.30551910935,
  111822. "attributes": {},
  111823. "center": [
  111824. 113.59568277455075,
  111825. 22.366566635195288,
  111826. 12.78751625
  111827. ],
  111828. "children": [],
  111829. "geometry_hash": 1891071345,
  111830. "id": 10,
  111831. "name": "港湾一号",
  111832. "parentId": null,
  111833. "polygon": {
  111834. "coordinates": [
  111835. [
  111836. [
  111837. 113.59590810534583,
  111838. 22.36679132753878
  111839. ],
  111840. [
  111841. 113.59590810534583,
  111842. 22.366807172528629
  111843. ],
  111844. [
  111845. 113.59545610274934,
  111846. 22.366807172528629
  111847. ],
  111848. [
  111849. 113.59545610274934,
  111850. 22.36679132753878
  111851. ]
  111852. ]
  111853. ],
  111854. "type": "Polygon"
  111855. },
  111856. "type": "BUILDING",
  111857. "volume": null,
  111858. "z_max": null,
  111859. "z_min": null
  111860. }
  111861. */
  111862. function Log$1(){
  111863. let args = Array.from(arguments);
  111864. let params = args[args.length-1];
  111865. if(params && params.font) {params = params.font, args.pop();}
  111866. else params = {};
  111867. let str = '', color = params.color || '#13f', fontSize = params.fontSize || 12;
  111868. args.forEach((e,i)=>{
  111869. i > 0 && (str += ' , ' );
  111870. /* if(params.toFixed && typeof e == 'number'){
  111871. e = e.toFixed(params.toFixed)
  111872. } */
  111873. if(params.toFixed ){
  111874. e = Potree.math.toPrecision(e, params.toFixed);
  111875. }
  111876. str += e; //object可以JSON.stringify,但不是所有都行
  111877. });
  111878. console.warn(`%c${str}`, `color:${color};font-size:${fontSize}px`);
  111879. }
  111880. function loadPointCloud$1(path, name, sceneCode, timeStamp, callback, onError){
  111881. let loaded = function(e){
  111882. e.pointcloud.name = name;
  111883. e.pointcloud.sceneCode = sceneCode; //对应4dkk的场景码
  111884. callback(e);
  111885. };
  111886. let promise = new Promise( resolve => {
  111887. // load pointcloud
  111888. if (!path){
  111889. // TODO: callback? comment? Hello? Bueller? Anyone?
  111890. } else if (path.indexOf('ept.json') > 0) {
  111891. EptLoader.load(path, function(geometry) {
  111892. if (!geometry) {
  111893. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  111894. }
  111895. else {
  111896. let pointcloud = new ExtendPointCloudOctree(geometry);
  111897. //loaded(pointcloud);
  111898. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  111899. }
  111900. });
  111901. } else if (path.indexOf('cloud.js') > 0) {
  111902. POCLoader.load(path, timeStamp, function (geometry) {
  111903. if (!geometry) {
  111904. //callback({type: 'loading_failed'});
  111905. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  111906. onError && onError();
  111907. } else {
  111908. let pointcloud = new ExtendPointCloudOctree(geometry);
  111909. // loaded(pointcloud);
  111910. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  111911. }
  111912. });
  111913. }/* else if (path.indexOf('metadata.json') > 0) { //部分浏览器(如uc)不支持NodeLoader中的1n的大数据写法
  111914. Potree.OctreeLoader.load(path).then(e => {
  111915. let geometry = e.geometry;
  111916. if(!geometry){
  111917. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  111918. }else{
  111919. let pointcloud = new ExtendPointCloudOctree(geometry);
  111920. let aPosition = pointcloud.getAttribute("position");
  111921. let material = pointcloud.material;
  111922. material.elevationRange = [
  111923. aPosition.range[0][2],
  111924. aPosition.range[1][2],
  111925. ];
  111926. // loaded(pointcloud);
  111927. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  111928. }
  111929. });
  111930. OctreeLoader.load(path, function (geometry) {
  111931. if (!geometry) {
  111932. //callback({type: 'loading_failed'});
  111933. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  111934. } else {
  111935. let pointcloud = new ExtendPointCloudOctree(geometry);
  111936. // loaded(pointcloud);
  111937. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  111938. }
  111939. });
  111940. } */else if (path.indexOf('.vpc') > 0) {
  111941. PointCloudArena4DGeometry.load(path, function (geometry) {
  111942. if (!geometry) {
  111943. //callback({type: 'loading_failed'});
  111944. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  111945. } else {
  111946. let pointcloud = new PointCloudArena4D(geometry);
  111947. // loaded(pointcloud);
  111948. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  111949. }
  111950. });
  111951. } else {
  111952. //callback({'type': 'loading_failed'});
  111953. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  111954. }
  111955. });
  111956. if(callback){
  111957. promise.then(pointcloud => {
  111958. loaded(pointcloud);
  111959. });
  111960. }else {
  111961. return promise;
  111962. }
  111963. };
  111964. // add selectgroup
  111965. (function($){
  111966. $.fn.extend({
  111967. selectgroup: function(args = {}){
  111968. let elGroup = $(this);
  111969. let rootID = elGroup.prop("id");
  111970. let groupID = `${rootID}`;
  111971. let groupTitle = (args.title !== undefined) ? args.title : "";
  111972. let elButtons = [];
  111973. elGroup.find("option").each((index, value) => {
  111974. let buttonID = $(value).prop("id");
  111975. let label = $(value).html();
  111976. let optionValue = $(value).prop("value");
  111977. let elButton = $(`
  111978. <span style="flex-grow: 1; display: inherit">
  111979. <label for="${buttonID}" class="ui-button" style="width: 100%; padding: .4em .1em">${label}</label>
  111980. <input type="radio" name="${groupID}" id="${buttonID}" value="${optionValue}" style="display: none"/>
  111981. </span>
  111982. `);
  111983. let elLabel = elButton.find("label");
  111984. let elInput = elButton.find("input");
  111985. elInput.change( () => {
  111986. elGroup.find("label").removeClass("ui-state-active");
  111987. elGroup.find("label").addClass("ui-state-default");
  111988. if(elInput.is(":checked")){
  111989. elLabel.addClass("ui-state-active");
  111990. }else {
  111991. //elLabel.addClass("ui-state-default");
  111992. }
  111993. });
  111994. elButtons.push(elButton);
  111995. });
  111996. let elFieldset = $(`
  111997. <fieldset style="border: none; margin: 0px; padding: 0px">
  111998. <legend>${groupTitle}</legend>
  111999. <span style="display: flex">
  112000. </span>
  112001. </fieldset>
  112002. `);
  112003. let elButtonContainer = elFieldset.find("span");
  112004. for(let elButton of elButtons){
  112005. elButtonContainer.append(elButton);
  112006. }
  112007. elButtonContainer.find("label").each( (index, value) => {
  112008. $(value).css("margin", "0px");
  112009. $(value).css("border-radius", "0px");
  112010. $(value).css("border", "1px solid black");
  112011. $(value).css("border-left", "none");
  112012. });
  112013. elButtonContainer.find("label:first").each( (index, value) => {
  112014. $(value).css("border-radius", "4px 0px 0px 4px");
  112015. });
  112016. elButtonContainer.find("label:last").each( (index, value) => {
  112017. $(value).css("border-radius", "0px 4px 4px 0px");
  112018. $(value).css("border-left", "none");
  112019. });
  112020. elGroup.empty();
  112021. elGroup.append(elFieldset);
  112022. }
  112023. });
  112024. })(jQuery);
  112025. //在这之后export的内容才赋值到Potree中
  112026. exports.Action = Action;
  112027. exports.Annotation = Annotation;
  112028. exports.Box3Helper = Box3Helper$1;
  112029. exports.BoxVolume = BoxVolume$1;
  112030. exports.CameraAnimation = CameraAnimation$1;
  112031. exports.CameraMode = CameraMode;
  112032. exports.ClassificationScheme = ClassificationScheme;
  112033. exports.ClipMethod = ClipMethod;
  112034. exports.ClipTask = ClipTask;
  112035. exports.ClipVolume = ClipVolume;
  112036. exports.ClippingTool = ClippingTool;
  112037. exports.ElevationGradientRepeat = ElevationGradientRepeat;
  112038. exports.Enum = Enum;
  112039. exports.EnumItem = EnumItem;
  112040. exports.EptBinaryLoader = EptBinaryLoader;
  112041. exports.EptKey = EptKey;
  112042. exports.EptLaszipLoader = EptLaszipLoader;
  112043. exports.EptLazBatcher = EptLazBatcher;
  112044. exports.EptLoader = EptLoader;
  112045. exports.EptZstandardLoader = EptZstandardLoader;
  112046. exports.EventDispatcher = EventDispatcher$1;
  112047. exports.ExtendPointCloudMaterial = ExtendPointCloudMaterial;
  112048. exports.ExtendPointCloudOctree = ExtendPointCloudOctree;
  112049. exports.ExtendScene = ExtendScene;
  112050. exports.EyeDomeLightingMaterial = EyeDomeLightingMaterial;
  112051. exports.Features = Features;
  112052. exports.FirstPersonControls = FirstPersonControls$1;
  112053. exports.GeoPackageLoader = GeoPackageLoader;
  112054. exports.Geopackage = Geopackage$1;
  112055. exports.Gradients = Gradients;
  112056. exports.HierarchicalSlider = HierarchicalSlider;
  112057. exports.Images360 = Images360;
  112058. exports.KeyCodes = KeyCodes;
  112059. exports.LRU = LRU;
  112060. exports.LRUItem = LRUItem;
  112061. exports.LengthUnits = LengthUnits;
  112062. exports.Log = Log$1;
  112063. exports.MOUSE = MOUSE$1;
  112064. exports.Measure = Measure$1;
  112065. exports.MeasuringTool = MeasuringTool;
  112066. exports.Message = Message;
  112067. exports.NodeLoader = NodeLoader;
  112068. exports.NormalizationEDLMaterial = NormalizationEDLMaterial;
  112069. exports.NormalizationMaterial = NormalizationMaterial;
  112070. exports.OctreeLoader = OctreeLoader;
  112071. exports.OrbitControls = OrbitControls$1;
  112072. exports.OrientedImage = OrientedImage;
  112073. exports.OrientedImageLoader = OrientedImageLoader;
  112074. exports.OrientedImages = OrientedImages;
  112075. exports.POCLoader = POCLoader;
  112076. exports.PointAttribute = PointAttribute;
  112077. exports.PointAttributeTypes = PointAttributeTypes;
  112078. exports.PointAttributes = PointAttributes;
  112079. exports.PointCloudEptGeometry = PointCloudEptGeometry;
  112080. exports.PointCloudEptGeometryNode = PointCloudEptGeometryNode;
  112081. exports.PointCloudOctreeGeometry = PointCloudOctreeGeometry;
  112082. exports.PointCloudOctreeGeometryNode = PointCloudOctreeGeometryNode;
  112083. exports.PointCloudSM = PointCloudSM;
  112084. exports.PointCloudTree = PointCloudTree;
  112085. exports.PointCloudTreeNode = PointCloudTreeNode;
  112086. exports.PointShape = PointShape$1;
  112087. exports.PointSizeType = PointSizeType;
  112088. exports.Points = Points$1;
  112089. exports.PolygonClipVolume = PolygonClipVolume;
  112090. exports.Profile = Profile;
  112091. exports.ProfileData = ProfileData;
  112092. exports.ProfileRequest = ProfileRequest;
  112093. exports.ProfileTool = ProfileTool;
  112094. exports.Renderer = Renderer;
  112095. exports.ScreenBoxSelectTool = ScreenBoxSelectTool;
  112096. exports.ShapefileLoader = ShapefileLoader;
  112097. exports.SphereVolume = SphereVolume$2;
  112098. exports.SpotLightHelper = SpotLightHelper$1;
  112099. exports.TextSprite = TextSprite$2;
  112100. exports.TransformationTool = TransformationTool;
  112101. exports.TreeType = TreeType;
  112102. exports.Utils = Utils;
  112103. exports.Version = Version;
  112104. exports.Viewer = Viewer;
  112105. exports.Volume = Volume$1;
  112106. exports.VolumeTool = VolumeTool;
  112107. exports.WorkerPool = WorkerPool;
  112108. exports.XHRFactory = XHRFactory;
  112109. exports.config = config$1;
  112110. exports.debug = debug;
  112111. exports.framenumber = framenumber;
  112112. exports.loadDatasets = loadDatasets;
  112113. exports.loadFile = loadFile;
  112114. exports.loadImgVersion = loadImgVersion;
  112115. exports.loadMapEntity = loadMapEntity;
  112116. exports.loadPanos = loadPanos;
  112117. exports.loadPanosInfo = loadPanosInfo;
  112118. exports.loadPointCloud = loadPointCloud$1;
  112119. exports.loadProject = loadProject;
  112120. exports.lru = lru;
  112121. exports.maxNodesLoading = maxNodesLoading;
  112122. exports.mergeEditStart = mergeEditStart;
  112123. exports.numNodesLoading = numNodesLoading;
  112124. exports.panoEditStart = panoEditStart;
  112125. exports.pointBudget = pointBudget;
  112126. exports.resourcePath = resourcePath;
  112127. exports.saveProject = saveProject;
  112128. exports.settings = settings;
  112129. exports.start = start;
  112130. exports.version = version;
  112131. exports.workerPool = workerPool;
  112132. Object.defineProperty(exports, '__esModule', { value: true });
  112133. })));
  112134. //# sourceMappingURL=potree.js.map